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.

60847 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 16
  46. /** Current Juce version number.
  47. Bits 16 to 32 = major version.
  48. Bits 8 to 16 = minor version.
  49. Bits 0 to 8 = point release (not currently used).
  50. See also SystemStats::getJUCEVersion() for a string version.
  51. */
  52. #define JUCE_VERSION ((JUCE_MAJOR_VERSION << 16) + (JUCE_MINOR_VERSION << 8) + JUCE_BUILDNUMBER)
  53. /*** Start of inlined file: juce_TargetPlatform.h ***/
  54. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  55. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  56. /* This file figures out which platform is being built, and defines some macros
  57. that the rest of the code can use for OS-specific compilation.
  58. Macros that will be set here are:
  59. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  60. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  61. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  62. - Either JUCE_INTEL or JUCE_PPC
  63. - Either JUCE_GCC or JUCE_MSVC
  64. */
  65. #if (defined (_WIN32) || defined (_WIN64))
  66. #define JUCE_WIN32 1
  67. #define JUCE_WINDOWS 1
  68. #elif defined (LINUX) || defined (__linux__)
  69. #define JUCE_LINUX 1
  70. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  71. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  72. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  73. #define JUCE_IPHONE 1
  74. #else
  75. #define JUCE_MAC 1
  76. #endif
  77. #else
  78. #error "Unknown platform!"
  79. #endif
  80. #if JUCE_WINDOWS
  81. #ifdef _MSC_VER
  82. #ifdef _WIN64
  83. #define JUCE_64BIT 1
  84. #else
  85. #define JUCE_32BIT 1
  86. #endif
  87. #endif
  88. #ifdef _DEBUG
  89. #define JUCE_DEBUG 1
  90. #endif
  91. #ifdef __MINGW32__
  92. #define JUCE_MINGW 1
  93. #endif
  94. /** If defined, this indicates that the processor is little-endian. */
  95. #define JUCE_LITTLE_ENDIAN 1
  96. #define JUCE_INTEL 1
  97. #endif
  98. #if JUCE_MAC
  99. #ifndef NDEBUG
  100. #define JUCE_DEBUG 1
  101. #endif
  102. #ifdef __LITTLE_ENDIAN__
  103. #define JUCE_LITTLE_ENDIAN 1
  104. #else
  105. #define JUCE_BIG_ENDIAN 1
  106. #endif
  107. #if defined (__ppc__) || defined (__ppc64__)
  108. #define JUCE_PPC 1
  109. #else
  110. #define JUCE_INTEL 1
  111. #endif
  112. #ifdef __LP64__
  113. #define JUCE_64BIT 1
  114. #else
  115. #define JUCE_32BIT 1
  116. #endif
  117. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  118. #error "Building for OSX 10.3 is no longer supported!"
  119. #endif
  120. #ifndef MAC_OS_X_VERSION_10_5
  121. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  122. #endif
  123. #endif
  124. #if JUCE_IPHONE
  125. #ifndef NDEBUG
  126. #define JUCE_DEBUG 1
  127. #endif
  128. #ifdef __LITTLE_ENDIAN__
  129. #define JUCE_LITTLE_ENDIAN 1
  130. #else
  131. #define JUCE_BIG_ENDIAN 1
  132. #endif
  133. #endif
  134. #if JUCE_LINUX
  135. #ifdef _DEBUG
  136. #define JUCE_DEBUG 1
  137. #endif
  138. // Allow override for big-endian Linux platforms
  139. #ifndef JUCE_BIG_ENDIAN
  140. #define JUCE_LITTLE_ENDIAN 1
  141. #endif
  142. #if defined (__LP64__) || defined (_LP64)
  143. #define JUCE_64BIT 1
  144. #else
  145. #define JUCE_32BIT 1
  146. #endif
  147. #define JUCE_INTEL 1
  148. #endif
  149. // Compiler type macros.
  150. #ifdef __GNUC__
  151. #define JUCE_GCC 1
  152. #elif defined (_MSC_VER)
  153. #define JUCE_MSVC 1
  154. #if _MSC_VER >= 1400
  155. #define JUCE_USE_INTRINSICS 1
  156. #endif
  157. #else
  158. #error unknown compiler
  159. #endif
  160. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  161. /*** End of inlined file: juce_TargetPlatform.h ***/
  162. // (sets up the various JUCE_WINDOWS, JUCE_MAC, etc flags)
  163. /*** Start of inlined file: juce_Config.h ***/
  164. #ifndef __JUCE_CONFIG_JUCEHEADER__
  165. #define __JUCE_CONFIG_JUCEHEADER__
  166. /*
  167. This file contains macros that enable/disable various JUCE features.
  168. */
  169. /** The name of the namespace that all Juce classes and functions will be
  170. put inside. If this is not defined, no namespace will be used.
  171. */
  172. #ifndef JUCE_NAMESPACE
  173. #define JUCE_NAMESPACE juce
  174. #endif
  175. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  176. project settings, but if you define this value, you can override this to force
  177. it to be true or false.
  178. */
  179. #ifndef JUCE_FORCE_DEBUG
  180. //#define JUCE_FORCE_DEBUG 0
  181. #endif
  182. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  183. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  184. Enabling it will also leave this turned on in release builds. When it's disabled,
  185. however, the jassert and jassertfalse macros will not be compiled in a
  186. release build.
  187. @see jassert, jassertfalse, Logger
  188. */
  189. #ifndef JUCE_LOG_ASSERTIONS
  190. #define JUCE_LOG_ASSERTIONS 0
  191. #endif
  192. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  193. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  194. on your Windows build machine.
  195. See the comments in the ASIOAudioIODevice class's header file for more
  196. info about this.
  197. */
  198. #ifndef JUCE_ASIO
  199. #define JUCE_ASIO 0
  200. #endif
  201. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  202. */
  203. #ifndef JUCE_WASAPI
  204. #define JUCE_WASAPI 0
  205. #endif
  206. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  207. */
  208. #ifndef JUCE_DIRECTSOUND
  209. #define JUCE_DIRECTSOUND 1
  210. #endif
  211. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  212. #ifndef JUCE_ALSA
  213. #define JUCE_ALSA 1
  214. #endif
  215. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  216. #ifndef JUCE_JACK
  217. #define JUCE_JACK 0
  218. #endif
  219. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  220. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  221. installed, and its header files will need to be on your include path.
  222. */
  223. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IPHONE || (JUCE_WINDOWS && ! JUCE_MSVC))
  224. #define JUCE_QUICKTIME 0
  225. #endif
  226. #if (JUCE_IPHONE || JUCE_LINUX) && JUCE_QUICKTIME
  227. #undef JUCE_QUICKTIME
  228. #endif
  229. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  230. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  231. */
  232. #ifndef JUCE_OPENGL
  233. #define JUCE_OPENGL 1
  234. #endif
  235. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  236. If your app doesn't need to read FLAC files, you might want to disable this to
  237. reduce the size of your codebase and build time.
  238. */
  239. #ifndef JUCE_USE_FLAC
  240. #define JUCE_USE_FLAC 1
  241. #endif
  242. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  243. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  244. reduce the size of your codebase and build time.
  245. */
  246. #ifndef JUCE_USE_OGGVORBIS
  247. #define JUCE_USE_OGGVORBIS 1
  248. #endif
  249. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  250. Unless you're using CD-burning, you should probably turn this flag off to
  251. reduce code size.
  252. */
  253. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  254. #define JUCE_USE_CDBURNER 0
  255. #endif
  256. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  257. Unless you're using CD-reading, you should probably turn this flag off to
  258. reduce code size.
  259. */
  260. #ifndef JUCE_USE_CDREADER
  261. #define JUCE_USE_CDREADER 0
  262. #endif
  263. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  264. */
  265. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  266. #define JUCE_USE_CAMERA 0
  267. #endif
  268. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  269. gets repainted will flash in a random colour, so that you can check exactly how much and how
  270. often your components are being drawn.
  271. */
  272. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  273. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  274. #endif
  275. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  276. Unless you specifically want to disable this, it's best to leave this option turned on.
  277. */
  278. #ifndef JUCE_USE_XINERAMA
  279. #define JUCE_USE_XINERAMA 1
  280. #endif
  281. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  282. turned on unless you have a good reason to disable it.
  283. */
  284. #ifndef JUCE_USE_XSHM
  285. #define JUCE_USE_XSHM 1
  286. #endif
  287. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  288. */
  289. #ifndef JUCE_USE_XRENDER
  290. #define JUCE_USE_XRENDER 0
  291. #endif
  292. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  293. unless you have a good reason to disable it.
  294. */
  295. #ifndef JUCE_USE_XCURSOR
  296. #define JUCE_USE_XCURSOR 1
  297. #endif
  298. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  299. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  300. you're building a plugin hosting app.
  301. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  302. */
  303. #ifndef JUCE_PLUGINHOST_VST
  304. #define JUCE_PLUGINHOST_VST 0
  305. #endif
  306. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  307. of course, and should only be enabled if you're building a plugin hosting app.
  308. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  309. */
  310. #ifndef JUCE_PLUGINHOST_AU
  311. #define JUCE_PLUGINHOST_AU 0
  312. #endif
  313. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  314. This should be enabled if you're writing a console application.
  315. */
  316. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  317. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  318. #endif
  319. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  320. If you're not using any embedded web-pages, turning this off may reduce your code size.
  321. */
  322. #ifndef JUCE_WEB_BROWSER
  323. #define JUCE_WEB_BROWSER 1
  324. #endif
  325. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  326. Carbon isn't required for a normal app, but may be needed by specialised classes like
  327. plugin-hosts, which support older APIs.
  328. */
  329. #ifndef JUCE_SUPPORT_CARBON
  330. #define JUCE_SUPPORT_CARBON 1
  331. #endif
  332. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  333. You might need to tweak this if you're linking to an external zlib library in your app,
  334. but for normal apps, this option should be left alone.
  335. */
  336. #ifndef JUCE_INCLUDE_ZLIB_CODE
  337. #define JUCE_INCLUDE_ZLIB_CODE 1
  338. #endif
  339. #ifndef JUCE_INCLUDE_FLAC_CODE
  340. #define JUCE_INCLUDE_FLAC_CODE 1
  341. #endif
  342. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  343. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  344. #endif
  345. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  346. #define JUCE_INCLUDE_PNGLIB_CODE 1
  347. #endif
  348. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  349. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  350. #endif
  351. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  352. (Currently, this only affects Windows builds in debug mode).
  353. */
  354. #ifndef JUCE_CHECK_MEMORY_LEAKS
  355. #define JUCE_CHECK_MEMORY_LEAKS 1
  356. #endif
  357. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  358. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  359. are passed to the JUCEApplication::unhandledException() callback for logging.
  360. */
  361. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  362. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  363. #endif
  364. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  365. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  366. #undef JUCE_QUICKTIME
  367. #define JUCE_QUICKTIME 0
  368. #undef JUCE_OPENGL
  369. #define JUCE_OPENGL 0
  370. #undef JUCE_USE_CDBURNER
  371. #define JUCE_USE_CDBURNER 0
  372. #undef JUCE_USE_CDREADER
  373. #define JUCE_USE_CDREADER 0
  374. #undef JUCE_WEB_BROWSER
  375. #define JUCE_WEB_BROWSER 0
  376. #undef JUCE_PLUGINHOST_AU
  377. #define JUCE_PLUGINHOST_AU 0
  378. #undef JUCE_PLUGINHOST_VST
  379. #define JUCE_PLUGINHOST_VST 0
  380. #endif
  381. #endif
  382. /*** End of inlined file: juce_Config.h ***/
  383. #ifdef JUCE_NAMESPACE
  384. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  385. #define END_JUCE_NAMESPACE }
  386. #else
  387. #define BEGIN_JUCE_NAMESPACE
  388. #define END_JUCE_NAMESPACE
  389. #endif
  390. /*** Start of inlined file: juce_PlatformDefs.h ***/
  391. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  392. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  393. /* This file defines miscellaneous macros for debugging, assertions, etc.
  394. */
  395. #ifdef JUCE_FORCE_DEBUG
  396. #undef JUCE_DEBUG
  397. #if JUCE_FORCE_DEBUG
  398. #define JUCE_DEBUG 1
  399. #endif
  400. #endif
  401. /** This macro defines the C calling convention used as the standard for Juce calls. */
  402. #if JUCE_MSVC
  403. #define JUCE_CALLTYPE __stdcall
  404. #else
  405. #define JUCE_CALLTYPE
  406. #endif
  407. // Debugging and assertion macros
  408. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  409. #if JUCE_LOG_ASSERTIONS
  410. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  411. #elif JUCE_DEBUG
  412. #define juce_LogCurrentAssertion std::cerr << "JUCE Assertion failure in " << __FILE__ << ", line " << __LINE__ << std::endl;
  413. #else
  414. #define juce_LogCurrentAssertion
  415. #endif
  416. #if JUCE_DEBUG
  417. // If debugging is enabled..
  418. /** Writes a string to the standard error stream.
  419. This is only compiled in a debug build.
  420. @see Logger::outputDebugString
  421. */
  422. #define DBG(dbgtext) Logger::outputDebugString (dbgtext);
  423. // Assertions..
  424. #if JUCE_WINDOWS || DOXYGEN
  425. #if JUCE_USE_INTRINSICS
  426. #pragma intrinsic (__debugbreak)
  427. /** This will try to break the debugger if one is currently hosting this app.
  428. @see jassert()
  429. */
  430. #define juce_breakDebugger __debugbreak();
  431. #elif JUCE_GCC
  432. /** This will try to break the debugger if one is currently hosting this app.
  433. @see jassert()
  434. */
  435. #define juce_breakDebugger asm("int $3");
  436. #else
  437. /** This will try to break the debugger if one is currently hosting this app.
  438. @see jassert()
  439. */
  440. #define juce_breakDebugger { __asm int 3 }
  441. #endif
  442. #elif JUCE_MAC
  443. #define juce_breakDebugger Debugger();
  444. #elif JUCE_IPHONE
  445. #define juce_breakDebugger kill (0, SIGTRAP);
  446. #elif JUCE_LINUX
  447. #define juce_breakDebugger kill (0, SIGTRAP);
  448. #endif
  449. /** This will always cause an assertion failure.
  450. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled
  451. in juce_Config.h).
  452. @see jassert()
  453. */
  454. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  455. /** Platform-independent assertion macro.
  456. This gets optimised out when not being built with debugging turned on.
  457. Be careful not to call any functions within its arguments that are vital to
  458. the behaviour of the program, because these won't get called in the release
  459. build.
  460. @see jassertfalse
  461. */
  462. #define jassert(expression) { if (! (expression)) jassertfalse; }
  463. #else
  464. // If debugging is disabled, these dummy debug and assertion macros are used..
  465. #define DBG(dbgtext)
  466. #define jassertfalse { juce_LogCurrentAssertion }
  467. #if JUCE_LOG_ASSERTIONS
  468. #define jassert(expression) { if (! (expression)) jassertfalse; }
  469. #else
  470. #define jassert(a) { }
  471. #endif
  472. #endif
  473. #ifndef DOXYGEN
  474. template <bool b> struct JuceStaticAssert;
  475. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  476. #endif
  477. /** A compile-time assertion macro.
  478. If the expression parameter is false, the macro will cause a compile error.
  479. */
  480. #define static_jassert(expression) JuceStaticAssert<expression>::dummy();
  481. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  482. #define JUCE_TRY try
  483. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  484. object so they can be logged by the application if it wants to.
  485. */
  486. #define JUCE_CATCH_EXCEPTION \
  487. catch (const std::exception& e) \
  488. { \
  489. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  490. } \
  491. catch (...) \
  492. { \
  493. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  494. }
  495. #define JUCE_CATCH_ALL catch (...) {}
  496. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse; }
  497. #else
  498. #define JUCE_TRY
  499. #define JUCE_CATCH_EXCEPTION
  500. #define JUCE_CATCH_ALL
  501. #define JUCE_CATCH_ALL_ASSERT
  502. #endif
  503. // Macros for inlining.
  504. #if JUCE_MSVC
  505. /** A platform-independent way of forcing an inline function.
  506. Use the syntax: @code
  507. forcedinline void myfunction (int x)
  508. @endcode
  509. */
  510. #ifndef JUCE_DEBUG
  511. #define forcedinline __forceinline
  512. #else
  513. #define forcedinline inline
  514. #endif
  515. #define JUCE_ALIGN(bytes) __declspec (align (bytes))
  516. #else
  517. /** A platform-independent way of forcing an inline function.
  518. Use the syntax: @code
  519. forcedinline void myfunction (int x)
  520. @endcode
  521. */
  522. #ifndef JUCE_DEBUG
  523. #define forcedinline inline __attribute__((always_inline))
  524. #else
  525. #define forcedinline inline
  526. #endif
  527. #define JUCE_ALIGN(bytes) __attribute__ ((aligned (bytes)))
  528. #endif
  529. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  530. /*** End of inlined file: juce_PlatformDefs.h ***/
  531. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  532. #if JUCE_MSVC
  533. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  534. #pragma warning (disable: 4284 4786) // (spurious VC6 warnings)
  535. #endif
  536. #pragma warning (push)
  537. #pragma warning (disable: 4514 4245 4100)
  538. #endif
  539. #include <cstdlib>
  540. #include <cstdarg>
  541. #include <climits>
  542. #include <limits>
  543. #include <cmath>
  544. #include <cwchar>
  545. #include <stdexcept>
  546. #include <typeinfo>
  547. #include <cstring>
  548. #include <cstdio>
  549. #include <iostream>
  550. #if JUCE_USE_INTRINSICS
  551. #include <intrin.h>
  552. #endif
  553. #if JUCE_MAC || JUCE_IPHONE
  554. #include <libkern/OSAtomic.h>
  555. #endif
  556. #if JUCE_LINUX
  557. #include <signal.h>
  558. #if __INTEL_COMPILER
  559. #if __ia64__
  560. #include <ia64intrin.h>
  561. #else
  562. #include <ia32intrin.h>
  563. #endif
  564. #endif
  565. #endif
  566. #if JUCE_MSVC && JUCE_DEBUG
  567. #include <crtdbg.h>
  568. #endif
  569. #if JUCE_MSVC
  570. #include <malloc.h>
  571. #pragma warning (pop)
  572. #if ! JUCE_PUBLIC_INCLUDES
  573. #pragma warning (4: 4511 4512 4100) // (enable some warnings that are turned off in VC8)
  574. #endif
  575. #endif
  576. // DLL building settings on Win32
  577. #if JUCE_MSVC
  578. #ifdef JUCE_DLL_BUILD
  579. #define JUCE_API __declspec (dllexport)
  580. #pragma warning (disable: 4251)
  581. #elif defined (JUCE_DLL)
  582. #define JUCE_API __declspec (dllimport)
  583. #pragma warning (disable: 4251)
  584. #endif
  585. #elif defined (__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
  586. #ifdef JUCE_DLL_BUILD
  587. #define JUCE_API __attribute__ ((visibility("default")))
  588. #endif
  589. #endif
  590. #ifndef JUCE_API
  591. /** This macro is added to all juce public class declarations. */
  592. #define JUCE_API
  593. #endif
  594. /** This macro is added to all juce public function declarations. */
  595. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  596. // Now include some basics that are needed by most of the Juce classes...
  597. BEGIN_JUCE_NAMESPACE
  598. extern bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger();
  599. #if JUCE_LOG_ASSERTIONS
  600. extern void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw();
  601. #endif
  602. /*** Start of inlined file: juce_Memory.h ***/
  603. #ifndef __JUCE_MEMORY_JUCEHEADER__
  604. #define __JUCE_MEMORY_JUCEHEADER__
  605. /*
  606. This file defines the various juce_malloc(), juce_free() macros that should be used in
  607. preference to the standard calls.
  608. */
  609. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  610. #ifndef JUCE_DLL
  611. // Win32 debug non-DLL versions..
  612. /** This should be used instead of calling malloc directly.
  613. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  614. */
  615. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  616. /** This should be used instead of calling calloc directly.
  617. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  618. */
  619. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  620. /** This should be used instead of calling realloc directly.
  621. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  622. */
  623. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  624. /** This should be used instead of calling free directly.
  625. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  626. */
  627. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  628. #else
  629. // Win32 debug DLL versions..
  630. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  631. // way all juce calls in the DLL and in the host API will all use the same allocator.
  632. extern JUCE_API void* juce_DebugMalloc (const int size, const char* file, const int line);
  633. extern JUCE_API void* juce_DebugCalloc (const int size, const char* file, const int line);
  634. extern JUCE_API void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line);
  635. extern JUCE_API void juce_DebugFree (void* const block);
  636. /** This should be used instead of calling malloc directly.
  637. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  638. */
  639. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  640. /** This should be used instead of calling calloc directly.
  641. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  642. */
  643. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  644. /** This should be used instead of calling realloc directly.
  645. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  646. */
  647. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  648. /** This should be used instead of calling free directly.
  649. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  650. */
  651. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  652. #endif
  653. #if ! defined (_AFXDLL)
  654. /** This macro can be added to classes to add extra debugging information to the memory
  655. allocated for them, so you can see the type of objects involved when there's a dump
  656. of leaked objects at program shutdown. (Only works on win32 at the moment).
  657. */
  658. #define juce_UseDebuggingNewOperator \
  659. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  660. static void* operator new (size_t, void* p) { return p; } \
  661. static void operator delete (void* p) { juce_free (p); } \
  662. static void operator delete (void*, void*) { }
  663. #endif
  664. #elif defined (JUCE_DLL)
  665. // Win32 DLL (release) versions..
  666. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  667. // way all juce calls in the DLL and in the host API will all use the same allocator.
  668. extern JUCE_API void* juce_Malloc (const int size);
  669. extern JUCE_API void* juce_Calloc (const int size);
  670. extern JUCE_API void* juce_Realloc (void* const block, const int size);
  671. extern JUCE_API void juce_Free (void* const block);
  672. /** This should be used instead of calling malloc directly.
  673. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  674. */
  675. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  676. /** This should be used instead of calling calloc directly.
  677. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  678. */
  679. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  680. /** This should be used instead of calling realloc directly.
  681. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  682. */
  683. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  684. /** This should be used instead of calling free directly.
  685. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  686. */
  687. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  688. #define juce_UseDebuggingNewOperator \
  689. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  690. static void* operator new (size_t, void* p) { return p; } \
  691. static void operator delete (void* p) { juce_free (p); } \
  692. static void operator delete (void*, void*) { }
  693. #else
  694. // Mac, Linux and Win32 (release) versions..
  695. /** This should be used instead of calling malloc directly.
  696. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  697. */
  698. #define juce_malloc(numBytes) malloc (numBytes)
  699. /** This should be used instead of calling calloc directly.
  700. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  701. */
  702. #define juce_calloc(numBytes) calloc (1, numBytes)
  703. /** This should be used instead of calling realloc directly.
  704. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  705. */
  706. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  707. /** This should be used instead of calling free directly.
  708. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  709. */
  710. #define juce_free(location) free (location)
  711. #endif
  712. /** This macro can be added to classes to add extra debugging information to the memory
  713. allocated for them, so you can see the type of objects involved when there's a dump
  714. of leaked objects at program shutdown. (Only works on win32 at the moment).
  715. Note that if you create a class that inherits from a class that uses this macro,
  716. your class must also use the macro, otherwise you'll probably get compile errors
  717. because of ambiguous new operators.
  718. Most of the JUCE classes use it, so see these for examples of where it should go.
  719. */
  720. #ifndef juce_UseDebuggingNewOperator
  721. #define juce_UseDebuggingNewOperator
  722. #endif
  723. #if JUCE_MSVC
  724. /** This is a compiler-independent way of declaring a variable as being thread-local.
  725. E.g.
  726. @code
  727. juce_ThreadLocal int myVariable;
  728. @endcode
  729. */
  730. #define juce_ThreadLocal __declspec(thread)
  731. #else
  732. #define juce_ThreadLocal __thread
  733. #endif
  734. #if JUCE_MINGW
  735. /** This allocator is not defined in mingw gcc. */
  736. #define alloca __builtin_alloca
  737. #endif
  738. /** Clears a block of memory. */
  739. inline void zeromem (void* memory, size_t numBytes) { memset (memory, 0, numBytes); }
  740. /** Clears a reference to a local structure. */
  741. template <typename Type>
  742. inline void zerostruct (Type& structure) { memset (&structure, 0, sizeof (structure)); }
  743. /** A handy function that calls delete on a pointer if it's non-zero, and then sets
  744. the pointer to null.
  745. */
  746. template <typename Type>
  747. inline void deleteAndZero (Type& pointer) { delete pointer; pointer = 0; }
  748. #endif // __JUCE_MEMORY_JUCEHEADER__
  749. /*** End of inlined file: juce_Memory.h ***/
  750. /*** Start of inlined file: juce_MathsFunctions.h ***/
  751. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  752. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  753. /*
  754. This file sets up some handy mathematical typdefs and functions.
  755. */
  756. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  757. /** A platform-independent 8-bit signed integer type. */
  758. typedef signed char int8;
  759. /** A platform-independent 8-bit unsigned integer type. */
  760. typedef unsigned char uint8;
  761. /** A platform-independent 16-bit signed integer type. */
  762. typedef signed short int16;
  763. /** A platform-independent 16-bit unsigned integer type. */
  764. typedef unsigned short uint16;
  765. /** A platform-independent 32-bit signed integer type. */
  766. typedef signed int int32;
  767. /** A platform-independent 32-bit unsigned integer type. */
  768. typedef unsigned int uint32;
  769. #if JUCE_MSVC
  770. /** A platform-independent 64-bit integer type. */
  771. typedef __int64 int64;
  772. /** A platform-independent 64-bit unsigned integer type. */
  773. typedef unsigned __int64 uint64;
  774. /** A platform-independent macro for writing 64-bit literals, needed because
  775. different compilers have different syntaxes for this.
  776. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  777. GCC, or 0x1000000000 for MSVC.
  778. */
  779. #define literal64bit(longLiteral) ((__int64) longLiteral)
  780. #else
  781. /** A platform-independent 64-bit integer type. */
  782. typedef long long int64;
  783. /** A platform-independent 64-bit unsigned integer type. */
  784. typedef unsigned long long uint64;
  785. /** A platform-independent macro for writing 64-bit literals, needed because
  786. different compilers have different syntaxes for this.
  787. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  788. GCC, or 0x1000000000 for MSVC.
  789. */
  790. #define literal64bit(longLiteral) (longLiteral##LL)
  791. #endif
  792. #if JUCE_64BIT
  793. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  794. typedef int64 pointer_sized_int;
  795. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  796. typedef uint64 pointer_sized_uint;
  797. #elif _MSC_VER >= 1300
  798. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  799. typedef _W64 int pointer_sized_int;
  800. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  801. typedef _W64 unsigned int pointer_sized_uint;
  802. #else
  803. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  804. typedef int pointer_sized_int;
  805. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  806. typedef unsigned int pointer_sized_uint;
  807. #endif
  808. /** A platform-independent unicode character type. */
  809. typedef wchar_t juce_wchar;
  810. // Some indispensible min/max functions
  811. /** Returns the larger of two values. */
  812. template <typename Type>
  813. inline Type jmax (const Type a, const Type b) { return (a < b) ? b : a; }
  814. /** Returns the larger of three values. */
  815. template <typename Type>
  816. inline Type jmax (const Type a, const Type b, const Type c) { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  817. /** Returns the larger of four values. */
  818. template <typename Type>
  819. inline Type jmax (const Type a, const Type b, const Type c, const Type d) { return jmax (a, jmax (b, c, d)); }
  820. /** Returns the smaller of two values. */
  821. template <typename Type>
  822. inline Type jmin (const Type a, const Type b) { return (b < a) ? b : a; }
  823. /** Returns the smaller of three values. */
  824. template <typename Type>
  825. inline Type jmin (const Type a, const Type b, const Type c) { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
  826. /** Returns the smaller of four values. */
  827. template <typename Type>
  828. inline Type jmin (const Type a, const Type b, const Type c, const Type d) { return jmin (a, jmin (b, c, d)); }
  829. /** Constrains a value to keep it within a given range.
  830. This will check that the specified value lies between the lower and upper bounds
  831. specified, and if not, will return the nearest value that would be in-range. Effectively,
  832. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  833. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  834. the results will be unpredictable.
  835. @param lowerLimit the minimum value to return
  836. @param upperLimit the maximum value to return
  837. @param valueToConstrain the value to try to return
  838. @returns the closest value to valueToConstrain which lies between lowerLimit
  839. and upperLimit (inclusive)
  840. @see jlimit0To, jmin, jmax
  841. */
  842. template <typename Type>
  843. inline Type jlimit (const Type lowerLimit,
  844. const Type upperLimit,
  845. const Type valueToConstrain) throw()
  846. {
  847. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  848. return (valueToConstrain < lowerLimit) ? lowerLimit
  849. : ((upperLimit < valueToConstrain) ? upperLimit
  850. : valueToConstrain);
  851. }
  852. /** Handy function to swap two values over.
  853. */
  854. template <typename Type>
  855. inline void swapVariables (Type& variable1, Type& variable2)
  856. {
  857. const Type tempVal = variable1;
  858. variable1 = variable2;
  859. variable2 = tempVal;
  860. }
  861. /** Handy function for getting the number of elements in a simple const C array.
  862. E.g.
  863. @code
  864. static int myArray[] = { 1, 2, 3 };
  865. int numElements = numElementsInArray (myArray) // returns 3
  866. @endcode
  867. */
  868. template <typename Type>
  869. inline int numElementsInArray (Type& array) { return static_cast<int> (sizeof (array) / sizeof (array[0])); }
  870. // Some useful maths functions that aren't always present with all compilers and build settings.
  871. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  872. versions of these functions of various platforms and compilers. */
  873. inline double juce_hypot (double a, double b)
  874. {
  875. #if JUCE_WINDOWS
  876. return _hypot (a, b);
  877. #else
  878. return hypot (a, b);
  879. #endif
  880. }
  881. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  882. versions of these functions of various platforms and compilers. */
  883. inline float juce_hypotf (float a, float b) throw()
  884. {
  885. #if JUCE_WINDOWS
  886. return (float) _hypot (a, b);
  887. #else
  888. return hypotf (a, b);
  889. #endif
  890. }
  891. /** 64-bit abs function. */
  892. inline int64 abs64 (const int64 n) throw()
  893. {
  894. return (n >= 0) ? n : -n;
  895. }
  896. /** This templated negate function will negate pointers as well as integers */
  897. template <typename Type>
  898. inline Type juce_negate (Type n) throw()
  899. {
  900. return sizeof (Type) == 1 ? (Type) -(char) n
  901. : (sizeof (Type) == 2 ? (Type) -(short) n
  902. : (sizeof (Type) == 4 ? (Type) -(int) n
  903. : ((Type) -(int64) n)));
  904. }
  905. /** This templated negate function will negate pointers as well as integers */
  906. template <typename Type>
  907. inline Type* juce_negate (Type* n) throw()
  908. {
  909. return (Type*) -(pointer_sized_int) n;
  910. }
  911. /** A predefined value for Pi, at double-precision.
  912. @see float_Pi
  913. */
  914. const double double_Pi = 3.1415926535897932384626433832795;
  915. /** A predefined value for Pi, at sngle-precision.
  916. @see double_Pi
  917. */
  918. const float float_Pi = 3.14159265358979323846f;
  919. /** The isfinite() method seems to vary between platforms, so this is a
  920. platform-independent function for it.
  921. */
  922. template <typename FloatingPointType>
  923. inline bool juce_isfinite (FloatingPointType value)
  924. {
  925. #if JUCE_WINDOWS
  926. return _finite (value);
  927. #else
  928. return std::isfinite (value);
  929. #endif
  930. }
  931. /** Fast floating-point-to-integer conversion.
  932. This is faster than using the normal c++ cast to convert a float to an int, and
  933. it will round the value to the nearest integer, rather than rounding it down
  934. like the normal cast does.
  935. Note that this routine gets its speed at the expense of some accuracy, and when
  936. rounding values whose floating point component is exactly 0.5, odd numbers and
  937. even numbers will be rounded up or down differently.
  938. */
  939. template <typename FloatType>
  940. inline int roundToInt (const FloatType value) throw()
  941. {
  942. union { int asInt[2]; double asDouble; } n;
  943. n.asDouble = ((double) value) + 6755399441055744.0;
  944. #if JUCE_BIG_ENDIAN
  945. return n.asInt [1];
  946. #else
  947. return n.asInt [0];
  948. #endif
  949. }
  950. /** Fast floating-point-to-integer conversion.
  951. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  952. fine for values above zero, but negative numbers are rounded the wrong way.
  953. */
  954. inline int roundToIntAccurate (const double value) throw()
  955. {
  956. return roundToInt (value + 1.5e-8);
  957. }
  958. /** Fast floating-point-to-integer conversion.
  959. This is faster than using the normal c++ cast to convert a double to an int, and
  960. it will round the value to the nearest integer, rather than rounding it down
  961. like the normal cast does.
  962. Note that this routine gets its speed at the expense of some accuracy, and when
  963. rounding values whose floating point component is exactly 0.5, odd numbers and
  964. even numbers will be rounded up or down differently. For a more accurate conversion,
  965. see roundDoubleToIntAccurate().
  966. */
  967. inline int roundDoubleToInt (const double value) throw()
  968. {
  969. return roundToInt (value);
  970. }
  971. /** Fast floating-point-to-integer conversion.
  972. This is faster than using the normal c++ cast to convert a float to an int, and
  973. it will round the value to the nearest integer, rather than rounding it down
  974. like the normal cast does.
  975. Note that this routine gets its speed at the expense of some accuracy, and when
  976. rounding values whose floating point component is exactly 0.5, odd numbers and
  977. even numbers will be rounded up or down differently.
  978. */
  979. inline int roundFloatToInt (const float value) throw()
  980. {
  981. return roundToInt (value);
  982. }
  983. /** This namespace contains a few template classes for helping work out class type variations.
  984. */
  985. namespace TypeHelpers
  986. {
  987. #if defined (_MSC_VER) && _MSC_VER <= 1400
  988. #define PARAMETER_TYPE(a) a
  989. #else
  990. /** The ParameterType struct is used to find the best type to use when passing some kind
  991. of object as a parameter.
  992. Of course, this is only likely to be useful in certain esoteric template situations.
  993. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  994. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  995. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  996. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  997. pass-by-value, but passing objects as a const reference, to avoid copying.
  998. */
  999. template <typename Type> struct ParameterType { typedef const Type& type; };
  1000. #if ! DOXYGEN
  1001. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  1002. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  1003. template <> struct ParameterType <char> { typedef char type; };
  1004. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  1005. template <> struct ParameterType <short> { typedef short type; };
  1006. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  1007. template <> struct ParameterType <int> { typedef int type; };
  1008. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  1009. template <> struct ParameterType <long> { typedef long type; };
  1010. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  1011. template <> struct ParameterType <int64> { typedef int64 type; };
  1012. template <> struct ParameterType <uint64> { typedef uint64 type; };
  1013. template <> struct ParameterType <bool> { typedef bool type; };
  1014. template <> struct ParameterType <float> { typedef float type; };
  1015. template <> struct ParameterType <double> { typedef double type; };
  1016. #endif
  1017. /** A helpful macro to simplify the use of the ParameterType template.
  1018. @see ParameterType
  1019. */
  1020. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  1021. #endif
  1022. }
  1023. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  1024. /*** End of inlined file: juce_MathsFunctions.h ***/
  1025. /*** Start of inlined file: juce_ByteOrder.h ***/
  1026. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  1027. #define __JUCE_BYTEORDER_JUCEHEADER__
  1028. /** Contains static methods for converting the byte order between different
  1029. endiannesses.
  1030. */
  1031. class JUCE_API ByteOrder
  1032. {
  1033. public:
  1034. /** Swaps the upper and lower bytes of a 16-bit integer. */
  1035. static uint16 swap (uint16 value);
  1036. /** Reverses the order of the 4 bytes in a 32-bit integer. */
  1037. static uint32 swap (uint32 value);
  1038. /** Reverses the order of the 8 bytes in a 64-bit integer. */
  1039. static uint64 swap (uint64 value);
  1040. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  1041. static uint16 swapIfBigEndian (uint16 value);
  1042. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  1043. static uint32 swapIfBigEndian (uint32 value);
  1044. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  1045. static uint64 swapIfBigEndian (uint64 value);
  1046. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  1047. static uint16 swapIfLittleEndian (uint16 value);
  1048. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  1049. static uint32 swapIfLittleEndian (uint32 value);
  1050. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  1051. static uint64 swapIfLittleEndian (uint64 value);
  1052. /** Turns 4 bytes into a little-endian integer. */
  1053. static uint32 littleEndianInt (const void* bytes);
  1054. /** Turns 2 bytes into a little-endian integer. */
  1055. static uint16 littleEndianShort (const void* bytes);
  1056. /** Turns 4 bytes into a big-endian integer. */
  1057. static uint32 bigEndianInt (const void* bytes);
  1058. /** Turns 2 bytes into a big-endian integer. */
  1059. static uint16 bigEndianShort (const void* bytes);
  1060. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1061. static int littleEndian24Bit (const char* bytes);
  1062. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1063. static int bigEndian24Bit (const char* bytes);
  1064. /** Copies a 24-bit number to 3 little-endian bytes. */
  1065. static void littleEndian24BitToChars (int value, char* destBytes);
  1066. /** Copies a 24-bit number to 3 big-endian bytes. */
  1067. static void bigEndian24BitToChars (int value, char* destBytes);
  1068. /** Returns true if the current CPU is big-endian. */
  1069. static bool isBigEndian();
  1070. private:
  1071. ByteOrder();
  1072. ByteOrder (const ByteOrder&);
  1073. ByteOrder& operator= (const ByteOrder&);
  1074. };
  1075. #if JUCE_USE_INTRINSICS
  1076. #pragma intrinsic (_byteswap_ulong)
  1077. #endif
  1078. inline uint16 ByteOrder::swap (uint16 n)
  1079. {
  1080. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  1081. return static_cast <uint16> (_byteswap_ushort (n));
  1082. #else
  1083. return static_cast <uint16> ((n << 8) | (n >> 8));
  1084. #endif
  1085. }
  1086. inline uint32 ByteOrder::swap (uint32 n)
  1087. {
  1088. #if JUCE_MAC || JUCE_IPHONE
  1089. return OSSwapInt32 (n);
  1090. #elif JUCE_GCC
  1091. asm("bswap %%eax" : "=a"(n) : "a"(n));
  1092. return n;
  1093. #elif JUCE_USE_INTRINSICS
  1094. return _byteswap_ulong (n);
  1095. #else
  1096. __asm {
  1097. mov eax, n
  1098. bswap eax
  1099. mov n, eax
  1100. }
  1101. return n;
  1102. #endif
  1103. }
  1104. inline uint64 ByteOrder::swap (uint64 value)
  1105. {
  1106. #if JUCE_MAC || JUCE_IPHONE
  1107. return OSSwapInt64 (value);
  1108. #elif JUCE_USE_INTRINSICS
  1109. return _byteswap_uint64 (value);
  1110. #else
  1111. return (((int64) swap ((uint32) value)) << 32) | swap ((uint32) (value >> 32));
  1112. #endif
  1113. }
  1114. #if JUCE_LITTLE_ENDIAN
  1115. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return v; }
  1116. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return v; }
  1117. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return v; }
  1118. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return swap (v); }
  1119. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return swap (v); }
  1120. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return swap (v); }
  1121. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1122. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1123. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1124. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1125. inline bool ByteOrder::isBigEndian() { return false; }
  1126. #else
  1127. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return swap (v); }
  1128. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return swap (v); }
  1129. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return swap (v); }
  1130. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return v; }
  1131. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return v; }
  1132. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return v; }
  1133. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1134. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1135. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1136. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1137. inline bool ByteOrder::isBigEndian() { return true; }
  1138. #endif
  1139. inline int ByteOrder::littleEndian24Bit (const char* const bytes) { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  1140. inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  1141. 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); }
  1142. 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); }
  1143. #endif // __JUCE_BYTEORDER_JUCEHEADER__
  1144. /*** End of inlined file: juce_ByteOrder.h ***/
  1145. /*** Start of inlined file: juce_Logger.h ***/
  1146. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1147. #define __JUCE_LOGGER_JUCEHEADER__
  1148. /*** Start of inlined file: juce_String.h ***/
  1149. #ifndef __JUCE_STRING_JUCEHEADER__
  1150. #define __JUCE_STRING_JUCEHEADER__
  1151. /*** Start of inlined file: juce_CharacterFunctions.h ***/
  1152. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1153. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1154. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1155. typedef juce_wchar tchar;
  1156. #if ! JUCE_DONT_DEFINE_MACROS
  1157. /** The 'T' macro allows a literal string to be compiled as unicode.
  1158. If you write your string literals in the form T("xyz"), it will be compiled as L"xyz"
  1159. or "xyz", depending on which representation is best for the String class to work with.
  1160. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1161. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1162. the juce/src directory) to avoid defining this macro. See the comments in
  1163. juce_withoutMacros.h for more info.
  1164. */
  1165. #define T(stringLiteral) JUCE_T(stringLiteral)
  1166. #endif
  1167. /**
  1168. A set of methods for manipulating characters and character strings, with
  1169. duplicate methods to handle 8-bit and unicode characters.
  1170. These are defined as wrappers around the basic C string handlers, to provide
  1171. a clean, cross-platform layer, (because various platforms differ in the
  1172. range of C library calls that they provide).
  1173. @see String
  1174. */
  1175. class JUCE_API CharacterFunctions
  1176. {
  1177. public:
  1178. static int length (const char* const s) throw();
  1179. static int length (const juce_wchar* const s) throw();
  1180. static void copy (char* dest, const char* src, const int maxBytes) throw();
  1181. static void copy (juce_wchar* dest, const juce_wchar* src, const int maxChars) throw();
  1182. static void copy (juce_wchar* dest, const char* src, const int maxChars) throw();
  1183. static void copy (char* dest, const juce_wchar* src, const int maxBytes) throw();
  1184. static int bytesRequiredForCopy (const juce_wchar* src) throw();
  1185. static void append (char* dest, const char* src) throw();
  1186. static void append (juce_wchar* dest, const juce_wchar* src) throw();
  1187. static int compare (const char* const s1, const char* const s2) throw();
  1188. static int compare (const juce_wchar* s1, const juce_wchar* s2) throw();
  1189. static int compare (const juce_wchar* s1, const char* s2) throw();
  1190. static int compare (const char* s1, const juce_wchar* s2) throw();
  1191. static int compare (const char* const s1, const char* const s2, const int maxChars) throw();
  1192. static int compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1193. static int compareIgnoreCase (const char* const s1, const char* const s2) throw();
  1194. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw();
  1195. static int compareIgnoreCase (const juce_wchar* s1, const char* s2) throw();
  1196. static int compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw();
  1197. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1198. static const char* find (const char* const haystack, const char* const needle) throw();
  1199. static const juce_wchar* find (const juce_wchar* haystack, const juce_wchar* const needle) throw();
  1200. static int indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw();
  1201. static int indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw();
  1202. static int indexOfCharFast (const char* const haystack, const char needle) throw();
  1203. static int indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw();
  1204. static int getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw();
  1205. static int getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw();
  1206. static int ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw();
  1207. static int ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw();
  1208. static int getIntValue (const char* const s) throw();
  1209. static int getIntValue (const juce_wchar* s) throw();
  1210. static int64 getInt64Value (const char* s) throw();
  1211. static int64 getInt64Value (const juce_wchar* s) throw();
  1212. static double getDoubleValue (const char* const s) throw();
  1213. static double getDoubleValue (const juce_wchar* const s) throw();
  1214. static char toUpperCase (const char character) throw();
  1215. static juce_wchar toUpperCase (const juce_wchar character) throw();
  1216. static void toUpperCase (char* s) throw();
  1217. static void toUpperCase (juce_wchar* s) throw();
  1218. static bool isUpperCase (const char character) throw();
  1219. static bool isUpperCase (const juce_wchar character) throw();
  1220. static char toLowerCase (const char character) throw();
  1221. static juce_wchar toLowerCase (const juce_wchar character) throw();
  1222. static void toLowerCase (char* s) throw();
  1223. static void toLowerCase (juce_wchar* s) throw();
  1224. static bool isLowerCase (const char character) throw();
  1225. static bool isLowerCase (const juce_wchar character) throw();
  1226. static bool isWhitespace (const char character) throw();
  1227. static bool isWhitespace (const juce_wchar character) throw();
  1228. static bool isDigit (const char character) throw();
  1229. static bool isDigit (const juce_wchar character) throw();
  1230. static bool isLetter (const char character) throw();
  1231. static bool isLetter (const juce_wchar character) throw();
  1232. static bool isLetterOrDigit (const char character) throw();
  1233. static bool isLetterOrDigit (const juce_wchar character) throw();
  1234. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legel
  1235. hex digit.
  1236. */
  1237. static int getHexDigitValue (const juce_wchar digit) throw();
  1238. };
  1239. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1240. /*** End of inlined file: juce_CharacterFunctions.h ***/
  1241. class OutputStream;
  1242. /**
  1243. The JUCE String class!
  1244. Using a reference-counted internal representation, these strings are fast
  1245. and efficient, and there are methods to do just about any operation you'll ever
  1246. dream of.
  1247. @see StringArray, StringPairArray
  1248. */
  1249. class JUCE_API String
  1250. {
  1251. public:
  1252. /** Creates an empty string.
  1253. @see empty
  1254. */
  1255. String() throw();
  1256. /** Creates a copy of another string. */
  1257. String (const String& other) throw();
  1258. /** Creates a string from a zero-terminated text string.
  1259. The string is assumed to be stored in the default system encoding.
  1260. */
  1261. String (const char* text);
  1262. /** Creates a string from an string of characters.
  1263. This will use up the the first maxChars characters of the string (or
  1264. less if the string is actually shorter)
  1265. */
  1266. String (const char* text, size_t maxChars);
  1267. /** Creates a string from a zero-terminated unicode text string. */
  1268. String (const juce_wchar* unicodeText);
  1269. /** Creates a string from a unicode text string.
  1270. This will use up the the first maxChars characters of the string (or
  1271. less if the string is actually shorter)
  1272. */
  1273. String (const juce_wchar* unicodeText, size_t maxChars);
  1274. /** Creates a string from a single character. */
  1275. static const String charToString (juce_wchar character);
  1276. /** Destructor. */
  1277. ~String() throw();
  1278. /** This is an empty string that can be used whenever one is needed.
  1279. It's better to use this than String() because it explains what's going on
  1280. and is more efficient.
  1281. */
  1282. static const String empty;
  1283. /** Generates a probably-unique 32-bit hashcode from this string. */
  1284. int hashCode() const throw();
  1285. /** Generates a probably-unique 64-bit hashcode from this string. */
  1286. int64 hashCode64() const throw();
  1287. /** Returns the number of characters in the string. */
  1288. int length() const throw();
  1289. // Assignment and concatenation operators..
  1290. /** Replaces this string's contents with another string. */
  1291. String& operator= (const String& other) throw();
  1292. /** Appends another string at the end of this one. */
  1293. String& operator+= (const juce_wchar* textToAppend);
  1294. /** Appends another string at the end of this one. */
  1295. String& operator+= (const String& stringToAppend);
  1296. /** Appends a character at the end of this string. */
  1297. String& operator+= (char characterToAppend);
  1298. /** Appends a character at the end of this string. */
  1299. String& operator+= (juce_wchar characterToAppend);
  1300. /** Appends a decimal number at the end of this string. */
  1301. String& operator+= (int numberToAppend);
  1302. /** Appends a decimal number at the end of this string. */
  1303. String& operator+= (unsigned int numberToAppend);
  1304. /** Appends a string at the end of this one.
  1305. @param textToAppend the string to add
  1306. @param maxCharsToTake the maximum number of characters to take from the string passed in
  1307. */
  1308. void append (const juce_wchar* textToAppend, int maxCharsToTake);
  1309. // Comparison methods..
  1310. /** Returns true if the string contains no characters.
  1311. Note that there's also an isNotEmpty() method to help write readable code.
  1312. @see containsNonWhitespaceChars()
  1313. */
  1314. inline bool isEmpty() const throw() { return text[0] == 0; }
  1315. /** Returns true if the string contains at least one character.
  1316. Note that there's also an isEmpty() method to help write readable code.
  1317. @see containsNonWhitespaceChars()
  1318. */
  1319. inline bool isNotEmpty() const throw() { return text[0] != 0; }
  1320. /** Case-insensitive comparison with another string. */
  1321. bool equalsIgnoreCase (const String& other) const throw();
  1322. /** Case-insensitive comparison with another string. */
  1323. bool equalsIgnoreCase (const juce_wchar* other) const throw();
  1324. /** Case-insensitive comparison with another string. */
  1325. bool equalsIgnoreCase (const char* other) const throw();
  1326. /** Case-sensitive comparison with another string.
  1327. @returns 0 if the two strings are identical; negative if this string
  1328. comes before the other one alphabetically, or positive if it
  1329. comes after it.
  1330. */
  1331. int compare (const String& other) const throw();
  1332. /** Case-sensitive comparison with another string.
  1333. @returns 0 if the two strings are identical; negative if this string
  1334. comes before the other one alphabetically, or positive if it
  1335. comes after it.
  1336. */
  1337. int compare (const char* other) const throw();
  1338. /** Case-sensitive comparison with another string.
  1339. @returns 0 if the two strings are identical; negative if this string
  1340. comes before the other one alphabetically, or positive if it
  1341. comes after it.
  1342. */
  1343. int compare (const juce_wchar* other) const throw();
  1344. /** Case-insensitive comparison with another string.
  1345. @returns 0 if the two strings are identical; negative if this string
  1346. comes before the other one alphabetically, or positive if it
  1347. comes after it.
  1348. */
  1349. int compareIgnoreCase (const String& other) const throw();
  1350. /** Lexicographic comparison with another string.
  1351. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  1352. characters, making it good for sorting human-readable strings.
  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 compareLexicographically (const String& other) const throw();
  1358. /** Tests whether the string begins with another string.
  1359. Uses a case-sensitive comparison.
  1360. */
  1361. bool startsWith (const String& text) const throw();
  1362. /** Tests whether the string begins with a particular character.
  1363. Uses a case-sensitive comparison.
  1364. */
  1365. bool startsWithChar (juce_wchar character) const throw();
  1366. /** Tests whether the string begins with another string.
  1367. Uses a case-insensitive comparison.
  1368. */
  1369. bool startsWithIgnoreCase (const String& text) const throw();
  1370. /** Tests whether the string ends with another string.
  1371. Uses a case-sensitive comparison.
  1372. */
  1373. bool endsWith (const String& text) const throw();
  1374. /** Tests whether the string ends with a particular character.
  1375. Uses a case-sensitive comparison.
  1376. */
  1377. bool endsWithChar (juce_wchar character) const throw();
  1378. /** Tests whether the string ends with another string.
  1379. Uses a case-insensitive comparison.
  1380. */
  1381. bool endsWithIgnoreCase (const String& text) const throw();
  1382. /** Tests whether the string contains another substring.
  1383. Uses a case-sensitive comparison.
  1384. */
  1385. bool contains (const String& text) const throw();
  1386. /** Tests whether the string contains a particular character.
  1387. Uses a case-sensitive comparison.
  1388. */
  1389. bool containsChar (juce_wchar character) const throw();
  1390. /** Tests whether the string contains another substring.
  1391. Uses a case-insensitive comparison.
  1392. */
  1393. bool containsIgnoreCase (const String& text) const throw();
  1394. /** Tests whether the string contains another substring as a distict word.
  1395. @returns true if the string contains this word, surrounded by
  1396. non-alphanumeric characters
  1397. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1398. */
  1399. bool containsWholeWord (const String& wordToLookFor) const throw();
  1400. /** Tests whether the string contains another substring as a distict word.
  1401. @returns true if the string contains this word, surrounded by
  1402. non-alphanumeric characters
  1403. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1404. */
  1405. bool containsWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  1406. /** Finds an instance of another substring if it exists as a distict word.
  1407. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1408. then this will return the index of the start of the substring. If it isn't
  1409. found, then it will return -1
  1410. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1411. */
  1412. int indexOfWholeWord (const String& wordToLookFor) const throw();
  1413. /** Finds an instance of another substring if it exists as a distict word.
  1414. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1415. then this will return the index of the start of the substring. If it isn't
  1416. found, then it will return -1
  1417. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1418. */
  1419. int indexOfWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  1420. /** Looks for any of a set of characters in the string.
  1421. Uses a case-sensitive comparison.
  1422. @returns true if the string contains any of the characters from
  1423. the string that is passed in.
  1424. */
  1425. bool containsAnyOf (const String& charactersItMightContain) const throw();
  1426. /** Looks for a set of characters in the string.
  1427. Uses a case-sensitive comparison.
  1428. @returns true if the all the characters in the string are also found in the
  1429. string that is passed in.
  1430. */
  1431. bool containsOnly (const String& charactersItMightContain) const throw();
  1432. /** Returns true if this string contains any non-whitespace characters.
  1433. This will return false if the string contains only whitespace characters, or
  1434. if it's empty.
  1435. It is equivalent to calling "myString.trim().isNotEmpty()".
  1436. */
  1437. bool containsNonWhitespaceChars() const throw();
  1438. /** Returns true if the string matches this simple wildcard expression.
  1439. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  1440. This isn't a full-blown regex though! The only wildcard characters supported
  1441. are "*" and "?". It's mainly intended for filename pattern matching.
  1442. */
  1443. bool matchesWildcard (const String& wildcard, bool ignoreCase) const throw();
  1444. // Substring location methods..
  1445. /** Searches for a character inside this string.
  1446. Uses a case-sensitive comparison.
  1447. @returns the index of the first occurrence of the character in this
  1448. string, or -1 if it's not found.
  1449. */
  1450. int indexOfChar (juce_wchar characterToLookFor) const throw();
  1451. /** Searches for a character inside this string.
  1452. Uses a case-sensitive comparison.
  1453. @param startIndex the index from which the search should proceed
  1454. @param characterToLookFor the character to look for
  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 (int startIndex, juce_wchar characterToLookFor) const throw();
  1459. /** Returns the index of the first character that matches one of the characters
  1460. passed-in to this method.
  1461. This scans the string, beginning from the startIndex supplied, and if it finds
  1462. a character that appears in the string charactersToLookFor, it returns its index.
  1463. If none of these characters are found, it returns -1.
  1464. If ignoreCase is true, the comparison will be case-insensitive.
  1465. @see indexOfChar, lastIndexOfAnyOf
  1466. */
  1467. int indexOfAnyOf (const String& charactersToLookFor,
  1468. int startIndex = 0,
  1469. bool ignoreCase = false) const throw();
  1470. /** Searches for a substring within this string.
  1471. Uses a case-sensitive comparison.
  1472. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1473. */
  1474. int indexOf (const String& text) const throw();
  1475. /** Searches for a substring within this string.
  1476. Uses a case-sensitive comparison.
  1477. @param startIndex the index from which the search should proceed
  1478. @param textToLookFor the string to search for
  1479. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1480. */
  1481. int indexOf (int startIndex,
  1482. const String& textToLookFor) const throw();
  1483. /** Searches for a substring within this string.
  1484. Uses a case-insensitive comparison.
  1485. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1486. */
  1487. int indexOfIgnoreCase (const String& textToLookFor) const throw();
  1488. /** Searches for a substring within this string.
  1489. Uses a case-insensitive comparison.
  1490. @param startIndex the index from which the search should proceed
  1491. @param textToLookFor the string to search for
  1492. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1493. */
  1494. int indexOfIgnoreCase (int startIndex,
  1495. const String& textToLookFor) const throw();
  1496. /** Searches for a character inside this string (working backwards from the end of the string).
  1497. Uses a case-sensitive comparison.
  1498. @returns the index of the last occurrence of the character in this
  1499. string, or -1 if it's not found.
  1500. */
  1501. int lastIndexOfChar (juce_wchar character) const throw();
  1502. /** Searches for a substring inside this string (working backwards from the end of the string).
  1503. Uses a case-sensitive comparison.
  1504. @returns the index of the start of the last occurrence of the
  1505. substring within this string, or -1 if it's not found.
  1506. */
  1507. int lastIndexOf (const String& textToLookFor) const throw();
  1508. /** Searches for a substring inside this string (working backwards from the end of the string).
  1509. Uses a case-insensitive comparison.
  1510. @returns the index of the start of the last occurrence of the
  1511. substring within this string, or -1 if it's not found.
  1512. */
  1513. int lastIndexOfIgnoreCase (const String& textToLookFor) const throw();
  1514. /** Returns the index of the last character in this string that matches one of the
  1515. characters passed-in to this method.
  1516. This scans the string backwards, starting from its end, and if it finds
  1517. a character that appears in the string charactersToLookFor, it returns its index.
  1518. If none of these characters are found, it returns -1.
  1519. If ignoreCase is true, the comparison will be case-insensitive.
  1520. @see lastIndexOf, indexOfAnyOf
  1521. */
  1522. int lastIndexOfAnyOf (const String& charactersToLookFor,
  1523. bool ignoreCase = false) const throw();
  1524. // Substring extraction and manipulation methods..
  1525. /** Returns the character at this index in the string.
  1526. No checks are made to see if the index is within a valid range, so be careful!
  1527. */
  1528. inline const juce_wchar& operator[] (int index) const throw() { jassert (((unsigned int) index) <= (unsigned int) length()); return text [index]; }
  1529. /** Returns a character from the string such that it can also be altered.
  1530. This can be used as a way of easily changing characters in the string.
  1531. Note that the index passed-in is not checked to see whether it's in-range, so
  1532. be careful when using this.
  1533. */
  1534. juce_wchar& operator[] (int index);
  1535. /** Returns the final character of the string.
  1536. If the string is empty this will return 0.
  1537. */
  1538. juce_wchar getLastCharacter() const throw();
  1539. /** Returns a subsection of the string.
  1540. If the range specified is beyond the limits of the string, as much as
  1541. possible is returned.
  1542. @param startIndex the index of the start of the substring needed
  1543. @param endIndex all characters from startIndex up to (but not including)
  1544. this index are returned
  1545. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  1546. */
  1547. const String substring (int startIndex, int endIndex) const;
  1548. /** Returns a section of the string, starting from a given position.
  1549. @param startIndex the first character to include. If this is beyond the end
  1550. of the string, an empty string is returned. If it is zero or
  1551. less, the whole string is returned.
  1552. @returns the substring from startIndex up to the end of the string
  1553. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  1554. */
  1555. const String substring (int startIndex) const;
  1556. /** Returns a version of this string with a number of characters removed
  1557. from the end.
  1558. @param numberToDrop the number of characters to drop from the end of the
  1559. string. If this is greater than the length of the string,
  1560. an empty string will be returned. If zero or less, the
  1561. original string will be returned.
  1562. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  1563. */
  1564. const String dropLastCharacters (int numberToDrop) const;
  1565. /** Returns a number of characters from the end of the string.
  1566. This returns the last numCharacters characters from the end of the string. If the
  1567. string is shorter than numCharacters, the whole string is returned.
  1568. @see substring, dropLastCharacters, getLastCharacter
  1569. */
  1570. const String getLastCharacters (int numCharacters) const;
  1571. /** Returns a section of the string starting from a given substring.
  1572. This will search for the first occurrence of the given substring, and
  1573. return the section of the string starting from the point where this is
  1574. found (optionally not including the substring itself).
  1575. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  1576. fromFirstOccurrenceOf ("34", false) would return "56".
  1577. If the substring isn't found, the method will return an empty string.
  1578. If ignoreCase is true, the comparison will be case-insensitive.
  1579. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  1580. */
  1581. const String fromFirstOccurrenceOf (const String& substringToStartFrom,
  1582. bool includeSubStringInResult,
  1583. bool ignoreCase) const;
  1584. /** Returns a section of the string starting from the last occurrence of a given substring.
  1585. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  1586. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  1587. return the whole of the original string.
  1588. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  1589. */
  1590. const String fromLastOccurrenceOf (const String& substringToFind,
  1591. bool includeSubStringInResult,
  1592. bool ignoreCase) const;
  1593. /** Returns the start of this string, up to the first occurrence of a substring.
  1594. This will search for the first occurrence of a given substring, and then
  1595. return a copy of the string, up to the position of this substring,
  1596. optionally including or excluding the substring itself in the result.
  1597. e.g. for the string "123456", upTo ("34", false) would return "12", and
  1598. upTo ("34", true) would return "1234".
  1599. If the substring isn't found, this will return the whole of the original string.
  1600. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  1601. */
  1602. const String upToFirstOccurrenceOf (const String& substringToEndWith,
  1603. bool includeSubStringInResult,
  1604. bool ignoreCase) const;
  1605. /** Returns the start of this string, up to the last occurrence of a substring.
  1606. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  1607. If the substring isn't found, this will return an empty string.
  1608. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  1609. */
  1610. const String upToLastOccurrenceOf (const String& substringToFind,
  1611. bool includeSubStringInResult,
  1612. bool ignoreCase) const;
  1613. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  1614. const String trim() const;
  1615. /** Returns a copy of this string with any whitespace characters removed from the start. */
  1616. const String trimStart() const;
  1617. /** Returns a copy of this string with any whitespace characters removed from the end. */
  1618. const String trimEnd() const;
  1619. /** Returns a copy of this string, having removed a specified set of characters from its start.
  1620. Characters are removed from the start of the string until it finds one that is not in the
  1621. specified set, and then it stops.
  1622. @param charactersToTrim the set of characters to remove.
  1623. @see trim, trimStart, trimCharactersAtEnd
  1624. */
  1625. const String trimCharactersAtStart (const String& charactersToTrim) const;
  1626. /** Returns a copy of this string, having removed a specified set of characters from its end.
  1627. Characters are removed from the end of the string until it finds one that is not in the
  1628. specified set, and then it stops.
  1629. @param charactersToTrim the set of characters to remove.
  1630. @see trim, trimEnd, trimCharactersAtStart
  1631. */
  1632. const String trimCharactersAtEnd (const String& charactersToTrim) const;
  1633. /** Returns an upper-case version of this string. */
  1634. const String toUpperCase() const;
  1635. /** Returns an lower-case version of this string. */
  1636. const String toLowerCase() const;
  1637. /** Replaces a sub-section of the string with another string.
  1638. This will return a copy of this string, with a set of characters
  1639. from startIndex to startIndex + numCharsToReplace removed, and with
  1640. a new string inserted in their place.
  1641. Note that this is a const method, and won't alter the string itself.
  1642. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  1643. it will be constrained to a valid range.
  1644. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  1645. characters will be taken out.
  1646. @param stringToInsert the new string to insert at startIndex after the characters have been
  1647. removed.
  1648. */
  1649. const String replaceSection (int startIndex,
  1650. int numCharactersToReplace,
  1651. const String& stringToInsert) const;
  1652. /** Replaces all occurrences of a substring with another string.
  1653. Returns a copy of this string, with any occurrences of stringToReplace
  1654. swapped for stringToInsertInstead.
  1655. Note that this is a const method, and won't alter the string itself.
  1656. */
  1657. const String replace (const String& stringToReplace,
  1658. const String& stringToInsertInstead,
  1659. bool ignoreCase = false) const;
  1660. /** Returns a string with all occurrences of a character replaced with a different one. */
  1661. const String replaceCharacter (juce_wchar characterToReplace,
  1662. juce_wchar characterToInsertInstead) const;
  1663. /** Replaces a set of characters with another set.
  1664. Returns a string in which each character from charactersToReplace has been replaced
  1665. by the character at the equivalent position in newCharacters (so the two strings
  1666. passed in must be the same length).
  1667. e.g. replaceCharacters ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  1668. Note that this is a const method, and won't affect the string itself.
  1669. */
  1670. const String replaceCharacters (const String& charactersToReplace,
  1671. const String& charactersToInsertInstead) const;
  1672. /** Returns a version of this string that only retains a fixed set of characters.
  1673. This will return a copy of this string, omitting any characters which are not
  1674. found in the string passed-in.
  1675. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  1676. Note that this is a const method, and won't alter the string itself.
  1677. */
  1678. const String retainCharacters (const String& charactersToRetain) const;
  1679. /** Returns a version of this string with a set of characters removed.
  1680. This will return a copy of this string, omitting any characters which are
  1681. found in the string passed-in.
  1682. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  1683. Note that this is a const method, and won't alter the string itself.
  1684. */
  1685. const String removeCharacters (const String& charactersToRemove) const;
  1686. /** Returns a section from the start of the string that only contains a certain set of characters.
  1687. This returns the leftmost section of the string, up to (and not including) the
  1688. first character that doesn't appear in the string passed in.
  1689. */
  1690. const String initialSectionContainingOnly (const String& permittedCharacters) const;
  1691. /** Returns a section from the start of the string that only contains a certain set of characters.
  1692. This returns the leftmost section of the string, up to (and not including) the
  1693. first character that occurs in the string passed in.
  1694. */
  1695. const String initialSectionNotContaining (const String& charactersToStopAt) const;
  1696. /** Checks whether the string might be in quotation marks.
  1697. @returns true if the string begins with a quote character (either a double or single quote).
  1698. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  1699. @see unquoted, quoted
  1700. */
  1701. bool isQuotedString() const;
  1702. /** Removes quotation marks from around the string, (if there are any).
  1703. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  1704. at the ends of the string are not affected. If there aren't any quotes, the original string
  1705. is returned.
  1706. Note that this is a const method, and won't alter the string itself.
  1707. @see isQuotedString, quoted
  1708. */
  1709. const String unquoted() const;
  1710. /** Adds quotation marks around a string.
  1711. This will return a copy of the string with a quote at the start and end, (but won't
  1712. add the quote if there's already one there, so it's safe to call this on strings that
  1713. may already have quotes around them).
  1714. Note that this is a const method, and won't alter the string itself.
  1715. @param quoteCharacter the character to add at the start and end
  1716. @see isQuotedString, unquoted
  1717. */
  1718. const String quoted (juce_wchar quoteCharacter = '"') const;
  1719. /** Creates a string which is a version of a string repeated and joined together.
  1720. @param stringToRepeat the string to repeat
  1721. @param numberOfTimesToRepeat how many times to repeat it
  1722. */
  1723. static const String repeatedString (const String& stringToRepeat,
  1724. int numberOfTimesToRepeat);
  1725. /** Returns a copy of this string with the specified character repeatedly added to its
  1726. beginning until the total length is at least the minimum length specified.
  1727. */
  1728. const String paddedLeft (juce_wchar padCharacter, int minimumLength) const;
  1729. /** Returns a copy of this string with the specified character repeatedly added to its
  1730. end until the total length is at least the minimum length specified.
  1731. */
  1732. const String paddedRight (juce_wchar padCharacter, int minimumLength) const;
  1733. /** Creates a string from data in an unknown format.
  1734. This looks at some binary data and tries to guess whether it's Unicode
  1735. or 8-bit characters, then returns a string that represents it correctly.
  1736. Should be able to handle Unicode endianness correctly, by looking at
  1737. the first two bytes.
  1738. */
  1739. static const String createStringFromData (const void* data, int size);
  1740. /** Creates a String from a printf-style parameter list.
  1741. I don't like this method. I don't use it myself, and I recommend avoiding it and
  1742. using the operator<< methods or pretty much anything else instead. It's only provided
  1743. here because of the popular unrest that was stirred-up when I tried to remove it...
  1744. If you're really determined to use it, at least make sure that you never, ever,
  1745. pass any String objects to it as parameters.
  1746. */
  1747. static const String formatted (const juce_wchar* formatString, ... );
  1748. // Numeric conversions..
  1749. /** Creates a string containing this signed 32-bit integer as a decimal number.
  1750. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1751. */
  1752. explicit String (int decimalInteger);
  1753. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  1754. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1755. */
  1756. explicit String (unsigned int decimalInteger);
  1757. /** Creates a string containing this signed 16-bit integer as a decimal number.
  1758. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1759. */
  1760. explicit String (short decimalInteger);
  1761. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  1762. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1763. */
  1764. explicit String (unsigned short decimalInteger);
  1765. /** Creates a string containing this signed 64-bit integer as a decimal number.
  1766. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1767. */
  1768. explicit String (int64 largeIntegerValue);
  1769. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  1770. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1771. */
  1772. explicit String (uint64 largeIntegerValue);
  1773. /** Creates a string representing this floating-point number.
  1774. @param floatValue the value to convert to a string
  1775. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1776. decimal places, and will not use exponent notation. If 0 or
  1777. less, it will use exponent notation if necessary.
  1778. @see getDoubleValue, getIntValue
  1779. */
  1780. explicit String (float floatValue,
  1781. int numberOfDecimalPlaces = 0);
  1782. /** Creates a string representing this floating-point number.
  1783. @param doubleValue the value to convert to a string
  1784. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1785. decimal places, and will not use exponent notation. If 0 or
  1786. less, it will use exponent notation if necessary.
  1787. @see getFloatValue, getIntValue
  1788. */
  1789. explicit String (double doubleValue,
  1790. int numberOfDecimalPlaces = 0);
  1791. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  1792. @returns the value of the string as a 32 bit signed base-10 integer.
  1793. @see getTrailingIntValue, getHexValue32, getHexValue64
  1794. */
  1795. int getIntValue() const throw();
  1796. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  1797. @returns the value of the string as a 64 bit signed base-10 integer.
  1798. */
  1799. int64 getLargeIntValue() const throw();
  1800. /** Parses a decimal number from the end of the string.
  1801. This will look for a value at the end of the string.
  1802. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  1803. Negative numbers are not handled, so "xyz-5" returns 5.
  1804. @see getIntValue
  1805. */
  1806. int getTrailingIntValue() const throw();
  1807. /** Parses this string as a floating point number.
  1808. @returns the value of the string as a 32-bit floating point value.
  1809. @see getDoubleValue
  1810. */
  1811. float getFloatValue() const throw();
  1812. /** Parses this string as a floating point number.
  1813. @returns the value of the string as a 64-bit floating point value.
  1814. @see getFloatValue
  1815. */
  1816. double getDoubleValue() const throw();
  1817. /** Parses the string as a hexadecimal number.
  1818. Non-hexadecimal characters in the string are ignored.
  1819. If the string contains too many characters, then the lowest significant
  1820. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  1821. @returns a 32-bit number which is the value of the string in hex.
  1822. */
  1823. int getHexValue32() const throw();
  1824. /** Parses the string as a hexadecimal number.
  1825. Non-hexadecimal characters in the string are ignored.
  1826. If the string contains too many characters, then the lowest significant
  1827. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  1828. @returns a 64-bit number which is the value of the string in hex.
  1829. */
  1830. int64 getHexValue64() const throw();
  1831. /** Creates a string representing this 32-bit value in hexadecimal. */
  1832. static const String toHexString (int number);
  1833. /** Creates a string representing this 64-bit value in hexadecimal. */
  1834. static const String toHexString (int64 number);
  1835. /** Creates a string representing this 16-bit value in hexadecimal. */
  1836. static const String toHexString (short number);
  1837. /** Creates a string containing a hex dump of a block of binary data.
  1838. @param data the binary data to use as input
  1839. @param size how many bytes of data to use
  1840. @param groupSize how many bytes are grouped together before inserting a
  1841. space into the output. e.g. group size 0 has no spaces,
  1842. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  1843. like "bea1 c2ff".
  1844. */
  1845. static const String toHexString (const unsigned char* data,
  1846. int size,
  1847. int groupSize = 1);
  1848. /** Returns a unicode version of this string.
  1849. Because it returns a reference to the string's internal data, the pointer
  1850. that is returned must not be stored anywhere, as it can become invalid whenever
  1851. any string methods (even some const ones!) are called.
  1852. */
  1853. inline operator const juce_wchar*() const throw() { return text; }
  1854. /** Returns a unicode version of this string.
  1855. Because it returns a reference to the string's internal data, the pointer
  1856. that is returned must not be stored anywhere, as it can become invalid whenever
  1857. any string methods (even some const ones!) are called.
  1858. */
  1859. inline operator juce_wchar*() throw() { return text; }
  1860. /** Returns a pointer to a UTF-8 version of this string.
  1861. Because it returns a reference to the string's internal data, the pointer
  1862. that is returned must not be stored anywhere, as it can be deleted whenever the
  1863. string changes.
  1864. @see getNumBytesAsUTF8, fromUTF8, copyToUTF8, toCString
  1865. */
  1866. const char* toUTF8() const;
  1867. /** Creates a String from a UTF-8 encoded buffer.
  1868. If the size is < 0, it'll keep reading until it hits a zero.
  1869. */
  1870. static const String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1);
  1871. /** Returns the number of bytes required to represent this string as UTF8.
  1872. The number returned does NOT include the trailing zero.
  1873. @see toUTF8, copyToUTF8
  1874. */
  1875. int getNumBytesAsUTF8() const throw();
  1876. /** Copies the string to a buffer as UTF-8 characters.
  1877. Returns the number of bytes copied to the buffer, including the terminating null
  1878. character.
  1879. @param destBuffer the place to copy it to; if this is a null pointer,
  1880. the method just returns the number of bytes required
  1881. (including the terminating null character).
  1882. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  1883. string won't fit, it'll put in as many as it can while
  1884. still allowing for a terminating null char at the end, and
  1885. will return the number of bytes that were actually used.
  1886. */
  1887. int copyToUTF8 (char* destBuffer, int maxBufferSizeBytes) const throw();
  1888. /** Returns a version of this string using the default 8-bit multi-byte system encoding.
  1889. Because it returns a reference to the string's internal data, the pointer
  1890. that is returned must not be stored anywhere, as it can be deleted whenever the
  1891. string changes.
  1892. @see getNumBytesAsCString, copyToCString, toUTF8
  1893. */
  1894. const char* toCString() const;
  1895. /** Returns the number of bytes
  1896. */
  1897. int getNumBytesAsCString() const throw();
  1898. /** Copies the string to a buffer.
  1899. @param destBuffer the place to copy it to; if this is a null pointer,
  1900. the method just returns the number of bytes required
  1901. (including the terminating null character).
  1902. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  1903. string won't fit, it'll put in as many as it can while
  1904. still allowing for a terminating null char at the end, and
  1905. will return the number of bytes that were actually used.
  1906. */
  1907. int copyToCString (char* destBuffer, int maxBufferSizeBytes) const throw();
  1908. /** Copies the string to a unicode buffer.
  1909. @param destBuffer the place to copy it to
  1910. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1911. not including the tailing zero, so this shouldn't be
  1912. larger than the size of your destination buffer - 1
  1913. */
  1914. void copyToUnicode (juce_wchar* destBuffer, int maxCharsToCopy) const throw();
  1915. /** Increases the string's internally allocated storage.
  1916. Although the string's contents won't be affected by this call, it will
  1917. increase the amount of memory allocated internally for the string to grow into.
  1918. If you're about to make a large number of calls to methods such
  1919. as += or <<, it's more efficient to preallocate enough extra space
  1920. beforehand, so that these methods won't have to keep resizing the string
  1921. to append the extra characters.
  1922. @param numCharsNeeded the number of characters to allocate storage for. If this
  1923. value is less than the currently allocated size, it will
  1924. have no effect.
  1925. */
  1926. void preallocateStorage (size_t numCharsNeeded);
  1927. /** Swaps the contents of this string with another one.
  1928. This is a very fast operation, as no allocation or copying needs to be done.
  1929. */
  1930. void swapWith (String& other) throw();
  1931. /** A helper class to improve performance when concatenating many large strings
  1932. together.
  1933. Because appending one string to another involves measuring the length of
  1934. both strings, repeatedly doing this for many long strings will become
  1935. an exponentially slow operation. This class uses some internal state to
  1936. avoid that, so that each append operation only needs to measure the length
  1937. of the appended string.
  1938. */
  1939. class JUCE_API Concatenator
  1940. {
  1941. public:
  1942. Concatenator (String& stringToAppendTo);
  1943. ~Concatenator();
  1944. void append (const String& s);
  1945. private:
  1946. String& result;
  1947. int nextIndex;
  1948. Concatenator (const Concatenator&);
  1949. Concatenator& operator= (const Concatenator&);
  1950. };
  1951. juce_UseDebuggingNewOperator // (adds debugging info to find leaked objects)
  1952. private:
  1953. juce_wchar* text;
  1954. // internal constructor that preallocates a certain amount of memory
  1955. String (size_t numChars, int dummyVariable);
  1956. String (const String& stringToCopy, size_t charsToAllocate);
  1957. void createInternal (const juce_wchar* text, size_t numChars);
  1958. void appendInternal (const juce_wchar* text, int numExtraChars);
  1959. };
  1960. /** Concatenates two strings. */
  1961. const String JUCE_CALLTYPE operator+ (const char* string1, const String& string2);
  1962. /** Concatenates two strings. */
  1963. const String JUCE_CALLTYPE operator+ (const juce_wchar* string1, const String& string2);
  1964. /** Concatenates two strings. */
  1965. const String JUCE_CALLTYPE operator+ (char string1, const String& string2);
  1966. /** Concatenates two strings. */
  1967. const String JUCE_CALLTYPE operator+ (juce_wchar string1, const String& string2);
  1968. /** Concatenates two strings. */
  1969. const String JUCE_CALLTYPE operator+ (String string1, const String& string2);
  1970. /** Concatenates two strings. */
  1971. const String JUCE_CALLTYPE operator+ (String string1, const char* string2);
  1972. /** Concatenates two strings. */
  1973. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* string2);
  1974. /** Concatenates two strings. */
  1975. const String JUCE_CALLTYPE operator+ (String string1, char characterToAppend);
  1976. /** Concatenates two strings. */
  1977. const String JUCE_CALLTYPE operator+ (String string1, juce_wchar characterToAppend);
  1978. /** Appends a character at the end of a string. */
  1979. String& JUCE_CALLTYPE operator<< (String& string1, char characterToAppend);
  1980. /** Appends a character at the end of a string. */
  1981. String& JUCE_CALLTYPE operator<< (String& string1, juce_wchar characterToAppend);
  1982. /** Appends a string to the end of the first one. */
  1983. String& JUCE_CALLTYPE operator<< (String& string1, const char* string2);
  1984. /** Appends a string to the end of the first one. */
  1985. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* string2);
  1986. /** Appends a string to the end of the first one. */
  1987. String& JUCE_CALLTYPE operator<< (String& string1, const String& string2);
  1988. /** Appends a decimal number at the end of a string. */
  1989. String& JUCE_CALLTYPE operator<< (String& string1, short number);
  1990. /** Appends a decimal number at the end of a string. */
  1991. String& JUCE_CALLTYPE operator<< (String& string1, int number);
  1992. /** Appends a decimal number at the end of a string. */
  1993. String& JUCE_CALLTYPE operator<< (String& string1, unsigned int number);
  1994. /** Appends a decimal number at the end of a string. */
  1995. String& JUCE_CALLTYPE operator<< (String& string1, long number);
  1996. /** Appends a decimal number at the end of a string. */
  1997. String& JUCE_CALLTYPE operator<< (String& string1, unsigned long number);
  1998. /** Appends a decimal number at the end of a string. */
  1999. String& JUCE_CALLTYPE operator<< (String& string1, float number);
  2000. /** Appends a decimal number at the end of a string. */
  2001. String& JUCE_CALLTYPE operator<< (String& string1, double number);
  2002. /** Case-sensitive comparison of two strings. */
  2003. bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw();
  2004. /** Case-sensitive comparison of two strings. */
  2005. bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw();
  2006. /** Case-sensitive comparison of two strings. */
  2007. bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw();
  2008. /** Case-sensitive comparison of two strings. */
  2009. bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw();
  2010. /** Case-sensitive comparison of two strings. */
  2011. bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw();
  2012. /** Case-sensitive comparison of two strings. */
  2013. bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw();
  2014. /** Case-sensitive comparison of two strings. */
  2015. bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw();
  2016. /** Case-sensitive comparison of two strings. */
  2017. bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw();
  2018. /** Case-sensitive comparison of two strings. */
  2019. bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw();
  2020. /** Case-sensitive comparison of two strings. */
  2021. bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw();
  2022. /** This streaming override allows you to pass a juce String directly into std output streams.
  2023. This is very handy for writing strings to std::cout, std::cerr, etc.
  2024. */
  2025. template <class charT, class traits>
  2026. std::basic_ostream <charT, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <charT, traits>& stream, const String& stringToWrite)
  2027. {
  2028. return stream << stringToWrite.toUTF8();
  2029. }
  2030. /** Writes a string to an OutputStream as UTF8. */
  2031. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text);
  2032. #endif // __JUCE_STRING_JUCEHEADER__
  2033. /*** End of inlined file: juce_String.h ***/
  2034. /**
  2035. Acts as an application-wide logging class.
  2036. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  2037. method and this will then be used by all calls to writeToLog.
  2038. The logger class also contains methods for writing messages to the debugger's
  2039. output stream.
  2040. @see FileLogger
  2041. */
  2042. class JUCE_API Logger
  2043. {
  2044. public:
  2045. /** Destructor. */
  2046. virtual ~Logger();
  2047. /** Sets the current logging class to use.
  2048. Note that the object passed in won't be deleted when no longer needed.
  2049. A null pointer can be passed-in to disable any logging.
  2050. If deleteOldLogger is set to true, the existing logger will be
  2051. deleted (if there is one).
  2052. */
  2053. static void JUCE_CALLTYPE setCurrentLogger (Logger* const newLogger,
  2054. const bool deleteOldLogger = false);
  2055. /** Writes a string to the current logger.
  2056. This will pass the string to the logger's logMessage() method if a logger
  2057. has been set.
  2058. @see logMessage
  2059. */
  2060. static void JUCE_CALLTYPE writeToLog (const String& message);
  2061. /** Writes a message to the standard error stream.
  2062. This can be called directly, or by using the DBG() macro in
  2063. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  2064. */
  2065. static void JUCE_CALLTYPE outputDebugString (const String& text);
  2066. protected:
  2067. Logger();
  2068. /** This is overloaded by subclasses to implement custom logging behaviour.
  2069. @see setCurrentLogger
  2070. */
  2071. virtual void logMessage (const String& message) = 0;
  2072. };
  2073. #endif // __JUCE_LOGGER_JUCEHEADER__
  2074. /*** End of inlined file: juce_Logger.h ***/
  2075. END_JUCE_NAMESPACE
  2076. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  2077. /*** End of inlined file: juce_StandardHeader.h ***/
  2078. BEGIN_JUCE_NAMESPACE
  2079. #if JUCE_MSVC
  2080. // this is set explicitly in case the app is using a different packing size.
  2081. #pragma pack (push, 8)
  2082. #pragma warning (push)
  2083. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  2084. #endif
  2085. // this is where all the class header files get brought in..
  2086. /*** Start of inlined file: juce_core_includes.h ***/
  2087. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  2088. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  2089. #ifndef __JUCE_ARRAY_JUCEHEADER__
  2090. /*** Start of inlined file: juce_Array.h ***/
  2091. #ifndef __JUCE_ARRAY_JUCEHEADER__
  2092. #define __JUCE_ARRAY_JUCEHEADER__
  2093. /*** Start of inlined file: juce_ArrayAllocationBase.h ***/
  2094. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2095. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2096. /*** Start of inlined file: juce_HeapBlock.h ***/
  2097. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  2098. #define __JUCE_HEAPBLOCK_JUCEHEADER__
  2099. /**
  2100. Very simple container class to hold a pointer to some data on the heap.
  2101. When you need to allocate some heap storage for something, always try to use
  2102. this class instead of allocating the memory directly using malloc/free.
  2103. A HeapBlock<char> object can be treated in pretty much exactly the same way
  2104. as an char*, but as long as you allocate it on the stack or as a class member,
  2105. it's almost impossible for it to leak memory.
  2106. It also makes your code much more concise and readable than doing the same thing
  2107. using direct allocations,
  2108. E.g. instead of this:
  2109. @code
  2110. int* temp = (int*) juce_malloc (1024 * sizeof (int));
  2111. memcpy (temp, xyz, 1024 * sizeof (int));
  2112. juce_free (temp);
  2113. temp = (int*) juce_calloc (2048 * sizeof (int));
  2114. temp[0] = 1234;
  2115. memcpy (foobar, temp, 2048 * sizeof (int));
  2116. juce_free (temp);
  2117. @endcode
  2118. ..you could just write this:
  2119. @code
  2120. HeapBlock <int> temp (1024);
  2121. memcpy (temp, xyz, 1024 * sizeof (int));
  2122. temp.calloc (2048);
  2123. temp[0] = 1234;
  2124. memcpy (foobar, temp, 2048 * sizeof (int));
  2125. @endcode
  2126. The class is extremely lightweight, containing only a pointer to the
  2127. data, and exposes malloc/realloc/calloc/free methods that do the same jobs
  2128. as their less object-oriented counterparts. Despite adding safety, you probably
  2129. won't sacrifice any performance by using this in place of normal pointers.
  2130. @see Array, OwnedArray, MemoryBlock
  2131. */
  2132. template <class ElementType>
  2133. class HeapBlock
  2134. {
  2135. public:
  2136. /** Creates a HeapBlock which is initially just a null pointer.
  2137. After creation, you can resize the array using the malloc(), calloc(),
  2138. or realloc() methods.
  2139. */
  2140. HeapBlock() throw() : data (0)
  2141. {
  2142. }
  2143. /** Creates a HeapBlock containing a number of elements.
  2144. The contents of the block are undefined, as it will have been created by a
  2145. malloc call.
  2146. If you want an array of zero values, you can use the calloc() method instead.
  2147. */
  2148. explicit HeapBlock (const size_t numElements)
  2149. : data (static_cast <ElementType*> (::juce_malloc (numElements * sizeof (ElementType))))
  2150. {
  2151. }
  2152. /** Destructor.
  2153. This will free the data, if any has been allocated.
  2154. */
  2155. ~HeapBlock()
  2156. {
  2157. ::juce_free (data);
  2158. }
  2159. /** Returns a raw pointer to the allocated data.
  2160. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2161. freed by calling the free() method.
  2162. */
  2163. inline operator ElementType*() const throw() { return data; }
  2164. /** Returns a raw pointer to the allocated data.
  2165. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2166. freed by calling the free() method.
  2167. */
  2168. inline ElementType* getData() const throw() { return data; }
  2169. /** Returns a void 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 void*() const throw() { return static_cast <void*> (data); }
  2174. /** Lets you use indirect calls to the first element in the array.
  2175. Obviously this will cause problems if the array hasn't been initialised, because it'll
  2176. be referencing a null pointer.
  2177. */
  2178. inline ElementType* operator->() const throw() { return data; }
  2179. /** Returns a reference to one of the data elements.
  2180. Obviously there's no bounds-checking here, as this object is just a dumb pointer and
  2181. has no idea of the size it currently has allocated.
  2182. */
  2183. template <typename IndexType>
  2184. inline ElementType& operator[] (IndexType index) const throw() { return data [index]; }
  2185. /** Returns a pointer to a data element at an offset from the start of the array.
  2186. This is the same as doing pointer arithmetic on the raw pointer itself.
  2187. */
  2188. template <typename IndexType>
  2189. inline ElementType* operator+ (IndexType index) const throw() { return data + index; }
  2190. /** Returns a reference to the raw data pointer.
  2191. Beware that the pointer returned here will become invalid as soon as you call
  2192. any of the allocator methods on this object!
  2193. */
  2194. inline ElementType* const* operator&() const throw() { return static_cast <ElementType* const*> (&data); }
  2195. /** Returns a reference to the raw data pointer.
  2196. Beware that the pointer returned here will become invalid as soon as you call
  2197. any of the allocator methods on this object!
  2198. */
  2199. inline ElementType** operator&() throw() { return static_cast <ElementType**> (&data); }
  2200. /** Compares the pointer with another pointer.
  2201. This can be handy for checking whether this is a null pointer.
  2202. */
  2203. inline bool operator== (const ElementType* const otherPointer) const throw() { return otherPointer == data; }
  2204. /** Compares the pointer with another pointer.
  2205. This can be handy for checking whether this is a null pointer.
  2206. */
  2207. inline bool operator!= (const ElementType* const otherPointer) const throw() { return otherPointer != data; }
  2208. /** Allocates a specified amount of memory.
  2209. This uses the normal malloc to allocate an amount of memory for this object.
  2210. Any previously allocated memory will be freed by this method.
  2211. The number of bytes allocated will be (newNumElements * elementSize). Normally
  2212. you wouldn't need to specify the second parameter, but it can be handy if you need
  2213. to allocate a size in bytes rather than in terms of the number of elements.
  2214. The data that is allocated will be freed when this object is deleted, or when you
  2215. call free() or any of the allocation methods.
  2216. */
  2217. void malloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2218. {
  2219. ::juce_free (data);
  2220. data = static_cast <ElementType*> (::juce_malloc (newNumElements * elementSize));
  2221. }
  2222. /** Allocates a specified amount of memory and clears it.
  2223. This does the same job as the malloc() method, but clears the memory that it allocates.
  2224. */
  2225. void calloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2226. {
  2227. ::juce_free (data);
  2228. data = static_cast <ElementType*> (::juce_calloc (newNumElements * elementSize));
  2229. }
  2230. /** Allocates a specified amount of memory and optionally clears it.
  2231. This does the same job as either malloc() or calloc(), depending on the
  2232. initialiseToZero parameter.
  2233. */
  2234. void allocate (const size_t newNumElements, const bool initialiseToZero)
  2235. {
  2236. ::juce_free (data);
  2237. if (initialiseToZero)
  2238. data = static_cast <ElementType*> (::juce_calloc (newNumElements * sizeof (ElementType)));
  2239. else
  2240. data = static_cast <ElementType*> (::juce_malloc (newNumElements * sizeof (ElementType)));
  2241. }
  2242. /** Re-allocates a specified amount of memory.
  2243. The semantics of this method are the same as malloc() and calloc(), but it
  2244. uses realloc() to keep as much of the existing data as possible.
  2245. */
  2246. void realloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2247. {
  2248. if (data == 0)
  2249. data = static_cast <ElementType*> (::juce_malloc (newNumElements * elementSize));
  2250. else
  2251. data = static_cast <ElementType*> (::juce_realloc (data, newNumElements * elementSize));
  2252. }
  2253. /** Frees any currently-allocated data.
  2254. This will free the data and reset this object to be a null pointer.
  2255. */
  2256. void free()
  2257. {
  2258. ::juce_free (data);
  2259. data = 0;
  2260. }
  2261. /** Swaps this object's data with the data of another HeapBlock.
  2262. The two objects simply exchange their data pointers.
  2263. */
  2264. void swapWith (HeapBlock <ElementType>& other) throw()
  2265. {
  2266. swapVariables (data, other.data);
  2267. }
  2268. private:
  2269. ElementType* data;
  2270. HeapBlock (const HeapBlock&);
  2271. HeapBlock& operator= (const HeapBlock&);
  2272. };
  2273. #endif // __JUCE_HEAPBLOCK_JUCEHEADER__
  2274. /*** End of inlined file: juce_HeapBlock.h ***/
  2275. /**
  2276. Implements some basic array storage allocation functions.
  2277. This class isn't really for public use - it's used by the other
  2278. array classes, but might come in handy for some purposes.
  2279. It inherits from a critical section class to allow the arrays to use
  2280. the "empty base class optimisation" pattern to reduce their footprint.
  2281. @see Array, OwnedArray, ReferenceCountedArray
  2282. */
  2283. template <class ElementType, class TypeOfCriticalSectionToUse>
  2284. class ArrayAllocationBase : public TypeOfCriticalSectionToUse
  2285. {
  2286. public:
  2287. /** Creates an empty array. */
  2288. ArrayAllocationBase() throw()
  2289. : numAllocated (0)
  2290. {
  2291. }
  2292. /** Destructor. */
  2293. ~ArrayAllocationBase()
  2294. {
  2295. }
  2296. /** Changes the amount of storage allocated.
  2297. This will retain any data currently held in the array, and either add or
  2298. remove extra space at the end.
  2299. @param numElements the number of elements that are needed
  2300. */
  2301. void setAllocatedSize (const int numElements)
  2302. {
  2303. if (numAllocated != numElements)
  2304. {
  2305. if (numElements > 0)
  2306. elements.realloc (numElements);
  2307. else
  2308. elements.free();
  2309. numAllocated = numElements;
  2310. }
  2311. }
  2312. /** Increases the amount of storage allocated if it is less than a given amount.
  2313. This will retain any data currently held in the array, but will add
  2314. extra space at the end to make sure there it's at least as big as the size
  2315. passed in. If it's already bigger, no action is taken.
  2316. @param minNumElements the minimum number of elements that are needed
  2317. */
  2318. void ensureAllocatedSize (const int minNumElements)
  2319. {
  2320. if (minNumElements > numAllocated)
  2321. setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
  2322. }
  2323. /** Minimises the amount of storage allocated so that it's no more than
  2324. the given number of elements.
  2325. */
  2326. void shrinkToNoMoreThan (const int maxNumElements)
  2327. {
  2328. if (maxNumElements < numAllocated)
  2329. setAllocatedSize (maxNumElements);
  2330. }
  2331. /** Swap the contents of two objects. */
  2332. void swapWith (ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  2333. {
  2334. elements.swapWith (other.elements);
  2335. swapVariables (numAllocated, other.numAllocated);
  2336. }
  2337. HeapBlock <ElementType> elements;
  2338. int numAllocated;
  2339. private:
  2340. ArrayAllocationBase (const ArrayAllocationBase&);
  2341. ArrayAllocationBase& operator= (const ArrayAllocationBase&);
  2342. };
  2343. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2344. /*** End of inlined file: juce_ArrayAllocationBase.h ***/
  2345. /*** Start of inlined file: juce_ElementComparator.h ***/
  2346. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2347. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2348. /**
  2349. Sorts a range of elements in an array.
  2350. The comparator object that is passed-in must define a public method with the following
  2351. signature:
  2352. @code
  2353. int compareElements (ElementType first, ElementType second);
  2354. @endcode
  2355. ..and this method must return:
  2356. - a value of < 0 if the first comes before the second
  2357. - a value of 0 if the two objects are equivalent
  2358. - a value of > 0 if the second comes before the first
  2359. To improve performance, the compareElements() method can be declared as static or const.
  2360. @param comparator an object which defines a compareElements() method
  2361. @param array the array to sort
  2362. @param firstElement the index of the first element of the range to be sorted
  2363. @param lastElement the index of the last element in the range that needs
  2364. sorting (this is inclusive)
  2365. @param retainOrderOfEquivalentItems if true, the order of items that the
  2366. comparator deems the same will be maintained - this will be
  2367. a slower algorithm than if they are allowed to be moved around.
  2368. @see sortArrayRetainingOrder
  2369. */
  2370. template <class ElementType, class ElementComparator>
  2371. static void sortArray (ElementComparator& comparator,
  2372. ElementType* const array,
  2373. int firstElement,
  2374. int lastElement,
  2375. const bool retainOrderOfEquivalentItems)
  2376. {
  2377. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2378. // avoids getting warning messages about the parameter being unused
  2379. if (lastElement > firstElement)
  2380. {
  2381. if (retainOrderOfEquivalentItems)
  2382. {
  2383. for (int i = firstElement; i < lastElement; ++i)
  2384. {
  2385. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  2386. {
  2387. const ElementType temp = array [i];
  2388. array [i] = array[i + 1];
  2389. array [i + 1] = temp;
  2390. if (i > firstElement)
  2391. i -= 2;
  2392. }
  2393. }
  2394. }
  2395. else
  2396. {
  2397. int fromStack[30], toStack[30];
  2398. int stackIndex = 0;
  2399. for (;;)
  2400. {
  2401. const int size = (lastElement - firstElement) + 1;
  2402. if (size <= 8)
  2403. {
  2404. int j = lastElement;
  2405. int maxIndex;
  2406. while (j > firstElement)
  2407. {
  2408. maxIndex = firstElement;
  2409. for (int k = firstElement + 1; k <= j; ++k)
  2410. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  2411. maxIndex = k;
  2412. const ElementType temp = array [maxIndex];
  2413. array [maxIndex] = array[j];
  2414. array [j] = temp;
  2415. --j;
  2416. }
  2417. }
  2418. else
  2419. {
  2420. const int mid = firstElement + (size >> 1);
  2421. ElementType temp = array [mid];
  2422. array [mid] = array [firstElement];
  2423. array [firstElement] = temp;
  2424. int i = firstElement;
  2425. int j = lastElement + 1;
  2426. for (;;)
  2427. {
  2428. while (++i <= lastElement
  2429. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  2430. {}
  2431. while (--j > firstElement
  2432. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  2433. {}
  2434. if (j < i)
  2435. break;
  2436. temp = array[i];
  2437. array[i] = array[j];
  2438. array[j] = temp;
  2439. }
  2440. temp = array [firstElement];
  2441. array [firstElement] = array[j];
  2442. array [j] = temp;
  2443. if (j - 1 - firstElement >= lastElement - i)
  2444. {
  2445. if (firstElement + 1 < j)
  2446. {
  2447. fromStack [stackIndex] = firstElement;
  2448. toStack [stackIndex] = j - 1;
  2449. ++stackIndex;
  2450. }
  2451. if (i < lastElement)
  2452. {
  2453. firstElement = i;
  2454. continue;
  2455. }
  2456. }
  2457. else
  2458. {
  2459. if (i < lastElement)
  2460. {
  2461. fromStack [stackIndex] = i;
  2462. toStack [stackIndex] = lastElement;
  2463. ++stackIndex;
  2464. }
  2465. if (firstElement + 1 < j)
  2466. {
  2467. lastElement = j - 1;
  2468. continue;
  2469. }
  2470. }
  2471. }
  2472. if (--stackIndex < 0)
  2473. break;
  2474. jassert (stackIndex < numElementsInArray (fromStack));
  2475. firstElement = fromStack [stackIndex];
  2476. lastElement = toStack [stackIndex];
  2477. }
  2478. }
  2479. }
  2480. }
  2481. /**
  2482. Searches a sorted array of elements, looking for the index at which a specified value
  2483. should be inserted for it to be in the correct order.
  2484. The comparator object that is passed-in must define a public method with the following
  2485. signature:
  2486. @code
  2487. int compareElements (ElementType first, ElementType second);
  2488. @endcode
  2489. ..and this method must return:
  2490. - a value of < 0 if the first comes before the second
  2491. - a value of 0 if the two objects are equivalent
  2492. - a value of > 0 if the second comes before the first
  2493. To improve performance, the compareElements() method can be declared as static or const.
  2494. @param comparator an object which defines a compareElements() method
  2495. @param array the array to search
  2496. @param newElement the value that is going to be inserted
  2497. @param firstElement the index of the first element to search
  2498. @param lastElement the index of the last element in the range (this is non-inclusive)
  2499. */
  2500. template <class ElementType, class ElementComparator>
  2501. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  2502. ElementType* const array,
  2503. const ElementType newElement,
  2504. int firstElement,
  2505. int lastElement)
  2506. {
  2507. jassert (firstElement <= lastElement);
  2508. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2509. // avoids getting warning messages about the parameter being unused
  2510. while (firstElement < lastElement)
  2511. {
  2512. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  2513. {
  2514. ++firstElement;
  2515. break;
  2516. }
  2517. else
  2518. {
  2519. const int halfway = (firstElement + lastElement) >> 1;
  2520. if (halfway == firstElement)
  2521. {
  2522. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2523. ++firstElement;
  2524. break;
  2525. }
  2526. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2527. {
  2528. firstElement = halfway;
  2529. }
  2530. else
  2531. {
  2532. lastElement = halfway;
  2533. }
  2534. }
  2535. }
  2536. return firstElement;
  2537. }
  2538. /**
  2539. A simple ElementComparator class that can be used to sort an array of
  2540. objects that support the '<' operator.
  2541. This will work for primitive types and objects that implement operator<().
  2542. Example: @code
  2543. Array <int> myArray;
  2544. DefaultElementComparator<int> sorter;
  2545. myArray.sort (sorter);
  2546. @endcode
  2547. @see ElementComparator
  2548. */
  2549. template <class ElementType>
  2550. class DefaultElementComparator
  2551. {
  2552. private:
  2553. typedef PARAMETER_TYPE (ElementType) ParameterType;
  2554. public:
  2555. static int compareElements (ParameterType first, ParameterType second)
  2556. {
  2557. return (first < second) ? -1 : ((second < first) ? 1 : 0);
  2558. }
  2559. };
  2560. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2561. /*** End of inlined file: juce_ElementComparator.h ***/
  2562. /*** Start of inlined file: juce_CriticalSection.h ***/
  2563. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  2564. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  2565. class JUCE_API ScopedLock;
  2566. class JUCE_API ScopedUnlock;
  2567. /**
  2568. Prevents multiple threads from accessing shared objects at the same time.
  2569. @see ScopedLock, Thread, InterProcessLock
  2570. */
  2571. class JUCE_API CriticalSection
  2572. {
  2573. public:
  2574. /**
  2575. Creates a CriticalSection object
  2576. */
  2577. CriticalSection() throw();
  2578. /** Destroys a CriticalSection object.
  2579. If the critical section is deleted whilst locked, its subsequent behaviour
  2580. is unpredictable.
  2581. */
  2582. ~CriticalSection() throw();
  2583. /** Locks this critical section.
  2584. If the lock is currently held by another thread, this will wait until it
  2585. becomes free.
  2586. If the lock is already held by the caller thread, the method returns immediately.
  2587. @see exit, ScopedLock
  2588. */
  2589. void enter() const throw();
  2590. /** Attempts to lock this critical section without blocking.
  2591. This method behaves identically to CriticalSection::enter, except that the caller thread
  2592. does not wait if the lock is currently held by another thread but returns false immediately.
  2593. @returns false if the lock is currently held by another thread, true otherwise.
  2594. @see enter
  2595. */
  2596. bool tryEnter() const throw();
  2597. /** Releases the lock.
  2598. If the caller thread hasn't got the lock, this can have unpredictable results.
  2599. If the enter() method has been called multiple times by the thread, each
  2600. call must be matched by a call to exit() before other threads will be allowed
  2601. to take over the lock.
  2602. @see enter, ScopedLock
  2603. */
  2604. void exit() const throw();
  2605. /** Provides the type of scoped lock to use with this type of critical section object. */
  2606. typedef ScopedLock ScopedLockType;
  2607. /** Provides the type of scoped unlocker to use with this type of critical section object. */
  2608. typedef ScopedUnlock ScopedUnlockType;
  2609. juce_UseDebuggingNewOperator
  2610. private:
  2611. #if JUCE_WINDOWS
  2612. #if JUCE_64BIT
  2613. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  2614. // block of memory here that's big enough to be used internally as a windows critical
  2615. // section object.
  2616. uint8 internal [44];
  2617. #else
  2618. uint8 internal [24];
  2619. #endif
  2620. #else
  2621. mutable pthread_mutex_t internal;
  2622. #endif
  2623. CriticalSection (const CriticalSection&);
  2624. CriticalSection& operator= (const CriticalSection&);
  2625. };
  2626. /**
  2627. A class that can be used in place of a real CriticalSection object.
  2628. This is currently used by some templated classes, and should get
  2629. optimised out by the compiler.
  2630. @see Array, OwnedArray, ReferenceCountedArray
  2631. */
  2632. class JUCE_API DummyCriticalSection
  2633. {
  2634. public:
  2635. inline DummyCriticalSection() throw() {}
  2636. inline ~DummyCriticalSection() throw() {}
  2637. inline void enter() const throw() {}
  2638. inline void exit() const throw() {}
  2639. /** A dummy scoped-lock type to use with a dummy critical section. */
  2640. struct ScopedLockType
  2641. {
  2642. ScopedLockType (const DummyCriticalSection&) throw() {}
  2643. };
  2644. /** A dummy scoped-unlocker type to use with a dummy critical section. */
  2645. typedef ScopedLockType ScopedUnlockType;
  2646. private:
  2647. DummyCriticalSection (const DummyCriticalSection&);
  2648. DummyCriticalSection& operator= (const DummyCriticalSection&);
  2649. };
  2650. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  2651. /*** End of inlined file: juce_CriticalSection.h ***/
  2652. /**
  2653. Holds a list of simple objects, such as ints, doubles, or pointers.
  2654. Examples of arrays are: Array<int>, Array<Rectangle> or Array<MyClass*>
  2655. The array can be used to hold simple, non-polymorphic objects as well as primitive types - to
  2656. do so, the class must fulfil these requirements:
  2657. - it must have a copy constructor and operator=
  2658. - it must be able to be relocated in memory by a memcpy without this causing a problem - so no
  2659. objects whose functionality relies on pointers or references to themselves can be used.
  2660. You can of course have an array of pointers to any kind of object, e.g. Array <MyClass*>, but if
  2661. you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the
  2662. ReferenceCountedArray class for more powerful ways of holding lists of objects.
  2663. For holding lists of strings, you can use Array\<String\>, but it's usually better to use the
  2664. specialised class StringArray, which provides more useful functions.
  2665. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  2666. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  2667. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  2668. */
  2669. template <typename ElementType,
  2670. typename TypeOfCriticalSectionToUse = DummyCriticalSection>
  2671. class Array
  2672. {
  2673. private:
  2674. #if defined (_MSC_VER) && _MSC_VER <= 1400
  2675. typedef const ElementType& ParameterType;
  2676. #else
  2677. typedef PARAMETER_TYPE (ElementType) ParameterType;
  2678. #endif
  2679. public:
  2680. /** Creates an empty array. */
  2681. Array() throw()
  2682. : numUsed (0)
  2683. {
  2684. }
  2685. /** Creates a copy of another array.
  2686. @param other the array to copy
  2687. */
  2688. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other)
  2689. {
  2690. const ScopedLockType lock (other.getLock());
  2691. numUsed = other.numUsed;
  2692. data.setAllocatedSize (other.numUsed);
  2693. for (int i = 0; i < numUsed; ++i)
  2694. new (data.elements + i) ElementType (other.data.elements[i]);
  2695. }
  2696. /** Initalises from a null-terminated C array of values.
  2697. @param values the array to copy from
  2698. */
  2699. template <typename TypeToCreateFrom>
  2700. explicit Array (const TypeToCreateFrom* values)
  2701. : numUsed (0)
  2702. {
  2703. while (*values != TypeToCreateFrom())
  2704. add (*values++);
  2705. }
  2706. /** Initalises from a C array of values.
  2707. @param values the array to copy from
  2708. @param numValues the number of values in the array
  2709. */
  2710. template <typename TypeToCreateFrom>
  2711. Array (const TypeToCreateFrom* values, int numValues)
  2712. : numUsed (numValues)
  2713. {
  2714. data.setAllocatedSize (numValues);
  2715. for (int i = 0; i < numValues; ++i)
  2716. new (data.elements + i) ElementType (values[i]);
  2717. }
  2718. /** Destructor. */
  2719. ~Array()
  2720. {
  2721. for (int i = 0; i < numUsed; ++i)
  2722. data.elements[i].~ElementType();
  2723. }
  2724. /** Copies another array.
  2725. @param other the array to copy
  2726. */
  2727. Array& operator= (const Array& other)
  2728. {
  2729. if (this != &other)
  2730. {
  2731. Array<ElementType, TypeOfCriticalSectionToUse> otherCopy (other);
  2732. swapWithArray (otherCopy);
  2733. }
  2734. return *this;
  2735. }
  2736. /** Compares this array to another one.
  2737. Two arrays are considered equal if they both contain the same set of
  2738. elements, in the same order.
  2739. @param other the other array to compare with
  2740. */
  2741. template <class OtherArrayType>
  2742. bool operator== (const OtherArrayType& other) const
  2743. {
  2744. const ScopedLockType lock (getLock());
  2745. if (numUsed != other.numUsed)
  2746. return false;
  2747. for (int i = numUsed; --i >= 0;)
  2748. if (! (data.elements [i] == other.data.elements [i]))
  2749. return false;
  2750. return true;
  2751. }
  2752. /** Compares this array to another one.
  2753. Two arrays are considered equal if they both contain the same set of
  2754. elements, in the same order.
  2755. @param other the other array to compare with
  2756. */
  2757. template <class OtherArrayType>
  2758. bool operator!= (const OtherArrayType& other) const
  2759. {
  2760. return ! operator== (other);
  2761. }
  2762. /** Removes all elements from the array.
  2763. This will remove all the elements, and free any storage that the array is
  2764. using. To clear the array without freeing the storage, use the clearQuick()
  2765. method instead.
  2766. @see clearQuick
  2767. */
  2768. void clear()
  2769. {
  2770. const ScopedLockType lock (getLock());
  2771. for (int i = 0; i < numUsed; ++i)
  2772. data.elements[i].~ElementType();
  2773. data.setAllocatedSize (0);
  2774. numUsed = 0;
  2775. }
  2776. /** Removes all elements from the array without freeing the array's allocated storage.
  2777. @see clear
  2778. */
  2779. void clearQuick()
  2780. {
  2781. const ScopedLockType lock (getLock());
  2782. for (int i = 0; i < numUsed; ++i)
  2783. data.elements[i].~ElementType();
  2784. numUsed = 0;
  2785. }
  2786. /** Returns the current number of elements in the array.
  2787. */
  2788. inline int size() const throw()
  2789. {
  2790. return numUsed;
  2791. }
  2792. /** Returns one of the elements in the array.
  2793. If the index passed in is beyond the range of valid elements, this
  2794. will return zero.
  2795. If you're certain that the index will always be a valid element, you
  2796. can call getUnchecked() instead, which is faster.
  2797. @param index the index of the element being requested (0 is the first element in the array)
  2798. @see getUnchecked, getFirst, getLast
  2799. */
  2800. inline ElementType operator[] (const int index) const
  2801. {
  2802. const ScopedLockType lock (getLock());
  2803. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  2804. : ElementType();
  2805. }
  2806. /** Returns one of the elements in the array, without checking the index passed in.
  2807. Unlike the operator[] method, this will try to return an element without
  2808. checking that the index is within the bounds of the array, so should only
  2809. be used when you're confident that it will always be a valid index.
  2810. @param index the index of the element being requested (0 is the first element in the array)
  2811. @see operator[], getFirst, getLast
  2812. */
  2813. inline const ElementType getUnchecked (const int index) const
  2814. {
  2815. const ScopedLockType lock (getLock());
  2816. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2817. return data.elements [index];
  2818. }
  2819. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  2820. This is like getUnchecked, but returns a direct reference to the element, so that
  2821. you can alter it directly. Obviously this can be dangerous, so only use it when
  2822. absolutely necessary.
  2823. @param index the index of the element being requested (0 is the first element in the array)
  2824. @see operator[], getFirst, getLast
  2825. */
  2826. inline ElementType& getReference (const int index) const throw()
  2827. {
  2828. const ScopedLockType lock (getLock());
  2829. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2830. return data.elements [index];
  2831. }
  2832. /** Returns the first element in the array, or 0 if the array is empty.
  2833. @see operator[], getUnchecked, getLast
  2834. */
  2835. inline ElementType getFirst() const
  2836. {
  2837. const ScopedLockType lock (getLock());
  2838. return (numUsed > 0) ? data.elements [0]
  2839. : ElementType();
  2840. }
  2841. /** Returns the last element in the array, or 0 if the array is empty.
  2842. @see operator[], getUnchecked, getFirst
  2843. */
  2844. inline ElementType getLast() const
  2845. {
  2846. const ScopedLockType lock (getLock());
  2847. return (numUsed > 0) ? data.elements [numUsed - 1]
  2848. : ElementType();
  2849. }
  2850. /** Returns a pointer to the actual array data.
  2851. This pointer will only be valid until the next time a non-const method
  2852. is called on the array.
  2853. */
  2854. inline ElementType* getRawDataPointer() throw()
  2855. {
  2856. return data.elements;
  2857. }
  2858. /** Finds the index of the first element which matches the value passed in.
  2859. This will search the array for the given object, and return the index
  2860. of its first occurrence. If the object isn't found, the method will return -1.
  2861. @param elementToLookFor the value or object to look for
  2862. @returns the index of the object, or -1 if it's not found
  2863. */
  2864. int indexOf (ParameterType elementToLookFor) const
  2865. {
  2866. const ScopedLockType lock (getLock());
  2867. const ElementType* e = data.elements.getData();
  2868. const ElementType* const end = e + numUsed;
  2869. while (e != end)
  2870. {
  2871. if (elementToLookFor == *e)
  2872. return static_cast <int> (e - data.elements.getData());
  2873. ++e;
  2874. }
  2875. return -1;
  2876. }
  2877. /** Returns true if the array contains at least one occurrence of an object.
  2878. @param elementToLookFor the value or object to look for
  2879. @returns true if the item is found
  2880. */
  2881. bool contains (ParameterType elementToLookFor) const
  2882. {
  2883. const ScopedLockType lock (getLock());
  2884. const ElementType* e = data.elements.getData();
  2885. const ElementType* const end = e + numUsed;
  2886. while (e != end)
  2887. {
  2888. if (elementToLookFor == *e)
  2889. return true;
  2890. ++e;
  2891. }
  2892. return false;
  2893. }
  2894. /** Appends a new element at the end of the array.
  2895. @param newElement the new object to add to the array
  2896. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  2897. */
  2898. void add (ParameterType newElement)
  2899. {
  2900. const ScopedLockType lock (getLock());
  2901. data.ensureAllocatedSize (numUsed + 1);
  2902. new (data.elements + numUsed++) ElementType (newElement);
  2903. }
  2904. /** Inserts a new element into the array at a given position.
  2905. If the index is less than 0 or greater than the size of the array, the
  2906. element will be added to the end of the array.
  2907. Otherwise, it will be inserted into the array, moving all the later elements
  2908. along to make room.
  2909. @param indexToInsertAt the index at which the new element should be
  2910. inserted (pass in -1 to add it to the end)
  2911. @param newElement the new object to add to the array
  2912. @see add, addSorted, addUsingDefaultSort, set
  2913. */
  2914. void insert (int indexToInsertAt, ParameterType newElement)
  2915. {
  2916. const ScopedLockType lock (getLock());
  2917. data.ensureAllocatedSize (numUsed + 1);
  2918. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2919. {
  2920. ElementType* const insertPos = data.elements + indexToInsertAt;
  2921. const int numberToMove = numUsed - indexToInsertAt;
  2922. if (numberToMove > 0)
  2923. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  2924. new (insertPos) ElementType (newElement);
  2925. ++numUsed;
  2926. }
  2927. else
  2928. {
  2929. new (data.elements + numUsed++) ElementType (newElement);
  2930. }
  2931. }
  2932. /** Inserts multiple copies of an element into the array at a given position.
  2933. If the index is less than 0 or greater than the size of the array, the
  2934. element will be added to the end of the array.
  2935. Otherwise, it will be inserted into the array, moving all the later elements
  2936. along to make room.
  2937. @param indexToInsertAt the index at which the new element should be inserted
  2938. @param newElement the new object to add to the array
  2939. @param numberOfTimesToInsertIt how many copies of the value to insert
  2940. @see insert, add, addSorted, set
  2941. */
  2942. void insertMultiple (int indexToInsertAt, ParameterType newElement,
  2943. int numberOfTimesToInsertIt)
  2944. {
  2945. if (numberOfTimesToInsertIt > 0)
  2946. {
  2947. const ScopedLockType lock (getLock());
  2948. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  2949. ElementType* insertPos;
  2950. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2951. {
  2952. insertPos = data.elements + indexToInsertAt;
  2953. const int numberToMove = numUsed - indexToInsertAt;
  2954. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  2955. }
  2956. else
  2957. {
  2958. insertPos = data.elements + numUsed;
  2959. }
  2960. numUsed += numberOfTimesToInsertIt;
  2961. while (--numberOfTimesToInsertIt >= 0)
  2962. new (insertPos++) ElementType (newElement);
  2963. }
  2964. }
  2965. /** Inserts an array of values into this array at a given position.
  2966. If the index is less than 0 or greater than the size of the array, the
  2967. new elements will be added to the end of the array.
  2968. Otherwise, they will be inserted into the array, moving all the later elements
  2969. along to make room.
  2970. @param indexToInsertAt the index at which the first new element should be inserted
  2971. @param newElements the new values to add to the array
  2972. @param numberOfElements how many items are in the array
  2973. @see insert, add, addSorted, set
  2974. */
  2975. void insertArray (int indexToInsertAt,
  2976. const ElementType* newElements,
  2977. int numberOfElements)
  2978. {
  2979. if (numberOfElements > 0)
  2980. {
  2981. const ScopedLockType lock (getLock());
  2982. data.ensureAllocatedSize (numUsed + numberOfElements);
  2983. ElementType* insertPos;
  2984. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2985. {
  2986. insertPos = data.elements + indexToInsertAt;
  2987. const int numberToMove = numUsed - indexToInsertAt;
  2988. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  2989. }
  2990. else
  2991. {
  2992. insertPos = data.elements + numUsed;
  2993. }
  2994. numUsed += numberOfElements;
  2995. while (--numberOfElements >= 0)
  2996. new (insertPos++) ElementType (*newElements++);
  2997. }
  2998. }
  2999. /** Appends a new element at the end of the array as long as the array doesn't
  3000. already contain it.
  3001. If the array already contains an element that matches the one passed in, nothing
  3002. will be done.
  3003. @param newElement the new object to add to the array
  3004. */
  3005. void addIfNotAlreadyThere (ParameterType newElement)
  3006. {
  3007. const ScopedLockType lock (getLock());
  3008. if (! contains (newElement))
  3009. add (newElement);
  3010. }
  3011. /** Replaces an element with a new value.
  3012. If the index is less than zero, this method does nothing.
  3013. If the index is beyond the end of the array, the item is added to the end of the array.
  3014. @param indexToChange the index whose value you want to change
  3015. @param newValue the new value to set for this index.
  3016. @see add, insert
  3017. */
  3018. void set (const int indexToChange, ParameterType newValue)
  3019. {
  3020. jassert (indexToChange >= 0);
  3021. const ScopedLockType lock (getLock());
  3022. if (((unsigned int) indexToChange) < (unsigned int) numUsed)
  3023. {
  3024. data.elements [indexToChange] = newValue;
  3025. }
  3026. else if (indexToChange >= 0)
  3027. {
  3028. data.ensureAllocatedSize (numUsed + 1);
  3029. new (data.elements + numUsed++) ElementType (newValue);
  3030. }
  3031. }
  3032. /** Replaces an element with a new value without doing any bounds-checking.
  3033. This just sets a value directly in the array's internal storage, so you'd
  3034. better make sure it's in range!
  3035. @param indexToChange the index whose value you want to change
  3036. @param newValue the new value to set for this index.
  3037. @see set, getUnchecked
  3038. */
  3039. void setUnchecked (const int indexToChange, ParameterType newValue)
  3040. {
  3041. const ScopedLockType lock (getLock());
  3042. jassert (((unsigned int) indexToChange) < (unsigned int) numUsed);
  3043. data.elements [indexToChange] = newValue;
  3044. }
  3045. /** Adds elements from an array to the end of this array.
  3046. @param elementsToAdd the array of elements to add
  3047. @param numElementsToAdd how many elements are in this other array
  3048. @see add
  3049. */
  3050. void addArray (const ElementType* elementsToAdd, int numElementsToAdd)
  3051. {
  3052. const ScopedLockType lock (getLock());
  3053. if (numElementsToAdd > 0)
  3054. {
  3055. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  3056. while (--numElementsToAdd >= 0)
  3057. {
  3058. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  3059. ++numUsed;
  3060. }
  3061. }
  3062. }
  3063. /** This swaps the contents of this array with those of another array.
  3064. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  3065. because it just swaps their internal pointers.
  3066. */
  3067. void swapWithArray (Array& otherArray) throw()
  3068. {
  3069. const ScopedLockType lock1 (getLock());
  3070. const ScopedLockType lock2 (otherArray.getLock());
  3071. data.swapWith (otherArray.data);
  3072. swapVariables (numUsed, otherArray.numUsed);
  3073. }
  3074. /** Adds elements from another array to the end of this array.
  3075. @param arrayToAddFrom the array from which to copy the elements
  3076. @param startIndex the first element of the other array to start copying from
  3077. @param numElementsToAdd how many elements to add from the other array. If this
  3078. value is negative or greater than the number of available elements,
  3079. all available elements will be copied.
  3080. @see add
  3081. */
  3082. template <class OtherArrayType>
  3083. void addArray (const OtherArrayType& arrayToAddFrom,
  3084. int startIndex = 0,
  3085. int numElementsToAdd = -1)
  3086. {
  3087. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  3088. const ScopedLockType lock2 (getLock());
  3089. if (startIndex < 0)
  3090. {
  3091. jassertfalse;
  3092. startIndex = 0;
  3093. }
  3094. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  3095. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  3096. while (--numElementsToAdd >= 0)
  3097. add (arrayToAddFrom.getUnchecked (startIndex++));
  3098. }
  3099. /** Inserts a new element into the array, assuming that the array is sorted.
  3100. This will use a comparator to find the position at which the new element
  3101. should go. If the array isn't sorted, the behaviour of this
  3102. method will be unpredictable.
  3103. @param comparator the comparator to use to compare the elements - see the sort()
  3104. method for details about the form this object should take
  3105. @param newElement the new element to insert to the array
  3106. @see addUsingDefaultSort, add, sort
  3107. */
  3108. template <class ElementComparator>
  3109. void addSorted (ElementComparator& comparator, ParameterType newElement)
  3110. {
  3111. const ScopedLockType lock (getLock());
  3112. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed), newElement);
  3113. }
  3114. /** Inserts a new element into the array, assuming that the array is sorted.
  3115. This will use the DefaultElementComparator class for sorting, so your ElementType
  3116. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  3117. method will be unpredictable.
  3118. @param newElement the new element to insert to the array
  3119. @see addSorted, sort
  3120. */
  3121. void addUsingDefaultSort (ParameterType newElement)
  3122. {
  3123. DefaultElementComparator <ElementType> comparator;
  3124. addSorted (comparator, newElement);
  3125. }
  3126. /** Finds the index of an element in the array, assuming that the array is sorted.
  3127. This will use a comparator to do a binary-chop to find the index of the given
  3128. element, if it exists. If the array isn't sorted, the behaviour of this
  3129. method will be unpredictable.
  3130. @param comparator the comparator to use to compare the elements - see the sort()
  3131. method for details about the form this object should take
  3132. @param elementToLookFor the element to search for
  3133. @returns the index of the element, or -1 if it's not found
  3134. @see addSorted, sort
  3135. */
  3136. template <class ElementComparator>
  3137. int indexOfSorted (ElementComparator& comparator, ParameterType elementToLookFor) const
  3138. {
  3139. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3140. // avoids getting warning messages about the parameter being unused
  3141. const ScopedLockType lock (getLock());
  3142. int start = 0;
  3143. int end = numUsed;
  3144. for (;;)
  3145. {
  3146. if (start >= end)
  3147. {
  3148. return -1;
  3149. }
  3150. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  3151. {
  3152. return start;
  3153. }
  3154. else
  3155. {
  3156. const int halfway = (start + end) >> 1;
  3157. if (halfway == start)
  3158. return -1;
  3159. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  3160. start = halfway;
  3161. else
  3162. end = halfway;
  3163. }
  3164. }
  3165. }
  3166. /** Removes an element from the array.
  3167. This will remove the element at a given index, and move back
  3168. all the subsequent elements to close the gap.
  3169. If the index passed in is out-of-range, nothing will happen.
  3170. @param indexToRemove the index of the element to remove
  3171. @returns the element that has been removed
  3172. @see removeValue, removeRange
  3173. */
  3174. ElementType remove (const int indexToRemove)
  3175. {
  3176. const ScopedLockType lock (getLock());
  3177. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  3178. {
  3179. --numUsed;
  3180. ElementType* const e = data.elements + indexToRemove;
  3181. ElementType removed (*e);
  3182. e->~ElementType();
  3183. const int numberToShift = numUsed - indexToRemove;
  3184. if (numberToShift > 0)
  3185. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  3186. if ((numUsed << 1) < data.numAllocated)
  3187. minimiseStorageOverheads();
  3188. return removed;
  3189. }
  3190. else
  3191. {
  3192. return ElementType();
  3193. }
  3194. }
  3195. /** Removes an item from the array.
  3196. This will remove the first occurrence of the given element from the array.
  3197. If the item isn't found, no action is taken.
  3198. @param valueToRemove the object to try to remove
  3199. @see remove, removeRange
  3200. */
  3201. void removeValue (ParameterType valueToRemove)
  3202. {
  3203. const ScopedLockType lock (getLock());
  3204. ElementType* e = data.elements;
  3205. for (int i = numUsed; --i >= 0;)
  3206. {
  3207. if (valueToRemove == *e)
  3208. {
  3209. remove (static_cast <int> (e - data.elements.getData()));
  3210. break;
  3211. }
  3212. ++e;
  3213. }
  3214. }
  3215. /** Removes a range of elements from the array.
  3216. This will remove a set of elements, starting from the given index,
  3217. and move subsequent elements down to close the gap.
  3218. If the range extends beyond the bounds of the array, it will
  3219. be safely clipped to the size of the array.
  3220. @param startIndex the index of the first element to remove
  3221. @param numberToRemove how many elements should be removed
  3222. @see remove, removeValue
  3223. */
  3224. void removeRange (int startIndex, int numberToRemove)
  3225. {
  3226. const ScopedLockType lock (getLock());
  3227. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  3228. startIndex = jlimit (0, numUsed, startIndex);
  3229. if (endIndex > startIndex)
  3230. {
  3231. ElementType* const e = data.elements + startIndex;
  3232. numberToRemove = endIndex - startIndex;
  3233. for (int i = 0; i < numberToRemove; ++i)
  3234. e[i].~ElementType();
  3235. const int numToShift = numUsed - endIndex;
  3236. if (numToShift > 0)
  3237. memmove (e, e + numberToRemove, numToShift * sizeof (ElementType));
  3238. numUsed -= numberToRemove;
  3239. if ((numUsed << 1) < data.numAllocated)
  3240. minimiseStorageOverheads();
  3241. }
  3242. }
  3243. /** Removes the last n elements from the array.
  3244. @param howManyToRemove how many elements to remove from the end of the array
  3245. @see remove, removeValue, removeRange
  3246. */
  3247. void removeLast (int howManyToRemove = 1)
  3248. {
  3249. const ScopedLockType lock (getLock());
  3250. if (howManyToRemove > numUsed)
  3251. howManyToRemove = numUsed;
  3252. for (int i = 0; i < howManyToRemove; ++i)
  3253. data.elements [numUsed - i].~ElementType();
  3254. numUsed -= howManyToRemove;
  3255. if ((numUsed << 1) < data.numAllocated)
  3256. minimiseStorageOverheads();
  3257. }
  3258. /** Removes any elements which are also in another array.
  3259. @param otherArray the other array in which to look for elements to remove
  3260. @see removeValuesNotIn, remove, removeValue, removeRange
  3261. */
  3262. template <class OtherArrayType>
  3263. void removeValuesIn (const OtherArrayType& otherArray)
  3264. {
  3265. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  3266. const ScopedLockType lock2 (getLock());
  3267. if (this == &otherArray)
  3268. {
  3269. clear();
  3270. }
  3271. else
  3272. {
  3273. if (otherArray.size() > 0)
  3274. {
  3275. for (int i = numUsed; --i >= 0;)
  3276. if (otherArray.contains (data.elements [i]))
  3277. remove (i);
  3278. }
  3279. }
  3280. }
  3281. /** Removes any elements which are not found in another array.
  3282. Only elements which occur in this other array will be retained.
  3283. @param otherArray the array in which to look for elements NOT to remove
  3284. @see removeValuesIn, remove, removeValue, removeRange
  3285. */
  3286. template <class OtherArrayType>
  3287. void removeValuesNotIn (const OtherArrayType& otherArray)
  3288. {
  3289. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  3290. const ScopedLockType lock2 (getLock());
  3291. if (this != &otherArray)
  3292. {
  3293. if (otherArray.size() <= 0)
  3294. {
  3295. clear();
  3296. }
  3297. else
  3298. {
  3299. for (int i = numUsed; --i >= 0;)
  3300. if (! otherArray.contains (data.elements [i]))
  3301. remove (i);
  3302. }
  3303. }
  3304. }
  3305. /** Swaps over two elements in the array.
  3306. This swaps over the elements found at the two indexes passed in.
  3307. If either index is out-of-range, this method will do nothing.
  3308. @param index1 index of one of the elements to swap
  3309. @param index2 index of the other element to swap
  3310. */
  3311. void swap (const int index1,
  3312. const int index2)
  3313. {
  3314. const ScopedLockType lock (getLock());
  3315. if (((unsigned int) index1) < (unsigned int) numUsed
  3316. && ((unsigned int) index2) < (unsigned int) numUsed)
  3317. {
  3318. swapVariables (data.elements [index1],
  3319. data.elements [index2]);
  3320. }
  3321. }
  3322. /** Moves one of the values to a different position.
  3323. This will move the value to a specified index, shuffling along
  3324. any intervening elements as required.
  3325. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  3326. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  3327. @param currentIndex the index of the value to be moved. If this isn't a
  3328. valid index, then nothing will be done
  3329. @param newIndex the index at which you'd like this value to end up. If this
  3330. is less than zero, the value will be moved to the end
  3331. of the array
  3332. */
  3333. void move (const int currentIndex, int newIndex) throw()
  3334. {
  3335. if (currentIndex != newIndex)
  3336. {
  3337. const ScopedLockType lock (getLock());
  3338. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  3339. {
  3340. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  3341. newIndex = numUsed - 1;
  3342. char tempCopy [sizeof (ElementType)];
  3343. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  3344. if (newIndex > currentIndex)
  3345. {
  3346. memmove (data.elements + currentIndex,
  3347. data.elements + currentIndex + 1,
  3348. (newIndex - currentIndex) * sizeof (ElementType));
  3349. }
  3350. else
  3351. {
  3352. memmove (data.elements + newIndex + 1,
  3353. data.elements + newIndex,
  3354. (currentIndex - newIndex) * sizeof (ElementType));
  3355. }
  3356. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  3357. }
  3358. }
  3359. }
  3360. /** Reduces the amount of storage being used by the array.
  3361. Arrays typically allocate slightly more storage than they need, and after
  3362. removing elements, they may have quite a lot of unused space allocated.
  3363. This method will reduce the amount of allocated storage to a minimum.
  3364. */
  3365. void minimiseStorageOverheads()
  3366. {
  3367. const ScopedLockType lock (getLock());
  3368. data.shrinkToNoMoreThan (numUsed);
  3369. }
  3370. /** Increases the array's internal storage to hold a minimum number of elements.
  3371. Calling this before adding a large known number of elements means that
  3372. the array won't have to keep dynamically resizing itself as the elements
  3373. are added, and it'll therefore be more efficient.
  3374. */
  3375. void ensureStorageAllocated (const int minNumElements)
  3376. {
  3377. const ScopedLockType lock (getLock());
  3378. data.ensureAllocatedSize (minNumElements);
  3379. }
  3380. /** Sorts the elements in the array.
  3381. This will use a comparator object to sort the elements into order. The object
  3382. passed must have a method of the form:
  3383. @code
  3384. int compareElements (ElementType first, ElementType second);
  3385. @endcode
  3386. ..and this method must return:
  3387. - a value of < 0 if the first comes before the second
  3388. - a value of 0 if the two objects are equivalent
  3389. - a value of > 0 if the second comes before the first
  3390. To improve performance, the compareElements() method can be declared as static or const.
  3391. @param comparator the comparator to use for comparing elements.
  3392. @param retainOrderOfEquivalentItems if this is true, then items
  3393. which the comparator says are equivalent will be
  3394. kept in the order in which they currently appear
  3395. in the array. This is slower to perform, but may
  3396. be important in some cases. If it's false, a faster
  3397. algorithm is used, but equivalent elements may be
  3398. rearranged.
  3399. @see addSorted, indexOfSorted, sortArray
  3400. */
  3401. template <class ElementComparator>
  3402. void sort (ElementComparator& comparator,
  3403. const bool retainOrderOfEquivalentItems = false) const
  3404. {
  3405. const ScopedLockType lock (getLock());
  3406. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3407. // avoids getting warning messages about the parameter being unused
  3408. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  3409. }
  3410. /** Returns the CriticalSection that locks this array.
  3411. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  3412. an object of ScopedLockType as an RAII lock for it.
  3413. */
  3414. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  3415. /** Returns the type of scoped lock to use for locking this array */
  3416. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  3417. juce_UseDebuggingNewOperator
  3418. private:
  3419. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  3420. int numUsed;
  3421. };
  3422. #endif // __JUCE_ARRAY_JUCEHEADER__
  3423. /*** End of inlined file: juce_Array.h ***/
  3424. #endif
  3425. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  3426. #endif
  3427. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  3428. /*** Start of inlined file: juce_BigInteger.h ***/
  3429. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  3430. #define __JUCE_BIGINTEGER_JUCEHEADER__
  3431. class MemoryBlock;
  3432. /**
  3433. An arbitrarily large integer class.
  3434. A BigInteger can be used in a similar way to a normal integer, but has no size
  3435. limit (except for memory and performance constraints).
  3436. Negative values are possible, but the value isn't stored as 2s-complement, so
  3437. be careful if you use negative values and look at the values of individual bits.
  3438. */
  3439. class JUCE_API BigInteger
  3440. {
  3441. public:
  3442. /** Creates an empty BigInteger */
  3443. BigInteger();
  3444. /** Creates a BigInteger containing an integer value in its low bits.
  3445. The low 32 bits of the number are initialised with this value.
  3446. */
  3447. BigInteger (unsigned int value);
  3448. /** Creates a BigInteger containing an integer value in its low bits.
  3449. The low 32 bits of the number are initialised with the absolute value
  3450. passed in, and its sign is set to reflect the sign of the number.
  3451. */
  3452. BigInteger (int value);
  3453. /** Creates a BigInteger containing an integer value in its low bits.
  3454. The low 64 bits of the number are initialised with the absolute value
  3455. passed in, and its sign is set to reflect the sign of the number.
  3456. */
  3457. BigInteger (int64 value);
  3458. /** Creates a copy of another BigInteger. */
  3459. BigInteger (const BigInteger& other);
  3460. /** Destructor. */
  3461. ~BigInteger();
  3462. /** Copies another BigInteger onto this one. */
  3463. BigInteger& operator= (const BigInteger& other);
  3464. /** Swaps the internal contents of this with another object. */
  3465. void swapWith (BigInteger& other) throw();
  3466. /** Returns the value of a specified bit in the number.
  3467. If the index is out-of-range, the result will be false.
  3468. */
  3469. bool operator[] (int bit) const throw();
  3470. /** Returns true if no bits are set. */
  3471. bool isZero() const throw();
  3472. /** Returns true if the value is 1. */
  3473. bool isOne() const throw();
  3474. /** Attempts to get the lowest bits of the value as an integer.
  3475. If the value is bigger than the integer limits, this will return only the lower bits.
  3476. */
  3477. int toInteger() const throw();
  3478. /** Resets the value to 0. */
  3479. void clear();
  3480. /** Clears a particular bit in the number. */
  3481. void clearBit (int bitNumber) throw();
  3482. /** Sets a specified bit to 1. */
  3483. void setBit (int bitNumber);
  3484. /** Sets or clears a specified bit. */
  3485. void setBit (int bitNumber, bool shouldBeSet);
  3486. /** Sets a range of bits to be either on or off.
  3487. @param startBit the first bit to change
  3488. @param numBits the number of bits to change
  3489. @param shouldBeSet whether to turn these bits on or off
  3490. */
  3491. void setRange (int startBit, int numBits, bool shouldBeSet);
  3492. /** Inserts a bit an a given position, shifting up any bits above it. */
  3493. void insertBit (int bitNumber, bool shouldBeSet);
  3494. /** Returns a range of bits as a new BigInteger.
  3495. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  3496. @see getBitRangeAsInt
  3497. */
  3498. const BigInteger getBitRange (int startBit, int numBits) const;
  3499. /** Returns a range of bits as an integer value.
  3500. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  3501. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  3502. getBitRange().
  3503. */
  3504. int getBitRangeAsInt (int startBit, int numBits) const throw();
  3505. /** Sets a range of bits to an integer value.
  3506. Copies the given integer onto a range of bits, starting at startBit,
  3507. and using up to numBits of the available bits.
  3508. */
  3509. void setBitRangeAsInt (int startBit, int numBits, unsigned int valueToSet);
  3510. /** Shifts a section of bits left or right.
  3511. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  3512. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  3513. */
  3514. void shiftBits (int howManyBitsLeft, int startBit);
  3515. /** Returns the total number of set bits in the value. */
  3516. int countNumberOfSetBits() const throw();
  3517. /** Looks for the index of the next set bit after a given starting point.
  3518. This searches from startIndex (inclusive) upwards for the first set bit,
  3519. and returns its index. If no set bits are found, it returns -1.
  3520. */
  3521. int findNextSetBit (int startIndex = 0) const throw();
  3522. /** Looks for the index of the next clear bit after a given starting point.
  3523. This searches from startIndex (inclusive) upwards for the first clear bit,
  3524. and returns its index.
  3525. */
  3526. int findNextClearBit (int startIndex = 0) const throw();
  3527. /** Returns the index of the highest set bit in the number.
  3528. If the value is zero, this will return -1.
  3529. */
  3530. int getHighestBit() const throw();
  3531. // All the standard arithmetic ops...
  3532. BigInteger& operator+= (const BigInteger& other);
  3533. BigInteger& operator-= (const BigInteger& other);
  3534. BigInteger& operator*= (const BigInteger& other);
  3535. BigInteger& operator/= (const BigInteger& other);
  3536. BigInteger& operator|= (const BigInteger& other);
  3537. BigInteger& operator&= (const BigInteger& other);
  3538. BigInteger& operator^= (const BigInteger& other);
  3539. BigInteger& operator%= (const BigInteger& other);
  3540. BigInteger& operator<<= (int numBitsToShift);
  3541. BigInteger& operator>>= (int numBitsToShift);
  3542. BigInteger& operator++();
  3543. BigInteger& operator--();
  3544. const BigInteger operator++ (int);
  3545. const BigInteger operator-- (int);
  3546. const BigInteger operator-() const;
  3547. const BigInteger operator+ (const BigInteger& other) const;
  3548. const BigInteger operator- (const BigInteger& other) const;
  3549. const BigInteger operator* (const BigInteger& other) const;
  3550. const BigInteger operator/ (const BigInteger& other) const;
  3551. const BigInteger operator| (const BigInteger& other) const;
  3552. const BigInteger operator& (const BigInteger& other) const;
  3553. const BigInteger operator^ (const BigInteger& other) const;
  3554. const BigInteger operator% (const BigInteger& other) const;
  3555. const BigInteger operator<< (int numBitsToShift) const;
  3556. const BigInteger operator>> (int numBitsToShift) const;
  3557. bool operator== (const BigInteger& other) const throw();
  3558. bool operator!= (const BigInteger& other) const throw();
  3559. bool operator< (const BigInteger& other) const throw();
  3560. bool operator<= (const BigInteger& other) const throw();
  3561. bool operator> (const BigInteger& other) const throw();
  3562. bool operator>= (const BigInteger& other) const throw();
  3563. /** Does a signed comparison of two BigIntegers.
  3564. Return values are:
  3565. - 0 if the numbers are the same
  3566. - < 0 if this number is smaller than the other
  3567. - > 0 if this number is bigger than the other
  3568. */
  3569. int compare (const BigInteger& other) const throw();
  3570. /** Compares the magnitudes of two BigIntegers, ignoring their signs.
  3571. Return values are:
  3572. - 0 if the numbers are the same
  3573. - < 0 if this number is smaller than the other
  3574. - > 0 if this number is bigger than the other
  3575. */
  3576. int compareAbsolute (const BigInteger& other) const throw();
  3577. /** Divides this value by another one and returns the remainder.
  3578. This number is divided by other, leaving the quotient in this number,
  3579. with the remainder being copied to the other BigInteger passed in.
  3580. */
  3581. void divideBy (const BigInteger& divisor, BigInteger& remainder);
  3582. /** Returns the largest value that will divide both this value and the one passed-in.
  3583. */
  3584. const BigInteger findGreatestCommonDivisor (BigInteger other) const;
  3585. /** Performs a combined exponent and modulo operation.
  3586. This BigInteger's value becomes (this ^ exponent) % modulus.
  3587. */
  3588. void exponentModulo (const BigInteger& exponent, const BigInteger& modulus);
  3589. /** Performs an inverse modulo on the value.
  3590. i.e. the result is (this ^ -1) mod (modulus).
  3591. */
  3592. void inverseModulo (const BigInteger& modulus);
  3593. /** Returns true if the value is less than zero.
  3594. @see setNegative, negate
  3595. */
  3596. bool isNegative() const throw();
  3597. /** Changes the sign of the number to be positive or negative.
  3598. @see isNegative, negate
  3599. */
  3600. void setNegative (const bool shouldBeNegative) throw();
  3601. /** Inverts the sign of the number.
  3602. @see isNegative, setNegative
  3603. */
  3604. void negate() throw();
  3605. /** Converts the number to a string.
  3606. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  3607. If minimumNumCharacters is greater than 0, the returned string will be
  3608. padded with leading zeros to reach at least that length.
  3609. */
  3610. const String toString (int base, int minimumNumCharacters = 1) const;
  3611. /** Reads the numeric value from a string.
  3612. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  3613. Any invalid characters will be ignored.
  3614. */
  3615. void parseString (const String& text, int base);
  3616. /** Turns the number into a block of binary data.
  3617. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  3618. of the number, and so on.
  3619. @see loadFromMemoryBlock
  3620. */
  3621. const MemoryBlock toMemoryBlock() const;
  3622. /** Converts a block of raw data into a number.
  3623. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  3624. of the number, and so on.
  3625. @see toMemoryBlock
  3626. */
  3627. void loadFromMemoryBlock (const MemoryBlock& data);
  3628. juce_UseDebuggingNewOperator
  3629. private:
  3630. HeapBlock <unsigned int> values;
  3631. int numValues, highestBit;
  3632. bool negative;
  3633. void ensureSize (int numVals);
  3634. static const BigInteger simpleGCD (BigInteger* m, BigInteger* n);
  3635. };
  3636. /** Writes a BigInteger to an OutputStream as a UTF8 decimal string. */
  3637. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value);
  3638. /** For backwards compatibility, BitArray is defined to be an alias for BigInteger.
  3639. */
  3640. typedef BigInteger BitArray;
  3641. #endif // __JUCE_BIGINTEGER_JUCEHEADER__
  3642. /*** End of inlined file: juce_BigInteger.h ***/
  3643. #endif
  3644. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  3645. /*** Start of inlined file: juce_DynamicObject.h ***/
  3646. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  3647. #define __JUCE_DYNAMICOBJECT_JUCEHEADER__
  3648. /*** Start of inlined file: juce_NamedValueSet.h ***/
  3649. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  3650. #define __JUCE_NAMEDVALUESET_JUCEHEADER__
  3651. /*** Start of inlined file: juce_Variant.h ***/
  3652. #ifndef __JUCE_VARIANT_JUCEHEADER__
  3653. #define __JUCE_VARIANT_JUCEHEADER__
  3654. /*** Start of inlined file: juce_Identifier.h ***/
  3655. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  3656. #define __JUCE_IDENTIFIER_JUCEHEADER__
  3657. /*** Start of inlined file: juce_StringPool.h ***/
  3658. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  3659. #define __JUCE_STRINGPOOL_JUCEHEADER__
  3660. /**
  3661. A StringPool holds a set of shared strings, which reduces storage overheads and improves
  3662. comparison speed when dealing with many duplicate strings.
  3663. When you add a string to a pool using getPooledString, it'll return a character
  3664. array containing the same string. This array is owned by the pool, and the same array
  3665. is returned every time a matching string is asked for. This means that it's trivial to
  3666. compare two pooled strings for equality, as you can simply compare their pointers. It
  3667. also cuts down on storage if you're using many copies of the same string.
  3668. */
  3669. class JUCE_API StringPool
  3670. {
  3671. public:
  3672. /** Creates an empty pool. */
  3673. StringPool() throw();
  3674. /** Destructor */
  3675. ~StringPool();
  3676. /** Returns a pointer to a copy of the string that is passed in.
  3677. The pool will always return the same pointer when asked for a string that matches it.
  3678. The pool will own all the pointers that it returns, deleting them when the pool itself
  3679. is deleted.
  3680. */
  3681. const juce_wchar* getPooledString (const String& original);
  3682. /** Returns a pointer to a copy of the string that is passed in.
  3683. The pool will always return the same pointer when asked for a string that matches it.
  3684. The pool will own all the pointers that it returns, deleting them when the pool itself
  3685. is deleted.
  3686. */
  3687. const juce_wchar* getPooledString (const char* original);
  3688. /** Returns a pointer to a copy of the string that is passed in.
  3689. The pool will always return the same pointer when asked for a string that matches it.
  3690. The pool will own all the pointers that it returns, deleting them when the pool itself
  3691. is deleted.
  3692. */
  3693. const juce_wchar* getPooledString (const juce_wchar* original);
  3694. /** Returns the number of strings in the pool. */
  3695. int size() const throw();
  3696. /** Returns one of the strings in the pool, by index. */
  3697. const juce_wchar* operator[] (int index) const throw();
  3698. private:
  3699. Array <String> strings;
  3700. };
  3701. #endif // __JUCE_STRINGPOOL_JUCEHEADER__
  3702. /*** End of inlined file: juce_StringPool.h ***/
  3703. /**
  3704. Represents a string identifier, designed for accessing properties by name.
  3705. Identifier objects are very light and fast to copy, but slower to initialise
  3706. from a string, so it's much faster to keep a static identifier object to refer
  3707. to frequently-used names, rather than constructing them each time you need it.
  3708. @see NamedPropertySet, ValueTree
  3709. */
  3710. class JUCE_API Identifier
  3711. {
  3712. public:
  3713. /** Creates a null identifier. */
  3714. Identifier() throw();
  3715. /** Creates an identifier with a specified name.
  3716. Because this name may need to be used in contexts such as script variables or XML
  3717. tags, it must only contain ascii letters and digits, or the underscore character.
  3718. */
  3719. Identifier (const char* name);
  3720. /** Creates an identifier with a specified name.
  3721. Because this name may need to be used in contexts such as script variables or XML
  3722. tags, it must only contain ascii letters and digits, or the underscore character.
  3723. */
  3724. Identifier (const String& name);
  3725. /** Creates a copy of another identifier. */
  3726. Identifier (const Identifier& other) throw();
  3727. /** Creates a copy of another identifier. */
  3728. Identifier& operator= (const Identifier& other) throw();
  3729. /** Destructor */
  3730. ~Identifier();
  3731. /** Compares two identifiers. This is a very fast operation. */
  3732. inline bool operator== (const Identifier& other) const throw() { return name == other.name; }
  3733. /** Compares two identifiers. This is a very fast operation. */
  3734. inline bool operator!= (const Identifier& other) const throw() { return name != other.name; }
  3735. /** Returns this identifier as a string. */
  3736. const String toString() const { return name; }
  3737. /** Returns this identifier's raw string pointer. */
  3738. operator const juce_wchar*() const throw() { return name; }
  3739. private:
  3740. const juce_wchar* name;
  3741. static StringPool& getPool();
  3742. };
  3743. #endif // __JUCE_IDENTIFIER_JUCEHEADER__
  3744. /*** End of inlined file: juce_Identifier.h ***/
  3745. /*** Start of inlined file: juce_OutputStream.h ***/
  3746. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  3747. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  3748. /*** Start of inlined file: juce_InputStream.h ***/
  3749. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  3750. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  3751. /*** Start of inlined file: juce_MemoryBlock.h ***/
  3752. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  3753. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  3754. /**
  3755. A class to hold a resizable block of raw data.
  3756. */
  3757. class JUCE_API MemoryBlock
  3758. {
  3759. public:
  3760. /** Create an uninitialised block with 0 size. */
  3761. MemoryBlock() throw();
  3762. /** Creates a memory block with a given initial size.
  3763. @param initialSize the size of block to create
  3764. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  3765. */
  3766. MemoryBlock (const size_t initialSize,
  3767. const bool initialiseToZero = false) throw();
  3768. /** Creates a copy of another memory block. */
  3769. MemoryBlock (const MemoryBlock& other) throw();
  3770. /** Creates a memory block using a copy of a block of data.
  3771. @param dataToInitialiseFrom some data to copy into this block
  3772. @param sizeInBytes how much space to use
  3773. */
  3774. MemoryBlock (const void* const dataToInitialiseFrom,
  3775. const size_t sizeInBytes) throw();
  3776. /** Destructor. */
  3777. ~MemoryBlock() throw();
  3778. /** Copies another memory block onto this one.
  3779. This block will be resized and copied to exactly match the other one.
  3780. */
  3781. MemoryBlock& operator= (const MemoryBlock& other) throw();
  3782. /** Compares two memory blocks.
  3783. @returns true only if the two blocks are the same size and have identical contents.
  3784. */
  3785. bool operator== (const MemoryBlock& other) const throw();
  3786. /** Compares two memory blocks.
  3787. @returns true if the two blocks are different sizes or have different contents.
  3788. */
  3789. bool operator!= (const MemoryBlock& other) const throw();
  3790. /** Returns true if the data in this MemoryBlock matches the raw bytes passed-in.
  3791. */
  3792. bool matches (const void* data, size_t dataSize) const throw();
  3793. /** Returns a void pointer to the data.
  3794. Note that the pointer returned will probably become invalid when the
  3795. block is resized.
  3796. */
  3797. void* getData() const throw() { return data; }
  3798. /** Returns a byte from the memory block.
  3799. This returns a reference, so you can also use it to set a byte.
  3800. */
  3801. template <typename Type>
  3802. char& operator[] (const Type offset) const throw() { return data [offset]; }
  3803. /** Returns the block's current allocated size, in bytes. */
  3804. size_t getSize() const throw() { return size; }
  3805. /** Resizes the memory block.
  3806. This will try to keep as much of the block's current content as it can,
  3807. and can optionally be made to clear any new space that gets allocated at
  3808. the end of the block.
  3809. @param newSize the new desired size for the block
  3810. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  3811. whether to clear the new section or just leave it
  3812. uninitialised
  3813. @see ensureSize
  3814. */
  3815. void setSize (const size_t newSize,
  3816. const bool initialiseNewSpaceToZero = false) throw();
  3817. /** Increases the block's size only if it's smaller than a given size.
  3818. @param minimumSize if the block is already bigger than this size, no action
  3819. will be taken; otherwise it will be increased to this size
  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 setSize
  3824. */
  3825. void ensureSize (const size_t minimumSize,
  3826. const bool initialiseNewSpaceToZero = false) throw();
  3827. /** Fills the entire memory block with a repeated byte value.
  3828. This is handy for clearing a block of memory to zero.
  3829. */
  3830. void fillWith (const uint8 valueToUse) throw();
  3831. /** Adds another block of data to the end of this one.
  3832. This block's size will be increased accordingly.
  3833. */
  3834. void append (const void* const data,
  3835. const size_t numBytes) throw();
  3836. /** Exchanges the contents of this and another memory block.
  3837. No actual copying is required for this, so it's very fast.
  3838. */
  3839. void swapWith (MemoryBlock& other) throw();
  3840. /** Copies data into this MemoryBlock from a memory address.
  3841. @param srcData the memory location of the data to copy into this block
  3842. @param destinationOffset the offset in this block at which the data being copied should begin
  3843. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  3844. it will be clipped so not to do anything nasty)
  3845. */
  3846. void copyFrom (const void* srcData,
  3847. int destinationOffset,
  3848. size_t numBytes) throw();
  3849. /** Copies data from this MemoryBlock to a memory address.
  3850. @param destData the memory location to write to
  3851. @param sourceOffset the offset within this block from which the copied data will be read
  3852. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  3853. zeros will be used for that portion of the data)
  3854. */
  3855. void copyTo (void* destData,
  3856. int sourceOffset,
  3857. size_t numBytes) const throw();
  3858. /** Chops out a section of the block.
  3859. This will remove a section of the memory block and close the gap around it,
  3860. shifting any subsequent data downwards and reducing the size of the block.
  3861. If the range specified goes beyond the size of the block, it will be clipped.
  3862. */
  3863. void removeSection (size_t startByte, size_t numBytesToRemove) throw();
  3864. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  3865. characters in the system's default encoding. */
  3866. const String toString() const throw();
  3867. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  3868. The block will be resized to the number of valid bytes read from the string.
  3869. Non-hex characters in the string will be ignored.
  3870. @see String::toHexString()
  3871. */
  3872. void loadFromHexString (const String& sourceHexString) throw();
  3873. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  3874. void setBitRange (size_t bitRangeStart,
  3875. size_t numBits,
  3876. int binaryNumberToApply) throw();
  3877. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  3878. int getBitRange (size_t bitRangeStart,
  3879. size_t numBitsToRead) const throw();
  3880. /** Returns a string of characters that represent the binary contents of this block.
  3881. Uses a 64-bit encoding system to allow binary data to be turned into a string
  3882. of simple non-extended characters, e.g. for storage in XML.
  3883. @see fromBase64Encoding
  3884. */
  3885. const String toBase64Encoding() const throw();
  3886. /** Takes a string of encoded characters and turns it into binary data.
  3887. The string passed in must have been created by to64BitEncoding(), and this
  3888. block will be resized to recreate the original data block.
  3889. @see toBase64Encoding
  3890. */
  3891. bool fromBase64Encoding (const String& encodedString) throw();
  3892. juce_UseDebuggingNewOperator
  3893. private:
  3894. HeapBlock <char> data;
  3895. size_t size;
  3896. };
  3897. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  3898. /*** End of inlined file: juce_MemoryBlock.h ***/
  3899. /** The base class for streams that read data.
  3900. Input and output streams are used throughout the library - subclasses can override
  3901. some or all of the virtual functions to implement their behaviour.
  3902. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  3903. */
  3904. class JUCE_API InputStream
  3905. {
  3906. public:
  3907. /** Destructor. */
  3908. virtual ~InputStream() {}
  3909. /** Returns the total number of bytes available for reading in this stream.
  3910. Note that this is the number of bytes available from the start of the
  3911. stream, not from the current position.
  3912. If the size of the stream isn't actually known, this may return -1.
  3913. */
  3914. virtual int64 getTotalLength() = 0;
  3915. /** Returns true if the stream has no more data to read. */
  3916. virtual bool isExhausted() = 0;
  3917. /** Reads a set of bytes from the stream into a memory buffer.
  3918. This is the only read method that subclasses actually need to implement, as the
  3919. InputStream base class implements the other read methods in terms of this one (although
  3920. it's often more efficient for subclasses to implement them directly).
  3921. @param destBuffer the destination buffer for the data
  3922. @param maxBytesToRead the maximum number of bytes to read - make sure the
  3923. memory block passed in is big enough to contain this
  3924. many bytes.
  3925. @returns the actual number of bytes that were read, which may be less than
  3926. maxBytesToRead if the stream is exhausted before it gets that far
  3927. */
  3928. virtual int read (void* destBuffer, int maxBytesToRead) = 0;
  3929. /** Reads a byte from the stream.
  3930. If the stream is exhausted, this will return zero.
  3931. @see OutputStream::writeByte
  3932. */
  3933. virtual char readByte();
  3934. /** Reads a boolean from the stream.
  3935. The bool is encoded as a single byte - 1 for true, 0 for false.
  3936. If the stream is exhausted, this will return false.
  3937. @see OutputStream::writeBool
  3938. */
  3939. virtual bool readBool();
  3940. /** Reads two bytes from the stream as a little-endian 16-bit value.
  3941. If the next two bytes read are byte1 and byte2, this returns
  3942. (byte1 | (byte2 << 8)).
  3943. If the stream is exhausted partway through reading the bytes, this will return zero.
  3944. @see OutputStream::writeShort, readShortBigEndian
  3945. */
  3946. virtual short readShort();
  3947. /** Reads two bytes from the stream as a little-endian 16-bit value.
  3948. If the next two bytes read are byte1 and byte2, this returns
  3949. (byte2 | (byte1 << 8)).
  3950. If the stream is exhausted partway through reading the bytes, this will return zero.
  3951. @see OutputStream::writeShortBigEndian, readShort
  3952. */
  3953. virtual short readShortBigEndian();
  3954. /** Reads four bytes from the stream as a little-endian 32-bit value.
  3955. If the next four bytes are byte1 to byte4, this returns
  3956. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  3957. If the stream is exhausted partway through reading the bytes, this will return zero.
  3958. @see OutputStream::writeInt, readIntBigEndian
  3959. */
  3960. virtual int readInt();
  3961. /** Reads four bytes from the stream as a big-endian 32-bit value.
  3962. If the next four bytes are byte1 to byte4, this returns
  3963. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  3964. If the stream is exhausted partway through reading the bytes, this will return zero.
  3965. @see OutputStream::writeIntBigEndian, readInt
  3966. */
  3967. virtual int readIntBigEndian();
  3968. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  3969. If the next eight bytes are byte1 to byte8, this returns
  3970. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  3971. If the stream is exhausted partway through reading the bytes, this will return zero.
  3972. @see OutputStream::writeInt64, readInt64BigEndian
  3973. */
  3974. virtual int64 readInt64();
  3975. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  3976. If the next eight bytes are byte1 to byte8, this returns
  3977. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  3978. If the stream is exhausted partway through reading the bytes, this will return zero.
  3979. @see OutputStream::writeInt64BigEndian, readInt64
  3980. */
  3981. virtual int64 readInt64BigEndian();
  3982. /** Reads four bytes as a 32-bit floating point value.
  3983. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  3984. If the stream is exhausted partway through reading the bytes, this will return zero.
  3985. @see OutputStream::writeFloat, readDouble
  3986. */
  3987. virtual float readFloat();
  3988. /** Reads four bytes as a 32-bit floating point value.
  3989. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  3990. If the stream is exhausted partway through reading the bytes, this will return zero.
  3991. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  3992. */
  3993. virtual float readFloatBigEndian();
  3994. /** Reads eight bytes as a 64-bit floating point value.
  3995. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  3996. If the stream is exhausted partway through reading the bytes, this will return zero.
  3997. @see OutputStream::writeDouble, readFloat
  3998. */
  3999. virtual double readDouble();
  4000. /** Reads eight bytes as a 64-bit floating point value.
  4001. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  4002. If the stream is exhausted partway through reading the bytes, this will return zero.
  4003. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  4004. */
  4005. virtual double readDoubleBigEndian();
  4006. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  4007. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  4008. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  4009. @see OutputStream::writeCompressedInt()
  4010. */
  4011. virtual int readCompressedInt();
  4012. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  4013. This will read up to the next "\n" or "\r\n" or end-of-stream.
  4014. After this call, the stream's position will be left pointing to the next character
  4015. following the line-feed, but the linefeeds aren't included in the string that
  4016. is returned.
  4017. */
  4018. virtual const String readNextLine();
  4019. /** Reads a zero-terminated UTF8 string from the stream.
  4020. This will read characters from the stream until it hits a zero character or
  4021. end-of-stream.
  4022. @see OutputStream::writeString, readEntireStreamAsString
  4023. */
  4024. virtual const String readString();
  4025. /** Tries to read the whole stream and turn it into a string.
  4026. This will read from the stream's current position until the end-of-stream, and
  4027. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  4028. */
  4029. virtual const String readEntireStreamAsString();
  4030. /** Reads from the stream and appends the data to a MemoryBlock.
  4031. @param destBlock the block to append the data onto
  4032. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  4033. of bytes that will be read - if it's negative, data
  4034. will be read until the stream is exhausted.
  4035. @returns the number of bytes that were added to the memory block
  4036. */
  4037. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  4038. int maxNumBytesToRead = -1);
  4039. /** Returns the offset of the next byte that will be read from the stream.
  4040. @see setPosition
  4041. */
  4042. virtual int64 getPosition() = 0;
  4043. /** Tries to move the current read position of the stream.
  4044. The position is an absolute number of bytes from the stream's start.
  4045. Some streams might not be able to do this, in which case they should do
  4046. nothing and return false. Others might be able to manage it by resetting
  4047. themselves and skipping to the correct position, although this is
  4048. obviously a bit slow.
  4049. @returns true if the stream manages to reposition itself correctly
  4050. @see getPosition
  4051. */
  4052. virtual bool setPosition (int64 newPosition) = 0;
  4053. /** Reads and discards a number of bytes from the stream.
  4054. Some input streams might implement this efficiently, but the base
  4055. class will just keep reading data until the requisite number of bytes
  4056. have been done.
  4057. */
  4058. virtual void skipNextBytes (int64 numBytesToSkip);
  4059. juce_UseDebuggingNewOperator
  4060. protected:
  4061. InputStream() throw() {}
  4062. };
  4063. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  4064. /*** End of inlined file: juce_InputStream.h ***/
  4065. class File;
  4066. /**
  4067. The base class for streams that write data to some kind of destination.
  4068. Input and output streams are used throughout the library - subclasses can override
  4069. some or all of the virtual functions to implement their behaviour.
  4070. @see InputStream, MemoryOutputStream, FileOutputStream
  4071. */
  4072. class JUCE_API OutputStream
  4073. {
  4074. protected:
  4075. OutputStream();
  4076. public:
  4077. /** Destructor.
  4078. Some subclasses might want to do things like call flush() during their
  4079. destructors.
  4080. */
  4081. virtual ~OutputStream();
  4082. /** If the stream is using a buffer, this will ensure it gets written
  4083. out to the destination. */
  4084. virtual void flush() = 0;
  4085. /** Tries to move the stream's output position.
  4086. Not all streams will be able to seek to a new position - this will return
  4087. false if it fails to work.
  4088. @see getPosition
  4089. */
  4090. virtual bool setPosition (int64 newPosition) = 0;
  4091. /** Returns the stream's current position.
  4092. @see setPosition
  4093. */
  4094. virtual int64 getPosition() = 0;
  4095. /** Writes a block of data to the stream.
  4096. When creating a subclass of OutputStream, this is the only write method
  4097. that needs to be overloaded - the base class has methods for writing other
  4098. types of data which use this to do the work.
  4099. @returns false if the write operation fails for some reason
  4100. */
  4101. virtual bool write (const void* dataToWrite,
  4102. int howManyBytes) = 0;
  4103. /** Writes a single byte to the stream.
  4104. @see InputStream::readByte
  4105. */
  4106. virtual void writeByte (char byte);
  4107. /** Writes a boolean to the stream as a single byte.
  4108. This is encoded as a binary byte (not as text) with a value of 1 or 0.
  4109. @see InputStream::readBool
  4110. */
  4111. virtual void writeBool (bool boolValue);
  4112. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  4113. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  4114. @see InputStream::readShort
  4115. */
  4116. virtual void writeShort (short value);
  4117. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  4118. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  4119. @see InputStream::readShortBigEndian
  4120. */
  4121. virtual void writeShortBigEndian (short value);
  4122. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  4123. @see InputStream::readInt
  4124. */
  4125. virtual void writeInt (int value);
  4126. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  4127. @see InputStream::readIntBigEndian
  4128. */
  4129. virtual void writeIntBigEndian (int value);
  4130. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  4131. @see InputStream::readInt64
  4132. */
  4133. virtual void writeInt64 (int64 value);
  4134. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  4135. @see InputStream::readInt64BigEndian
  4136. */
  4137. virtual void writeInt64BigEndian (int64 value);
  4138. /** Writes a 32-bit floating point value to the stream in a binary format.
  4139. The binary 32-bit encoding of the float is written as a little-endian int.
  4140. @see InputStream::readFloat
  4141. */
  4142. virtual void writeFloat (float value);
  4143. /** Writes a 32-bit floating point value to the stream in a binary format.
  4144. The binary 32-bit encoding of the float is written as a big-endian int.
  4145. @see InputStream::readFloatBigEndian
  4146. */
  4147. virtual void writeFloatBigEndian (float value);
  4148. /** Writes a 64-bit floating point value to the stream in a binary format.
  4149. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  4150. @see InputStream::readDouble
  4151. */
  4152. virtual void writeDouble (double value);
  4153. /** Writes a 64-bit floating point value to the stream in a binary format.
  4154. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  4155. @see InputStream::readDoubleBigEndian
  4156. */
  4157. virtual void writeDoubleBigEndian (double value);
  4158. /** Writes a condensed binary encoding of a 32-bit integer.
  4159. If you're storing a lot of integers which are unlikely to have very large values,
  4160. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  4161. under 0xffff only 3 bytes, etc.
  4162. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  4163. @see InputStream::readCompressedInt
  4164. */
  4165. virtual void writeCompressedInt (int value);
  4166. /** Stores a string in the stream in a binary format.
  4167. This isn't the method to use if you're trying to append text to the end of a
  4168. text-file! It's intended for storing a string so that it can be retrieved later
  4169. by InputStream::readString().
  4170. It writes the string to the stream as UTF8, including the null termination character.
  4171. For appending text to a file, instead use writeText, or operator<<
  4172. @see InputStream::readString, writeText, operator<<
  4173. */
  4174. virtual void writeString (const String& text);
  4175. /** Writes a string of text to the stream.
  4176. It can either write it as UTF8 characters or as unicode, and
  4177. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  4178. should only be done at the start of a file).
  4179. The method also replaces '\\n' characters in the text with '\\r\\n'.
  4180. */
  4181. virtual void writeText (const String& text,
  4182. bool asUnicode,
  4183. bool writeUnicodeHeaderBytes);
  4184. /** Reads data from an input stream and writes it to this stream.
  4185. @param source the stream to read from
  4186. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  4187. less than zero, it will keep reading until the input
  4188. is exhausted)
  4189. */
  4190. virtual int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  4191. juce_UseDebuggingNewOperator
  4192. };
  4193. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  4194. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, int number);
  4195. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  4196. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, double number);
  4197. /** Writes a character to a stream. */
  4198. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, char character);
  4199. /** Writes a null-terminated text string to a stream. */
  4200. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* text);
  4201. /** Writes a block of data from a MemoryBlock to a stream. */
  4202. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data);
  4203. /** Writes the contents of a file to a stream. */
  4204. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead);
  4205. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  4206. /*** End of inlined file: juce_OutputStream.h ***/
  4207. class JUCE_API DynamicObject;
  4208. /**
  4209. A variant class, that can be used to hold a range of primitive values.
  4210. A var object can hold a range of simple primitive values, strings, or
  4211. a reference-counted pointer to a DynamicObject. The var class is intended
  4212. to act like the values used in dynamic scripting languages.
  4213. @see DynamicObject
  4214. */
  4215. class JUCE_API var
  4216. {
  4217. public:
  4218. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  4219. typedef Identifier identifier;
  4220. /** Creates a void variant. */
  4221. var() throw();
  4222. /** Destructor. */
  4223. ~var() throw();
  4224. /** A static var object that can be used where you need an empty variant object. */
  4225. static const var null;
  4226. var (const var& valueToCopy);
  4227. var (int value) throw();
  4228. var (bool value) throw();
  4229. var (double value) throw();
  4230. var (const char* value);
  4231. var (const juce_wchar* value);
  4232. var (const String& value);
  4233. var (DynamicObject* object);
  4234. var (MethodFunction method) throw();
  4235. var& operator= (const var& valueToCopy);
  4236. var& operator= (int value);
  4237. var& operator= (bool value);
  4238. var& operator= (double value);
  4239. var& operator= (const char* value);
  4240. var& operator= (const juce_wchar* value);
  4241. var& operator= (const String& value);
  4242. var& operator= (DynamicObject* object);
  4243. var& operator= (MethodFunction method);
  4244. void swapWith (var& other) throw();
  4245. operator int() const;
  4246. operator bool() const;
  4247. operator float() const;
  4248. operator double() const;
  4249. operator const String() const;
  4250. const String toString() const;
  4251. DynamicObject* getObject() const;
  4252. bool isVoid() const throw() { return type == voidType; }
  4253. bool isInt() const throw() { return type == intType; }
  4254. bool isBool() const throw() { return type == boolType; }
  4255. bool isDouble() const throw() { return type == doubleType; }
  4256. bool isString() const throw() { return type == stringType; }
  4257. bool isObject() const throw() { return type == objectType; }
  4258. bool isMethod() const throw() { return type == methodType; }
  4259. /** Writes a binary representation of this value to a stream.
  4260. The data can be read back later using readFromStream().
  4261. */
  4262. void writeToStream (OutputStream& output) const;
  4263. /** Reads back a stored binary representation of a value.
  4264. The data in the stream must have been written using writeToStream(), or this
  4265. will have unpredictable results.
  4266. */
  4267. static const var readFromStream (InputStream& input);
  4268. /** If this variant is an object, this returns one of its properties. */
  4269. const var operator[] (const Identifier& propertyName) const;
  4270. /** If this variant is an object, this invokes one of its methods with no arguments. */
  4271. const var call (const Identifier& method) const;
  4272. /** If this variant is an object, this invokes one of its methods with one argument. */
  4273. const var call (const Identifier& method, const var& arg1) const;
  4274. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  4275. const var call (const Identifier& method, const var& arg1, const var& arg2) const;
  4276. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  4277. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3);
  4278. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  4279. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  4280. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  4281. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  4282. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  4283. const var invoke (const Identifier& method, const var* arguments, int numArguments) const;
  4284. /** If this variant is a method pointer, this invokes it on a target object. */
  4285. const var invoke (const var& targetObject, const var* arguments, int numArguments) const;
  4286. juce_UseDebuggingNewOperator
  4287. /** Returns true if this var has the same value as the one supplied. */
  4288. bool equals (const var& other) const throw();
  4289. private:
  4290. enum Type
  4291. {
  4292. voidType = 0,
  4293. intType,
  4294. boolType,
  4295. doubleType,
  4296. stringType,
  4297. objectType,
  4298. methodType
  4299. };
  4300. union ValueUnion
  4301. {
  4302. int intValue;
  4303. bool boolValue;
  4304. double doubleValue;
  4305. String* stringValue;
  4306. DynamicObject* objectValue;
  4307. MethodFunction methodValue;
  4308. };
  4309. Type type;
  4310. ValueUnion value;
  4311. };
  4312. bool operator== (const var& v1, const var& v2) throw();
  4313. bool operator!= (const var& v1, const var& v2) throw();
  4314. bool operator== (const var& v1, const String& v2) throw();
  4315. bool operator!= (const var& v1, const String& v2) throw();
  4316. #endif // __JUCE_VARIANT_JUCEHEADER__
  4317. /*** End of inlined file: juce_Variant.h ***/
  4318. /** Holds a set of named var objects.
  4319. This can be used as a basic structure to hold a set of var object, which can
  4320. be retrieved by using their identifier.
  4321. */
  4322. class JUCE_API NamedValueSet
  4323. {
  4324. public:
  4325. /** Creates an empty set. */
  4326. NamedValueSet() throw();
  4327. /** Creates a copy of another set. */
  4328. NamedValueSet (const NamedValueSet& other);
  4329. /** Replaces this set with a copy of another set. */
  4330. NamedValueSet& operator= (const NamedValueSet& other);
  4331. /** Destructor. */
  4332. ~NamedValueSet();
  4333. bool operator== (const NamedValueSet& other) const;
  4334. bool operator!= (const NamedValueSet& other) const;
  4335. /** Returns the total number of values that the set contains. */
  4336. int size() const throw();
  4337. /** Returns the value of a named item.
  4338. If the name isn't found, this will return a void variant.
  4339. @see getProperty
  4340. */
  4341. const var& operator[] (const Identifier& name) const;
  4342. /** Tries to return the named value, but if no such value is found, this will
  4343. instead return the supplied default value.
  4344. */
  4345. const var getWithDefault (const Identifier& name, const var& defaultReturnValue) const;
  4346. /** Returns a pointer to the object holding a named value, or
  4347. null if there is no value with this name. */
  4348. var* getItem (const Identifier& name) const;
  4349. /** Changes or adds a named value.
  4350. @returns true if a value was changed or added; false if the
  4351. value was already set the the value passed-in.
  4352. */
  4353. bool set (const Identifier& name, const var& newValue);
  4354. /** Returns true if the set contains an item with the specified name. */
  4355. bool contains (const Identifier& name) const;
  4356. /** Removes a value from the set.
  4357. @returns true if a value was removed; false if there was no value
  4358. with the name that was given.
  4359. */
  4360. bool remove (const Identifier& name);
  4361. /** Returns the name of the value at a given index.
  4362. The index must be between 0 and size() - 1. Out-of-range indexes will
  4363. return an empty identifier.
  4364. */
  4365. const Identifier getName (int index) const;
  4366. /** Returns the value of the item at a given index.
  4367. The index must be between 0 and size() - 1. Out-of-range indexes will
  4368. return an empty identifier.
  4369. */
  4370. const var getValueAt (int index) const;
  4371. /** Removes all values. */
  4372. void clear();
  4373. juce_UseDebuggingNewOperator
  4374. private:
  4375. struct NamedValue
  4376. {
  4377. NamedValue() throw();
  4378. NamedValue (const Identifier& name, const var& value);
  4379. bool operator== (const NamedValue& other) const throw();
  4380. Identifier name;
  4381. var value;
  4382. };
  4383. Array <NamedValue> values;
  4384. };
  4385. #endif // __JUCE_NAMEDVALUESET_JUCEHEADER__
  4386. /*** End of inlined file: juce_NamedValueSet.h ***/
  4387. /*** Start of inlined file: juce_ReferenceCountedObject.h ***/
  4388. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  4389. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  4390. /*** Start of inlined file: juce_Atomic.h ***/
  4391. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  4392. #define __JUCE_ATOMIC_JUCEHEADER__
  4393. /**
  4394. Simple class to hold a primitive value and perform atomic operations on it.
  4395. The type used must be a 32 or 64 bit primitive, like an int, pointer, etc.
  4396. There are methods to perform most of the basic atomic operations.
  4397. */
  4398. template <typename Type>
  4399. class Atomic
  4400. {
  4401. public:
  4402. /** Creates a new value, initialised to zero. */
  4403. inline Atomic() throw()
  4404. : value (0)
  4405. {
  4406. }
  4407. /** Creates a new value, with a given initial value. */
  4408. inline Atomic (const Type initialValue) throw()
  4409. : value (initialValue)
  4410. {
  4411. }
  4412. /** Copies another value (atomically). */
  4413. inline Atomic (const Atomic& other) throw()
  4414. : value (other.get())
  4415. {
  4416. }
  4417. /** Copies another value onto this one (atomically). */
  4418. inline Atomic& operator= (const Atomic& other) throw()
  4419. {
  4420. set (other.get());
  4421. return *this;
  4422. }
  4423. /** Destructor. */
  4424. inline ~Atomic() throw()
  4425. {
  4426. // This class can only be used for types which are 32 or 64 bits in size.
  4427. static_jassert (sizeof (Type) == 4 || sizeof (Type) == 8);
  4428. }
  4429. /** Atomically reads and returns the current value. */
  4430. Type get() const throw();
  4431. /** Atomically sets the current value. */
  4432. void set (Type newValue) throw();
  4433. /** Atomically sets the current value, returning the value that was replaced. */
  4434. Type exchange (Type value) throw();
  4435. /** Atomically adds a number to this value, returning the new value. */
  4436. Type operator+= (Type amountToAdd) throw();
  4437. /** Atomically subtracts a number from this value, returning the new value. */
  4438. Type operator-= (Type amountToSubtract) throw();
  4439. /** Atomically increments this value, returning the new value. */
  4440. Type operator++() throw();
  4441. /** Atomically decrements this value, returning the new value. */
  4442. Type operator--() throw();
  4443. /** Atomically compares this value with a target value, and if it is equal, sets
  4444. this to be equal to a new value.
  4445. This operation is the atomic equivalent of doing this:
  4446. @code
  4447. bool compareAndSetBool (Type newValue, Type valueToCompare)
  4448. {
  4449. if (get() == valueToCompare)
  4450. {
  4451. set (newValue);
  4452. return true;
  4453. }
  4454. return false;
  4455. }
  4456. @endcode
  4457. @returns true if the comparison was true and the value was replaced; false if
  4458. the comparison failed and the value was left unchanged.
  4459. @see compareAndSetValue
  4460. */
  4461. bool compareAndSetBool (Type newValue, Type valueToCompare) throw();
  4462. /** Atomically compares this value with a target value, and if it is equal, sets
  4463. this to be equal to a new value.
  4464. This operation is the atomic equivalent of doing this:
  4465. @code
  4466. Type compareAndSetValue (Type newValue, Type valueToCompare)
  4467. {
  4468. Type oldValue = get();
  4469. if (oldValue == valueToCompare)
  4470. set (newValue);
  4471. return oldValue;
  4472. }
  4473. @endcode
  4474. @returns the old value before it was changed.
  4475. @see compareAndSetBool
  4476. */
  4477. Type compareAndSetValue (Type newValue, Type valueToCompare) throw();
  4478. /** Implements a memory read/write barrier. */
  4479. static void memoryBarrier() throw();
  4480. JUCE_ALIGN(8)
  4481. /** The raw value that this class operates on.
  4482. This is exposed publically in case you need to manipulate it directly
  4483. for performance reasons.
  4484. */
  4485. Type value;
  4486. };
  4487. /*
  4488. The following code is in the header so that the atomics can be inlined where possible...
  4489. */
  4490. #if (JUCE_IPHONE && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_3_2 || ! defined (__IPHONE_3_2))) \
  4491. || (JUCE_MAC && (JUCE_PPC || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)))
  4492. #define JUCE_ATOMICS_MAC 1 // Older OSX builds using gcc4.1 or earlier
  4493. #if JUCE_PPC || JUCE_IPHONE
  4494. // None of these atomics are available for PPC or for iPhoneOS 3.1 or earlier!!
  4495. template <typename Type> static Type OSAtomicAdd64 (Type b, volatile Type* a) throw() { jassertfalse; return *a += b; }
  4496. template <typename Type> static Type OSAtomicIncrement64 (volatile Type* a) throw() { jassertfalse; return ++*a; }
  4497. template <typename Type> static Type OSAtomicDecrement64 (volatile Type* a) throw() { jassertfalse; return --*a; }
  4498. template <typename Type> static bool OSAtomicCompareAndSwap64Barrier (Type old, Type newValue, volatile Type* value) throw()
  4499. { jassertfalse; if (old == *value) { *value = newValue; return true; } return false; }
  4500. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  4501. #endif
  4502. #elif JUCE_GCC
  4503. #define JUCE_ATOMICS_GCC 1 // GCC with intrinsics
  4504. #else
  4505. #define JUCE_ATOMICS_WINDOWS 1 // Windows with intrinsics
  4506. #if JUCE_USE_INTRINSICS || JUCE_64BIT
  4507. #pragma intrinsic (_InterlockedExchange, _InterlockedIncrement, _InterlockedDecrement, _InterlockedCompareExchange, \
  4508. _InterlockedCompareExchange64, _InterlockedExchangeAdd, _ReadWriteBarrier)
  4509. #define juce_InterlockedExchange(a, b) _InterlockedExchange(a, b)
  4510. #define juce_InterlockedIncrement(a) _InterlockedIncrement(a)
  4511. #define juce_InterlockedDecrement(a) _InterlockedDecrement(a)
  4512. #define juce_InterlockedExchangeAdd(a, b) _InterlockedExchangeAdd(a, b)
  4513. #define juce_InterlockedCompareExchange(a, b, c) _InterlockedCompareExchange(a, b, c)
  4514. #define juce_InterlockedCompareExchange64(a, b, c) _InterlockedCompareExchange64(a, b, c)
  4515. #define juce_MemoryBarrier _ReadWriteBarrier
  4516. #else
  4517. // (these are defined in juce_win32_Threads.cpp)
  4518. long juce_InterlockedExchange (volatile long* a, long b) throw();
  4519. long juce_InterlockedIncrement (volatile long* a) throw();
  4520. long juce_InterlockedDecrement (volatile long* a) throw();
  4521. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw();
  4522. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw();
  4523. __int64 juce_InterlockedCompareExchange64 (volatile __int64* a, __int64 b, __int64 c) throw();
  4524. static void juce_MemoryBarrier() throw() { long x = 0; juce_InterlockedIncrement (&x); }
  4525. #endif
  4526. #if JUCE_64BIT
  4527. #pragma intrinsic (_InterlockedExchangeAdd64, _InterlockedExchange64, _InterlockedIncrement64, _InterlockedDecrement64)
  4528. #define juce_InterlockedExchangeAdd64(a, b) _InterlockedExchangeAdd64(a, b)
  4529. #define juce_InterlockedExchange64(a, b) _InterlockedExchange64(a, b)
  4530. #define juce_InterlockedIncrement64(a) _InterlockedIncrement64(a)
  4531. #define juce_InterlockedDecrement64(a) _InterlockedDecrement64(a)
  4532. #else
  4533. // None of these atomics are available in a 32-bit Windows build!!
  4534. template <typename Type> static Type juce_InterlockedExchangeAdd64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a += b; return old; }
  4535. template <typename Type> static Type juce_InterlockedExchange64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a = b; return old; }
  4536. template <typename Type> static Type juce_InterlockedIncrement64 (volatile Type* a) throw() { jassertfalse; return ++*a; }
  4537. template <typename Type> static Type juce_InterlockedDecrement64 (volatile Type* a) throw() { jassertfalse; return --*a; }
  4538. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  4539. #endif
  4540. #endif
  4541. #if JUCE_MSVC
  4542. #pragma warning (push)
  4543. #pragma warning (disable: 4311) // (truncation warning)
  4544. #endif
  4545. template <typename Type>
  4546. inline Type Atomic<Type>::get() const throw()
  4547. {
  4548. return const_cast <Atomic<Type>*> (this)->operator+= (0);
  4549. }
  4550. template <typename Type>
  4551. inline void Atomic<Type>::set (const Type newValue) throw()
  4552. {
  4553. exchange (newValue);
  4554. }
  4555. template <typename Type>
  4556. inline Type Atomic<Type>::exchange (const Type newValue) throw()
  4557. {
  4558. #if JUCE_ATOMICS_MAC || JUCE_ATOMICS_GCC
  4559. Type currentVal = value;
  4560. while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; }
  4561. return currentVal;
  4562. #elif JUCE_ATOMICS_WINDOWS
  4563. return sizeof (Type) == 4 ? (Type) juce_InterlockedExchange ((volatile long*) &value, (long) newValue)
  4564. : (Type) juce_InterlockedExchange64 ((volatile __int64*) &value, (__int64) newValue);
  4565. #endif
  4566. }
  4567. template <typename Type>
  4568. inline Type Atomic<Type>::operator+= (const Type amountToAdd) throw()
  4569. {
  4570. #if JUCE_ATOMICS_MAC
  4571. return sizeof (Type) == 4 ? (Type) OSAtomicAdd32 ((int32_t) amountToAdd, (int32_t*) &value)
  4572. : (Type) OSAtomicAdd64 ((int64_t) amountToAdd, (int64_t*) &value);
  4573. #elif JUCE_ATOMICS_WINDOWS
  4574. return sizeof (Type) == 4 ? (Type) (juce_InterlockedExchangeAdd ((volatile long*) &value, (long) amountToAdd) + (long) amountToAdd)
  4575. : (Type) (juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) amountToAdd) + (__int64) amountToAdd);
  4576. #elif JUCE_ATOMICS_GCC
  4577. return (Type) __sync_add_and_fetch (&value, amountToAdd);
  4578. #endif
  4579. }
  4580. template <typename Type>
  4581. inline Type Atomic<Type>::operator-= (const Type amountToSubtract) throw()
  4582. {
  4583. return operator+= (juce_negate (amountToSubtract));
  4584. }
  4585. template <typename Type>
  4586. inline Type Atomic<Type>::operator++() throw()
  4587. {
  4588. #if JUCE_ATOMICS_MAC
  4589. return sizeof (Type) == 4 ? (Type) OSAtomicIncrement32 ((int32_t*) &value)
  4590. : (Type) OSAtomicIncrement64 ((int64_t*) &value);
  4591. #elif JUCE_ATOMICS_WINDOWS
  4592. return sizeof (Type) == 4 ? (Type) juce_InterlockedIncrement ((volatile long*) &value)
  4593. : (Type) juce_InterlockedIncrement64 ((volatile __int64*) &value);
  4594. #elif JUCE_ATOMICS_GCC
  4595. return (Type) __sync_add_and_fetch (&value, 1);
  4596. #endif
  4597. }
  4598. template <typename Type>
  4599. inline Type Atomic<Type>::operator--() throw()
  4600. {
  4601. #if JUCE_ATOMICS_MAC
  4602. return sizeof (Type) == 4 ? (Type) OSAtomicDecrement32 ((int32_t*) &value)
  4603. : (Type) OSAtomicDecrement64 ((int64_t*) &value);
  4604. #elif JUCE_ATOMICS_WINDOWS
  4605. return sizeof (Type) == 4 ? (Type) juce_InterlockedDecrement ((volatile long*) &value)
  4606. : (Type) juce_InterlockedDecrement64 ((volatile __int64*) &value);
  4607. #elif JUCE_ATOMICS_GCC
  4608. return (Type) __sync_add_and_fetch (&value, -1);
  4609. #endif
  4610. }
  4611. template <typename Type>
  4612. inline bool Atomic<Type>::compareAndSetBool (const Type newValue, const Type valueToCompare) throw()
  4613. {
  4614. #if JUCE_ATOMICS_MAC
  4615. return sizeof (Type) == 4 ? OSAtomicCompareAndSwap32Barrier ((int32_t) valueToCompare, (int32_t) newValue, (int32_t*) &value)
  4616. : OSAtomicCompareAndSwap64Barrier ((int64_t) valueToCompare, (int64_t) newValue, (int64_t*) &value);
  4617. #elif JUCE_ATOMICS_WINDOWS
  4618. return compareAndSetValue (newValue, valueToCompare) == valueToCompare;
  4619. #elif JUCE_ATOMICS_GCC
  4620. return __sync_bool_compare_and_swap (&value, valueToCompare, newValue);
  4621. #endif
  4622. }
  4623. template <typename Type>
  4624. inline Type Atomic<Type>::compareAndSetValue (const Type newValue, const Type valueToCompare) throw()
  4625. {
  4626. #if JUCE_ATOMICS_MAC
  4627. for (;;) // Annoying workaround for OSX only having a bool CAS operation..
  4628. {
  4629. if (compareAndSetBool (newValue, valueToCompare))
  4630. return valueToCompare;
  4631. const Type result = value;
  4632. if (result != valueToCompare)
  4633. return result;
  4634. }
  4635. #elif JUCE_ATOMICS_WINDOWS
  4636. return sizeof (Type) == 4 ? (Type) juce_InterlockedCompareExchange ((volatile long*) &value, (long) newValue, (long) valueToCompare)
  4637. : (Type) juce_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) newValue, (__int64) valueToCompare);
  4638. #elif JUCE_ATOMICS_GCC
  4639. return __sync_val_compare_and_swap (&value, valueToCompare, newValue);
  4640. #endif
  4641. }
  4642. template <typename Type>
  4643. inline void Atomic<Type>::memoryBarrier() throw()
  4644. {
  4645. #if JUCE_ATOMICS_MAC
  4646. OSMemoryBarrier();
  4647. #elif JUCE_ATOMICS_GCC
  4648. __sync_synchronize();
  4649. #elif JUCE_ATOMICS_WINDOWS
  4650. juce_MemoryBarrier();
  4651. #endif
  4652. }
  4653. #if JUCE_MSVC
  4654. #pragma warning (pop)
  4655. #endif
  4656. #endif // __JUCE_ATOMIC_JUCEHEADER__
  4657. /*** End of inlined file: juce_Atomic.h ***/
  4658. /**
  4659. Adds reference-counting to an object.
  4660. To add reference-counting to a class, derive it from this class, and
  4661. use the ReferenceCountedObjectPtr class to point to it.
  4662. e.g. @code
  4663. class MyClass : public ReferenceCountedObject
  4664. {
  4665. void foo();
  4666. // This is a neat way of declaring a typedef for a pointer class,
  4667. // rather than typing out the full templated name each time..
  4668. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  4669. };
  4670. MyClass::Ptr p = new MyClass();
  4671. MyClass::Ptr p2 = p;
  4672. p = 0;
  4673. p2->foo();
  4674. @endcode
  4675. Once a new ReferenceCountedObject has been assigned to a pointer, be
  4676. careful not to delete the object manually.
  4677. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  4678. */
  4679. class JUCE_API ReferenceCountedObject
  4680. {
  4681. public:
  4682. /** Increments the object's reference count.
  4683. This is done automatically by the smart pointer, but is public just
  4684. in case it's needed for nefarious purposes.
  4685. */
  4686. inline void incReferenceCount() throw()
  4687. {
  4688. ++refCount;
  4689. }
  4690. /** Decreases the object's reference count.
  4691. If the count gets to zero, the object will be deleted.
  4692. */
  4693. inline void decReferenceCount() throw()
  4694. {
  4695. jassert (getReferenceCount() > 0);
  4696. if (--refCount == 0)
  4697. delete this;
  4698. }
  4699. /** Returns the object's current reference count. */
  4700. inline int getReferenceCount() const throw()
  4701. {
  4702. return refCount.get();
  4703. }
  4704. protected:
  4705. /** Creates the reference-counted object (with an initial ref count of zero). */
  4706. ReferenceCountedObject()
  4707. {
  4708. }
  4709. /** Destructor. */
  4710. virtual ~ReferenceCountedObject()
  4711. {
  4712. // it's dangerous to delete an object that's still referenced by something else!
  4713. jassert (getReferenceCount() == 0);
  4714. }
  4715. private:
  4716. Atomic <int> refCount;
  4717. };
  4718. /**
  4719. Used to point to an object of type ReferenceCountedObject.
  4720. It's wise to use a typedef instead of typing out the templated name
  4721. each time - e.g.
  4722. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  4723. @see ReferenceCountedObject, ReferenceCountedObjectArray
  4724. */
  4725. template <class ReferenceCountedObjectClass>
  4726. class ReferenceCountedObjectPtr
  4727. {
  4728. public:
  4729. /** Creates a pointer to a null object. */
  4730. inline ReferenceCountedObjectPtr() throw()
  4731. : referencedObject (0)
  4732. {
  4733. }
  4734. /** Creates a pointer to an object.
  4735. This will increment the object's reference-count if it is non-null.
  4736. */
  4737. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  4738. : referencedObject (refCountedObject)
  4739. {
  4740. if (refCountedObject != 0)
  4741. refCountedObject->incReferenceCount();
  4742. }
  4743. /** Copies another pointer.
  4744. This will increment the object's reference-count (if it is non-null).
  4745. */
  4746. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  4747. : referencedObject (other.referencedObject)
  4748. {
  4749. if (referencedObject != 0)
  4750. referencedObject->incReferenceCount();
  4751. }
  4752. /** Changes this pointer to point at a different object.
  4753. The reference count of the old object is decremented, and it might be
  4754. deleted if it hits zero. The new object's count is incremented.
  4755. */
  4756. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  4757. {
  4758. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  4759. if (newObject != referencedObject)
  4760. {
  4761. if (newObject != 0)
  4762. newObject->incReferenceCount();
  4763. ReferenceCountedObjectClass* const oldObject = referencedObject;
  4764. referencedObject = newObject;
  4765. if (oldObject != 0)
  4766. oldObject->decReferenceCount();
  4767. }
  4768. return *this;
  4769. }
  4770. /** Changes this pointer to point at a different object.
  4771. The reference count of the old object is decremented, and it might be
  4772. deleted if it hits zero. The new object's count is incremented.
  4773. */
  4774. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  4775. {
  4776. if (referencedObject != newObject)
  4777. {
  4778. if (newObject != 0)
  4779. newObject->incReferenceCount();
  4780. ReferenceCountedObjectClass* const oldObject = referencedObject;
  4781. referencedObject = newObject;
  4782. if (oldObject != 0)
  4783. oldObject->decReferenceCount();
  4784. }
  4785. return *this;
  4786. }
  4787. /** Destructor.
  4788. This will decrement the object's reference-count, and may delete it if it
  4789. gets to zero.
  4790. */
  4791. inline ~ReferenceCountedObjectPtr()
  4792. {
  4793. if (referencedObject != 0)
  4794. referencedObject->decReferenceCount();
  4795. }
  4796. /** Returns the object that this pointer references.
  4797. The pointer returned may be zero, of course.
  4798. */
  4799. inline operator ReferenceCountedObjectClass*() const throw()
  4800. {
  4801. return referencedObject;
  4802. }
  4803. /** Returns true if this pointer refers to the given object. */
  4804. inline bool operator== (ReferenceCountedObjectClass* const object) const throw()
  4805. {
  4806. return referencedObject == object;
  4807. }
  4808. /** Returns true if this pointer doesn't refer to the given object. */
  4809. inline bool operator!= (ReferenceCountedObjectClass* const object) const throw()
  4810. {
  4811. return referencedObject != object;
  4812. }
  4813. // the -> operator is called on the referenced object
  4814. inline ReferenceCountedObjectClass* operator->() const throw()
  4815. {
  4816. return referencedObject;
  4817. }
  4818. /** Returns the object that this pointer references.
  4819. The pointer returned may be zero, of course.
  4820. */
  4821. inline ReferenceCountedObjectClass* getObject() const throw()
  4822. {
  4823. return referencedObject;
  4824. }
  4825. private:
  4826. ReferenceCountedObjectClass* referencedObject;
  4827. };
  4828. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  4829. /*** End of inlined file: juce_ReferenceCountedObject.h ***/
  4830. /**
  4831. Represents a dynamically implemented object.
  4832. This class is primarily intended for wrapping scripting language objects,
  4833. but could be used for other purposes.
  4834. An instance of a DynamicObject can be used to store named properties, and
  4835. by subclassing hasMethod() and invokeMethod(), you can give your object
  4836. methods.
  4837. */
  4838. class JUCE_API DynamicObject : public ReferenceCountedObject
  4839. {
  4840. public:
  4841. DynamicObject();
  4842. /** Destructor. */
  4843. virtual ~DynamicObject();
  4844. /** Returns true if the object has a property with this name.
  4845. Note that if the property is actually a method, this will return false.
  4846. */
  4847. virtual bool hasProperty (const Identifier& propertyName) const;
  4848. /** Returns a named property.
  4849. This returns a void if no such property exists.
  4850. */
  4851. virtual const var getProperty (const Identifier& propertyName) const;
  4852. /** Sets a named property. */
  4853. virtual void setProperty (const Identifier& propertyName, const var& newValue);
  4854. /** Removes a named property. */
  4855. virtual void removeProperty (const Identifier& propertyName);
  4856. /** Checks whether this object has the specified method.
  4857. The default implementation of this just checks whether there's a property
  4858. with this name that's actually a method, but this can be overridden for
  4859. building objects with dynamic invocation.
  4860. */
  4861. virtual bool hasMethod (const Identifier& methodName) const;
  4862. /** Invokes a named method on this object.
  4863. The default implementation looks up the named property, and if it's a method
  4864. call, then it invokes it.
  4865. This method is virtual to allow more dynamic invocation to used for objects
  4866. where the methods may not already be set as properies.
  4867. */
  4868. virtual const var invokeMethod (const Identifier& methodName,
  4869. const var* parameters,
  4870. int numParameters);
  4871. /** Sets up a method.
  4872. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  4873. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  4874. the code easier to read,
  4875. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  4876. @code
  4877. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  4878. @endcode
  4879. */
  4880. void setMethod (const Identifier& methodName,
  4881. var::MethodFunction methodFunction);
  4882. /** Removes all properties and methods from the object. */
  4883. void clear();
  4884. juce_UseDebuggingNewOperator
  4885. private:
  4886. NamedValueSet properties;
  4887. };
  4888. #endif // __JUCE_DYNAMICOBJECT_JUCEHEADER__
  4889. /*** End of inlined file: juce_DynamicObject.h ***/
  4890. #endif
  4891. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  4892. #endif
  4893. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  4894. #endif
  4895. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  4896. #endif
  4897. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  4898. #endif
  4899. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  4900. #endif
  4901. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  4902. /*** Start of inlined file: juce_OwnedArray.h ***/
  4903. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  4904. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  4905. /*** Start of inlined file: juce_ScopedPointer.h ***/
  4906. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  4907. #define __JUCE_SCOPEDPOINTER_JUCEHEADER__
  4908. /**
  4909. This class holds a pointer which is automatically deleted when this object goes
  4910. out of scope.
  4911. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  4912. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  4913. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  4914. created objects.
  4915. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  4916. to an object. If you use the assignment operator to assign a different object to a
  4917. ScopedPointer, the old one will be automatically deleted.
  4918. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  4919. object to which it points during its lifetime. This means that making a copy of a const
  4920. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  4921. old one.
  4922. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  4923. can use the release() method.
  4924. */
  4925. template <class ObjectType>
  4926. class ScopedPointer
  4927. {
  4928. public:
  4929. /** Creates a ScopedPointer containing a null pointer. */
  4930. inline ScopedPointer() throw() : object (0)
  4931. {
  4932. }
  4933. /** Creates a ScopedPointer that owns the specified object. */
  4934. inline ScopedPointer (ObjectType* const objectToTakePossessionOf) throw()
  4935. : object (objectToTakePossessionOf)
  4936. {
  4937. }
  4938. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  4939. Because a pointer can only belong to one ScopedPointer, this transfers
  4940. the pointer from the other object to this one, and the other object is reset to
  4941. be a null pointer.
  4942. */
  4943. ScopedPointer (ScopedPointer& objectToTransferFrom) throw()
  4944. : object (objectToTransferFrom.object)
  4945. {
  4946. objectToTransferFrom.object = 0;
  4947. }
  4948. /** Destructor.
  4949. This will delete the object that this ScopedPointer currently refers to.
  4950. */
  4951. inline ~ScopedPointer() { delete object; }
  4952. /** Changes this ScopedPointer to point to a new object.
  4953. Because a pointer can only belong to one ScopedPointer, this transfers
  4954. the pointer from the other object to this one, and the other object is reset to
  4955. be a null pointer.
  4956. If this ScopedPointer already points to an object, that object
  4957. will first be deleted.
  4958. */
  4959. ScopedPointer& operator= (ScopedPointer& objectToTransferFrom)
  4960. {
  4961. if (this != objectToTransferFrom.getAddress())
  4962. {
  4963. // Two ScopedPointers should never be able to refer to the same object - if
  4964. // this happens, you must have done something dodgy!
  4965. jassert (object == 0 || object != objectToTransferFrom.object);
  4966. ObjectType* const oldObject = object;
  4967. object = objectToTransferFrom.object;
  4968. objectToTransferFrom.object = 0;
  4969. delete oldObject;
  4970. }
  4971. return *this;
  4972. }
  4973. /** Changes this ScopedPointer to point to a new object.
  4974. If this ScopedPointer already points to an object, that object
  4975. will first be deleted.
  4976. The pointer that you pass is may be null.
  4977. */
  4978. ScopedPointer& operator= (ObjectType* const newObjectToTakePossessionOf)
  4979. {
  4980. if (object != newObjectToTakePossessionOf)
  4981. {
  4982. ObjectType* const oldObject = object;
  4983. object = newObjectToTakePossessionOf;
  4984. delete oldObject;
  4985. }
  4986. return *this;
  4987. }
  4988. /** Returns the object that this ScopedPointer refers to.
  4989. */
  4990. inline operator ObjectType*() const throw() { return object; }
  4991. /** Returns the object that this ScopedPointer refers to.
  4992. */
  4993. inline ObjectType& operator*() const throw() { return *object; }
  4994. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  4995. inline ObjectType* operator->() const throw() { return object; }
  4996. /** Returns a reference to the address of the object that this ScopedPointer refers to. */
  4997. inline ObjectType* const* operator&() const throw() { return static_cast <ObjectType* const*> (&object); }
  4998. /** Returns a reference to the address of the object that this ScopedPointer refers to. */
  4999. inline ObjectType** operator&() throw() { return static_cast <ObjectType**> (&object); }
  5000. /** Removes the current object from this ScopedPointer without deleting it.
  5001. This will return the current object, and set the ScopedPointer to a null pointer.
  5002. */
  5003. ObjectType* release() throw() { ObjectType* const o = object; object = 0; return o; }
  5004. /** Swaps this object with that of another ScopedPointer.
  5005. The two objects simply exchange their pointers.
  5006. */
  5007. void swapWith (ScopedPointer <ObjectType>& other) throw()
  5008. {
  5009. // Two ScopedPointers should never be able to refer to the same object - if
  5010. // this happens, you must have done something dodgy!
  5011. jassert (object != other.object);
  5012. swapVariables (object, other.object);
  5013. }
  5014. private:
  5015. ObjectType* object;
  5016. // (Required as an alternative to the overloaded & operator).
  5017. const ScopedPointer* getAddress() const throw() { return this; }
  5018. #if ! JUCE_MSVC // (MSVC can't deal with multiple copy constructors)
  5019. // This is private to stop people accidentally copying a const ScopedPointer (the compiler
  5020. // will let you do so by implicitly casting the source to its raw object pointer).
  5021. ScopedPointer (const ScopedPointer&);
  5022. #endif
  5023. };
  5024. /** Compares a ScopedPointer with another pointer.
  5025. This can be handy for checking whether this is a null pointer.
  5026. */
  5027. template <class ObjectType>
  5028. inline bool operator== (const ScopedPointer<ObjectType>& pointer1, const ObjectType* const pointer2) throw()
  5029. {
  5030. return static_cast <ObjectType*> (pointer1) == pointer2;
  5031. }
  5032. /** Compares a ScopedPointer with another pointer.
  5033. This can be handy for checking whether this is a null pointer.
  5034. */
  5035. template <class ObjectType>
  5036. inline bool operator!= (const ScopedPointer<ObjectType>& pointer1, const ObjectType* const pointer2) throw()
  5037. {
  5038. return static_cast <ObjectType*> (pointer1) != pointer2;
  5039. }
  5040. #endif // __JUCE_SCOPEDPOINTER_JUCEHEADER__
  5041. /*** End of inlined file: juce_ScopedPointer.h ***/
  5042. /** An array designed for holding objects.
  5043. This holds a list of pointers to objects, and will automatically
  5044. delete the objects when they are removed from the array, or when the
  5045. array is itself deleted.
  5046. Declare it in the form: OwnedArray<MyObjectClass>
  5047. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  5048. After adding objects, they are 'owned' by the array and will be deleted when
  5049. removed or replaced.
  5050. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  5051. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  5052. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  5053. */
  5054. template <class ObjectClass,
  5055. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  5056. class OwnedArray
  5057. {
  5058. public:
  5059. /** Creates an empty array. */
  5060. OwnedArray() throw()
  5061. : numUsed (0)
  5062. {
  5063. }
  5064. /** Deletes the array and also deletes any objects inside it.
  5065. To get rid of the array without deleting its objects, use its
  5066. clear (false) method before deleting it.
  5067. */
  5068. ~OwnedArray()
  5069. {
  5070. clear (true);
  5071. }
  5072. /** Clears the array, optionally deleting the objects inside it first. */
  5073. void clear (const bool deleteObjects = true)
  5074. {
  5075. const ScopedLockType lock (getLock());
  5076. if (deleteObjects)
  5077. {
  5078. while (numUsed > 0)
  5079. delete data.elements [--numUsed];
  5080. }
  5081. data.setAllocatedSize (0);
  5082. numUsed = 0;
  5083. }
  5084. /** Returns the number of items currently in the array.
  5085. @see operator[]
  5086. */
  5087. inline int size() const throw()
  5088. {
  5089. return numUsed;
  5090. }
  5091. /** Returns a pointer to the object at this index in the array.
  5092. If the index is out-of-range, this will return a null pointer, (and
  5093. it could be null anyway, because it's ok for the array to hold null
  5094. pointers as well as objects).
  5095. @see getUnchecked
  5096. */
  5097. inline ObjectClass* operator[] (const int index) const throw()
  5098. {
  5099. const ScopedLockType lock (getLock());
  5100. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  5101. : static_cast <ObjectClass*> (0);
  5102. }
  5103. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  5104. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  5105. it can be used when you're sure the index if always going to be legal.
  5106. */
  5107. inline ObjectClass* getUnchecked (const int index) const throw()
  5108. {
  5109. const ScopedLockType lock (getLock());
  5110. jassert (((unsigned int) index) < (unsigned int) numUsed);
  5111. return data.elements [index];
  5112. }
  5113. /** Returns a pointer to the first object in the array.
  5114. This will return a null pointer if the array's empty.
  5115. @see getLast
  5116. */
  5117. inline ObjectClass* getFirst() const throw()
  5118. {
  5119. const ScopedLockType lock (getLock());
  5120. return numUsed > 0 ? data.elements [0]
  5121. : static_cast <ObjectClass*> (0);
  5122. }
  5123. /** Returns a pointer to the last object in the array.
  5124. This will return a null pointer if the array's empty.
  5125. @see getFirst
  5126. */
  5127. inline ObjectClass* getLast() const throw()
  5128. {
  5129. const ScopedLockType lock (getLock());
  5130. return numUsed > 0 ? data.elements [numUsed - 1]
  5131. : static_cast <ObjectClass*> (0);
  5132. }
  5133. /** Returns a pointer to the actual array data.
  5134. This pointer will only be valid until the next time a non-const method
  5135. is called on the array.
  5136. */
  5137. inline ObjectClass** getRawDataPointer() throw()
  5138. {
  5139. return data.elements;
  5140. }
  5141. /** Finds the index of an object which might be in the array.
  5142. @param objectToLookFor the object to look for
  5143. @returns the index at which the object was found, or -1 if it's not found
  5144. */
  5145. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  5146. {
  5147. const ScopedLockType lock (getLock());
  5148. ObjectClass* const* e = data.elements.getData();
  5149. ObjectClass* const* const end = e + numUsed;
  5150. while (e != end)
  5151. {
  5152. if (objectToLookFor == *e)
  5153. return static_cast <int> (e - data.elements.getData());
  5154. ++e;
  5155. }
  5156. return -1;
  5157. }
  5158. /** Returns true if the array contains a specified object.
  5159. @param objectToLookFor the object to look for
  5160. @returns true if the object is in the array
  5161. */
  5162. bool contains (const ObjectClass* const objectToLookFor) const throw()
  5163. {
  5164. const ScopedLockType lock (getLock());
  5165. ObjectClass* const* e = data.elements.getData();
  5166. ObjectClass* const* const end = e + numUsed;
  5167. while (e != end)
  5168. {
  5169. if (objectToLookFor == *e)
  5170. return true;
  5171. ++e;
  5172. }
  5173. return false;
  5174. }
  5175. /** Appends a new object to the end of the array.
  5176. Note that the this object will be deleted by the OwnedArray when it
  5177. is removed, so be careful not to delete it somewhere else.
  5178. Also be careful not to add the same object to the array more than once,
  5179. as this will obviously cause deletion of dangling pointers.
  5180. @param newObject the new object to add to the array
  5181. @see set, insert, addIfNotAlreadyThere, addSorted
  5182. */
  5183. void add (const ObjectClass* const newObject) throw()
  5184. {
  5185. const ScopedLockType lock (getLock());
  5186. data.ensureAllocatedSize (numUsed + 1);
  5187. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  5188. }
  5189. /** Inserts a new object into the array at the given index.
  5190. Note that the this object will be deleted by the OwnedArray when it
  5191. is removed, so be careful not to delete it somewhere else.
  5192. If the index is less than 0 or greater than the size of the array, the
  5193. element will be added to the end of the array.
  5194. Otherwise, it will be inserted into the array, moving all the later elements
  5195. along to make room.
  5196. Be careful not to add the same object to the array more than once,
  5197. as this will obviously cause deletion of dangling pointers.
  5198. @param indexToInsertAt the index at which the new element should be inserted
  5199. @param newObject the new object to add to the array
  5200. @see add, addSorted, addIfNotAlreadyThere, set
  5201. */
  5202. void insert (int indexToInsertAt,
  5203. const ObjectClass* const newObject) throw()
  5204. {
  5205. if (indexToInsertAt >= 0)
  5206. {
  5207. const ScopedLockType lock (getLock());
  5208. if (indexToInsertAt > numUsed)
  5209. indexToInsertAt = numUsed;
  5210. data.ensureAllocatedSize (numUsed + 1);
  5211. ObjectClass** const e = data.elements + indexToInsertAt;
  5212. const int numToMove = numUsed - indexToInsertAt;
  5213. if (numToMove > 0)
  5214. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  5215. *e = const_cast <ObjectClass*> (newObject);
  5216. ++numUsed;
  5217. }
  5218. else
  5219. {
  5220. add (newObject);
  5221. }
  5222. }
  5223. /** Appends a new object at the end of the array as long as the array doesn't
  5224. already contain it.
  5225. If the array already contains a matching object, nothing will be done.
  5226. @param newObject the new object to add to the array
  5227. */
  5228. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  5229. {
  5230. const ScopedLockType lock (getLock());
  5231. if (! contains (newObject))
  5232. add (newObject);
  5233. }
  5234. /** Replaces an object in the array with a different one.
  5235. If the index is less than zero, this method does nothing.
  5236. If the index is beyond the end of the array, the new object is added to the end of the array.
  5237. Be careful not to add the same object to the array more than once,
  5238. as this will obviously cause deletion of dangling pointers.
  5239. @param indexToChange the index whose value you want to change
  5240. @param newObject the new value to set for this index.
  5241. @param deleteOldElement whether to delete the object that's being replaced with the new one
  5242. @see add, insert, remove
  5243. */
  5244. void set (const int indexToChange,
  5245. const ObjectClass* const newObject,
  5246. const bool deleteOldElement = true)
  5247. {
  5248. if (indexToChange >= 0)
  5249. {
  5250. ScopedPointer <ObjectClass> toDelete;
  5251. const ScopedLockType lock (getLock());
  5252. if (indexToChange < numUsed)
  5253. {
  5254. if (deleteOldElement)
  5255. {
  5256. toDelete = data.elements [indexToChange];
  5257. if (toDelete == newObject)
  5258. toDelete = 0;
  5259. }
  5260. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  5261. }
  5262. else
  5263. {
  5264. data.ensureAllocatedSize (numUsed + 1);
  5265. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  5266. }
  5267. }
  5268. }
  5269. /** Adds elements from another array to the end of this array.
  5270. @param arrayToAddFrom the array from which to copy the elements
  5271. @param startIndex the first element of the other array to start copying from
  5272. @param numElementsToAdd how many elements to add from the other array. If this
  5273. value is negative or greater than the number of available elements,
  5274. all available elements will be copied.
  5275. @see add
  5276. */
  5277. template <class OtherArrayType>
  5278. void addArray (const OtherArrayType& arrayToAddFrom,
  5279. int startIndex = 0,
  5280. int numElementsToAdd = -1)
  5281. {
  5282. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5283. const ScopedLockType lock2 (getLock());
  5284. if (startIndex < 0)
  5285. {
  5286. jassertfalse;
  5287. startIndex = 0;
  5288. }
  5289. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5290. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5291. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5292. while (--numElementsToAdd >= 0)
  5293. {
  5294. data.elements [numUsed] = arrayToAddFrom.getUnchecked (startIndex++);
  5295. ++numUsed;
  5296. }
  5297. }
  5298. /** Adds copies of the elements in another array to the end of this array.
  5299. The other array must be either an OwnedArray of a compatible type of object, or an Array
  5300. containing pointers to the same kind of object. The objects involved must provide
  5301. a copy constructor, and this will be used to create new copies of each element, and
  5302. add them to this array.
  5303. @param arrayToAddFrom the array from which to copy the elements
  5304. @param startIndex the first element of the other array to start copying from
  5305. @param numElementsToAdd how many elements to add from the other array. If this
  5306. value is negative or greater than the number of available elements,
  5307. all available elements will be copied.
  5308. @see add
  5309. */
  5310. template <class OtherArrayType>
  5311. void addCopiesOf (const OtherArrayType& arrayToAddFrom,
  5312. int startIndex = 0,
  5313. int numElementsToAdd = -1)
  5314. {
  5315. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5316. const ScopedLockType lock2 (getLock());
  5317. if (startIndex < 0)
  5318. {
  5319. jassertfalse;
  5320. startIndex = 0;
  5321. }
  5322. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5323. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5324. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5325. while (--numElementsToAdd >= 0)
  5326. {
  5327. data.elements [numUsed] = new ObjectClass (*arrayToAddFrom.getUnchecked (startIndex++));
  5328. ++numUsed;
  5329. }
  5330. }
  5331. /** Inserts a new object into the array assuming that the array is sorted.
  5332. This will use a comparator to find the position at which the new object
  5333. should go. If the array isn't sorted, the behaviour of this
  5334. method will be unpredictable.
  5335. @param comparator the comparator to use to compare the elements - see the sort method
  5336. for details about this object's structure
  5337. @param newObject the new object to insert to the array
  5338. @see add, sort, indexOfSorted
  5339. */
  5340. template <class ElementComparator>
  5341. void addSorted (ElementComparator& comparator,
  5342. ObjectClass* const newObject) throw()
  5343. {
  5344. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5345. // avoids getting warning messages about the parameter being unused
  5346. const ScopedLockType lock (getLock());
  5347. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  5348. }
  5349. /** Finds the index of an object in the array, assuming that the array is sorted.
  5350. This will use a comparator to do a binary-chop to find the index of the given
  5351. element, if it exists. If the array isn't sorted, the behaviour of this
  5352. method will be unpredictable.
  5353. @param comparator the comparator to use to compare the elements - see the sort()
  5354. method for details about the form this object should take
  5355. @param objectToLookFor the object to search for
  5356. @returns the index of the element, or -1 if it's not found
  5357. @see addSorted, sort
  5358. */
  5359. template <class ElementComparator>
  5360. int indexOfSorted (ElementComparator& comparator,
  5361. const ObjectClass* const objectToLookFor) const throw()
  5362. {
  5363. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5364. // avoids getting warning messages about the parameter being unused
  5365. const ScopedLockType lock (getLock());
  5366. int start = 0;
  5367. int end = numUsed;
  5368. for (;;)
  5369. {
  5370. if (start >= end)
  5371. {
  5372. return -1;
  5373. }
  5374. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  5375. {
  5376. return start;
  5377. }
  5378. else
  5379. {
  5380. const int halfway = (start + end) >> 1;
  5381. if (halfway == start)
  5382. return -1;
  5383. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  5384. start = halfway;
  5385. else
  5386. end = halfway;
  5387. }
  5388. }
  5389. }
  5390. /** Removes an object from the array.
  5391. This will remove the object at a given index (optionally also
  5392. deleting it) and move back all the subsequent objects to close the gap.
  5393. If the index passed in is out-of-range, nothing will happen.
  5394. @param indexToRemove the index of the element to remove
  5395. @param deleteObject whether to delete the object that is removed
  5396. @see removeObject, removeRange
  5397. */
  5398. void remove (const int indexToRemove,
  5399. const bool deleteObject = true)
  5400. {
  5401. ScopedPointer <ObjectClass> toDelete;
  5402. const ScopedLockType lock (getLock());
  5403. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  5404. {
  5405. ObjectClass** const e = data.elements + indexToRemove;
  5406. if (deleteObject)
  5407. toDelete = *e;
  5408. --numUsed;
  5409. const int numToShift = numUsed - indexToRemove;
  5410. if (numToShift > 0)
  5411. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  5412. if ((numUsed << 1) < data.numAllocated)
  5413. minimiseStorageOverheads();
  5414. }
  5415. }
  5416. /** Removes a specified object from the array.
  5417. If the item isn't found, no action is taken.
  5418. @param objectToRemove the object to try to remove
  5419. @param deleteObject whether to delete the object (if it's found)
  5420. @see remove, removeRange
  5421. */
  5422. void removeObject (const ObjectClass* const objectToRemove,
  5423. const bool deleteObject = true)
  5424. {
  5425. const ScopedLockType lock (getLock());
  5426. ObjectClass** e = data.elements.getData();
  5427. for (int i = numUsed; --i >= 0;)
  5428. {
  5429. if (objectToRemove == *e)
  5430. {
  5431. remove (static_cast <int> (e - data.elements.getData()), deleteObject);
  5432. break;
  5433. }
  5434. ++e;
  5435. }
  5436. }
  5437. /** Removes a range of objects from the array.
  5438. This will remove a set of objects, starting from the given index,
  5439. and move any subsequent elements down to close the gap.
  5440. If the range extends beyond the bounds of the array, it will
  5441. be safely clipped to the size of the array.
  5442. @param startIndex the index of the first object to remove
  5443. @param numberToRemove how many objects should be removed
  5444. @param deleteObjects whether to delete the objects that get removed
  5445. @see remove, removeObject
  5446. */
  5447. void removeRange (int startIndex,
  5448. const int numberToRemove,
  5449. const bool deleteObjects = true)
  5450. {
  5451. const ScopedLockType lock (getLock());
  5452. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  5453. startIndex = jlimit (0, numUsed, startIndex);
  5454. if (endIndex > startIndex)
  5455. {
  5456. if (deleteObjects)
  5457. {
  5458. for (int i = startIndex; i < endIndex; ++i)
  5459. {
  5460. delete data.elements [i];
  5461. data.elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  5462. }
  5463. }
  5464. const int rangeSize = endIndex - startIndex;
  5465. ObjectClass** e = data.elements + startIndex;
  5466. int numToShift = numUsed - endIndex;
  5467. numUsed -= rangeSize;
  5468. while (--numToShift >= 0)
  5469. {
  5470. *e = e [rangeSize];
  5471. ++e;
  5472. }
  5473. if ((numUsed << 1) < data.numAllocated)
  5474. minimiseStorageOverheads();
  5475. }
  5476. }
  5477. /** Removes the last n objects from the array.
  5478. @param howManyToRemove how many objects to remove from the end of the array
  5479. @param deleteObjects whether to also delete the objects that are removed
  5480. @see remove, removeObject, removeRange
  5481. */
  5482. void removeLast (int howManyToRemove = 1,
  5483. const bool deleteObjects = true)
  5484. {
  5485. const ScopedLockType lock (getLock());
  5486. if (howManyToRemove >= numUsed)
  5487. {
  5488. clear (deleteObjects);
  5489. }
  5490. else
  5491. {
  5492. while (--howManyToRemove >= 0)
  5493. remove (numUsed - 1, deleteObjects);
  5494. }
  5495. }
  5496. /** Swaps a pair of objects in the array.
  5497. If either of the indexes passed in is out-of-range, nothing will happen,
  5498. otherwise the two objects at these positions will be exchanged.
  5499. */
  5500. void swap (const int index1,
  5501. const int index2) throw()
  5502. {
  5503. const ScopedLockType lock (getLock());
  5504. if (((unsigned int) index1) < (unsigned int) numUsed
  5505. && ((unsigned int) index2) < (unsigned int) numUsed)
  5506. {
  5507. swapVariables (data.elements [index1],
  5508. data.elements [index2]);
  5509. }
  5510. }
  5511. /** Moves one of the objects to a different position.
  5512. This will move the object to a specified index, shuffling along
  5513. any intervening elements as required.
  5514. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  5515. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  5516. @param currentIndex the index of the object to be moved. If this isn't a
  5517. valid index, then nothing will be done
  5518. @param newIndex the index at which you'd like this object to end up. If this
  5519. is less than zero, it will be moved to the end of the array
  5520. */
  5521. void move (const int currentIndex,
  5522. int newIndex) throw()
  5523. {
  5524. if (currentIndex != newIndex)
  5525. {
  5526. const ScopedLockType lock (getLock());
  5527. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  5528. {
  5529. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  5530. newIndex = numUsed - 1;
  5531. ObjectClass* const value = data.elements [currentIndex];
  5532. if (newIndex > currentIndex)
  5533. {
  5534. memmove (data.elements + currentIndex,
  5535. data.elements + currentIndex + 1,
  5536. (newIndex - currentIndex) * sizeof (ObjectClass*));
  5537. }
  5538. else
  5539. {
  5540. memmove (data.elements + newIndex + 1,
  5541. data.elements + newIndex,
  5542. (currentIndex - newIndex) * sizeof (ObjectClass*));
  5543. }
  5544. data.elements [newIndex] = value;
  5545. }
  5546. }
  5547. }
  5548. /** This swaps the contents of this array with those of another array.
  5549. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  5550. because it just swaps their internal pointers.
  5551. */
  5552. void swapWithArray (OwnedArray& otherArray) throw()
  5553. {
  5554. const ScopedLockType lock1 (getLock());
  5555. const ScopedLockType lock2 (otherArray.getLock());
  5556. data.swapWith (otherArray.data);
  5557. swapVariables (numUsed, otherArray.numUsed);
  5558. }
  5559. /** Reduces the amount of storage being used by the array.
  5560. Arrays typically allocate slightly more storage than they need, and after
  5561. removing elements, they may have quite a lot of unused space allocated.
  5562. This method will reduce the amount of allocated storage to a minimum.
  5563. */
  5564. void minimiseStorageOverheads() throw()
  5565. {
  5566. const ScopedLockType lock (getLock());
  5567. data.shrinkToNoMoreThan (numUsed);
  5568. }
  5569. /** Increases the array's internal storage to hold a minimum number of elements.
  5570. Calling this before adding a large known number of elements means that
  5571. the array won't have to keep dynamically resizing itself as the elements
  5572. are added, and it'll therefore be more efficient.
  5573. */
  5574. void ensureStorageAllocated (const int minNumElements) throw()
  5575. {
  5576. const ScopedLockType lock (getLock());
  5577. data.ensureAllocatedSize (minNumElements);
  5578. }
  5579. /** Sorts the elements in the array.
  5580. This will use a comparator object to sort the elements into order. The object
  5581. passed must have a method of the form:
  5582. @code
  5583. int compareElements (ElementType first, ElementType second);
  5584. @endcode
  5585. ..and this method must return:
  5586. - a value of < 0 if the first comes before the second
  5587. - a value of 0 if the two objects are equivalent
  5588. - a value of > 0 if the second comes before the first
  5589. To improve performance, the compareElements() method can be declared as static or const.
  5590. @param comparator the comparator to use for comparing elements.
  5591. @param retainOrderOfEquivalentItems if this is true, then items
  5592. which the comparator says are equivalent will be
  5593. kept in the order in which they currently appear
  5594. in the array. This is slower to perform, but may
  5595. be important in some cases. If it's false, a faster
  5596. algorithm is used, but equivalent elements may be
  5597. rearranged.
  5598. @see sortArray, indexOfSorted
  5599. */
  5600. template <class ElementComparator>
  5601. void sort (ElementComparator& comparator,
  5602. const bool retainOrderOfEquivalentItems = false) const throw()
  5603. {
  5604. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5605. // avoids getting warning messages about the parameter being unused
  5606. const ScopedLockType lock (getLock());
  5607. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  5608. }
  5609. /** Returns the CriticalSection that locks this array.
  5610. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  5611. an object of ScopedLockType as an RAII lock for it.
  5612. */
  5613. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  5614. /** Returns the type of scoped lock to use for locking this array */
  5615. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  5616. juce_UseDebuggingNewOperator
  5617. private:
  5618. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  5619. int numUsed;
  5620. // disallow copy constructor and assignment
  5621. OwnedArray (const OwnedArray&);
  5622. OwnedArray& operator= (const OwnedArray&);
  5623. };
  5624. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  5625. /*** End of inlined file: juce_OwnedArray.h ***/
  5626. #endif
  5627. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  5628. /*** Start of inlined file: juce_PropertySet.h ***/
  5629. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  5630. #define __JUCE_PROPERTYSET_JUCEHEADER__
  5631. /*** Start of inlined file: juce_StringPairArray.h ***/
  5632. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5633. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5634. /*** Start of inlined file: juce_StringArray.h ***/
  5635. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  5636. #define __JUCE_STRINGARRAY_JUCEHEADER__
  5637. /**
  5638. A special array for holding a list of strings.
  5639. @see String, StringPairArray
  5640. */
  5641. class JUCE_API StringArray
  5642. {
  5643. public:
  5644. /** Creates an empty string array */
  5645. StringArray() throw();
  5646. /** Creates a copy of another string array */
  5647. StringArray (const StringArray& other);
  5648. /** Creates an array containing a single string. */
  5649. explicit StringArray (const String& firstValue);
  5650. /** Creates a copy of an array of string literals.
  5651. @param strings an array of strings to add. Null pointers in the array will be
  5652. treated as empty strings
  5653. @param numberOfStrings how many items there are in the array
  5654. */
  5655. StringArray (const juce_wchar* const* strings, int numberOfStrings);
  5656. /** Creates a copy of an array of string literals.
  5657. @param strings an array of strings to add. Null pointers in the array will be
  5658. treated as empty strings
  5659. @param numberOfStrings how many items there are in the array
  5660. */
  5661. StringArray (const char* const* strings, int numberOfStrings);
  5662. /** Creates a copy of a null-terminated array of string literals.
  5663. Each item from the array passed-in is added, until it encounters a null pointer,
  5664. at which point it stops.
  5665. */
  5666. explicit StringArray (const juce_wchar* const* strings);
  5667. /** Creates a copy of a null-terminated array of string literals.
  5668. Each item from the array passed-in is added, until it encounters a null pointer,
  5669. at which point it stops.
  5670. */
  5671. explicit StringArray (const char* const* strings);
  5672. /** Destructor. */
  5673. ~StringArray();
  5674. /** Copies the contents of another string array into this one */
  5675. StringArray& operator= (const StringArray& other);
  5676. /** Compares two arrays.
  5677. Comparisons are case-sensitive.
  5678. @returns true only if the other array contains exactly the same strings in the same order
  5679. */
  5680. bool operator== (const StringArray& other) const throw();
  5681. /** Compares two arrays.
  5682. Comparisons are case-sensitive.
  5683. @returns false if the other array contains exactly the same strings in the same order
  5684. */
  5685. bool operator!= (const StringArray& other) const throw();
  5686. /** Returns the number of strings in the array */
  5687. inline int size() const throw() { return strings.size(); };
  5688. /** Returns one of the strings from the array.
  5689. If the index is out-of-range, an empty string is returned.
  5690. Obviously the reference returned shouldn't be stored for later use, as the
  5691. string it refers to may disappear when the array changes.
  5692. */
  5693. const String& operator[] (int index) const throw();
  5694. /** Returns a reference to one of the strings in the array.
  5695. This lets you modify a string in-place in the array, but you must be sure that
  5696. the index is in-range.
  5697. */
  5698. String& getReference (int index) throw();
  5699. /** Searches for a string in the array.
  5700. The comparison will be case-insensitive if the ignoreCase parameter is true.
  5701. @returns true if the string is found inside the array
  5702. */
  5703. bool contains (const String& stringToLookFor,
  5704. bool ignoreCase = false) const;
  5705. /** Searches for a string in the array.
  5706. The comparison will be case-insensitive if the ignoreCase parameter is true.
  5707. @param stringToLookFor the string to try to find
  5708. @param ignoreCase whether the comparison should be case-insensitive
  5709. @param startIndex the first index to start searching from
  5710. @returns the index of the first occurrence of the string in this array,
  5711. or -1 if it isn't found.
  5712. */
  5713. int indexOf (const String& stringToLookFor,
  5714. bool ignoreCase = false,
  5715. int startIndex = 0) const;
  5716. /** Appends a string at the end of the array. */
  5717. void add (const String& stringToAdd);
  5718. /** Inserts a string into the array.
  5719. This will insert a string into the array at the given index, moving
  5720. up the other elements to make room for it.
  5721. If the index is less than zero or greater than the size of the array,
  5722. the new string will be added to the end of the array.
  5723. */
  5724. void insert (int index, const String& stringToAdd);
  5725. /** Adds a string to the array as long as it's not already in there.
  5726. The search can optionally be case-insensitive.
  5727. */
  5728. void addIfNotAlreadyThere (const String& stringToAdd, bool ignoreCase = false);
  5729. /** Replaces one of the strings in the array with another one.
  5730. If the index is higher than the array's size, the new string will be
  5731. added to the end of the array; if it's less than zero nothing happens.
  5732. */
  5733. void set (int index, const String& newString);
  5734. /** Appends some strings from another array to the end of this one.
  5735. @param other the array to add
  5736. @param startIndex the first element of the other array to add
  5737. @param numElementsToAdd the maximum number of elements to add (if this is
  5738. less than zero, they are all added)
  5739. */
  5740. void addArray (const StringArray& other,
  5741. int startIndex = 0,
  5742. int numElementsToAdd = -1);
  5743. /** Breaks up a string into tokens and adds them to this array.
  5744. This will tokenise the given string using whitespace characters as the
  5745. token delimiters, and will add these tokens to the end of the array.
  5746. @returns the number of tokens added
  5747. */
  5748. int addTokens (const String& stringToTokenise,
  5749. bool preserveQuotedStrings);
  5750. /** Breaks up a string into tokens and adds them to this array.
  5751. This will tokenise the given string (using the string passed in to define the
  5752. token delimiters), and will add these tokens to the end of the array.
  5753. @param stringToTokenise the string to tokenise
  5754. @param breakCharacters a string of characters, any of which will be considered
  5755. to be a token delimiter.
  5756. @param quoteCharacters if this string isn't empty, it defines a set of characters
  5757. which are treated as quotes. Any text occurring
  5758. between quotes is not broken up into tokens.
  5759. @returns the number of tokens added
  5760. */
  5761. int addTokens (const String& stringToTokenise,
  5762. const String& breakCharacters,
  5763. const String& quoteCharacters);
  5764. /** Breaks up a string into lines and adds them to this array.
  5765. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  5766. to the array. Line-break characters are omitted from the strings that are added to
  5767. the array.
  5768. */
  5769. int addLines (const String& stringToBreakUp);
  5770. /** Removes all elements from the array. */
  5771. void clear();
  5772. /** Removes a string from the array.
  5773. If the index is out-of-range, no action will be taken.
  5774. */
  5775. void remove (int index);
  5776. /** Finds a string in the array and removes it.
  5777. This will remove the first occurrence of the given string from the array. The
  5778. comparison may be case-insensitive depending on the ignoreCase parameter.
  5779. */
  5780. void removeString (const String& stringToRemove,
  5781. bool ignoreCase = false);
  5782. /** Removes a range of elements from the array.
  5783. This will remove a set of elements, starting from the given index,
  5784. and move subsequent elements down to close the gap.
  5785. If the range extends beyond the bounds of the array, it will
  5786. be safely clipped to the size of the array.
  5787. @param startIndex the index of the first element to remove
  5788. @param numberToRemove how many elements should be removed
  5789. */
  5790. void removeRange (int startIndex, int numberToRemove);
  5791. /** Removes any duplicated elements from the array.
  5792. If any string appears in the array more than once, only the first occurrence of
  5793. it will be retained.
  5794. @param ignoreCase whether to use a case-insensitive comparison
  5795. */
  5796. void removeDuplicates (bool ignoreCase);
  5797. /** Removes empty strings from the array.
  5798. @param removeWhitespaceStrings if true, strings that only contain whitespace
  5799. characters will also be removed
  5800. */
  5801. void removeEmptyStrings (bool removeWhitespaceStrings = true);
  5802. /** Moves one of the strings to a different position.
  5803. This will move the string to a specified index, shuffling along
  5804. any intervening elements as required.
  5805. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  5806. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  5807. @param currentIndex the index of the value to be moved. If this isn't a
  5808. valid index, then nothing will be done
  5809. @param newIndex the index at which you'd like this value to end up. If this
  5810. is less than zero, the value will be moved to the end
  5811. of the array
  5812. */
  5813. void move (int currentIndex, int newIndex) throw();
  5814. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  5815. void trim();
  5816. /** Adds numbers to the strings in the array, to make each string unique.
  5817. This will add numbers to the ends of groups of similar strings.
  5818. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  5819. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  5820. @param appendNumberToFirstInstance whether the first of a group of similar strings
  5821. also has a number appended to it.
  5822. @param preNumberString when adding a number, this string is added before the number.
  5823. If you pass 0, a default string will be used, which adds
  5824. brackets around the number.
  5825. @param postNumberString this string is appended after any numbers that are added.
  5826. If you pass 0, a default string will be used, which adds
  5827. brackets around the number.
  5828. */
  5829. void appendNumbersToDuplicates (bool ignoreCaseWhenComparing,
  5830. bool appendNumberToFirstInstance,
  5831. const juce_wchar* preNumberString = 0,
  5832. const juce_wchar* postNumberString = 0);
  5833. /** Joins the strings in the array together into one string.
  5834. This will join a range of elements from the array into a string, separating
  5835. them with a given string.
  5836. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  5837. @param separatorString the string to insert between all the strings
  5838. @param startIndex the first element to join
  5839. @param numberOfElements how many elements to join together. If this is less
  5840. than zero, all available elements will be used.
  5841. */
  5842. const String joinIntoString (const String& separatorString,
  5843. int startIndex = 0,
  5844. int numberOfElements = -1) const;
  5845. /** Sorts the array into alphabetical order.
  5846. @param ignoreCase if true, the comparisons used will be case-sensitive.
  5847. */
  5848. void sort (bool ignoreCase);
  5849. /** Reduces the amount of storage being used by the array.
  5850. Arrays typically allocate slightly more storage than they need, and after
  5851. removing elements, they may have quite a lot of unused space allocated.
  5852. This method will reduce the amount of allocated storage to a minimum.
  5853. */
  5854. void minimiseStorageOverheads();
  5855. juce_UseDebuggingNewOperator
  5856. private:
  5857. Array <String> strings;
  5858. };
  5859. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  5860. /*** End of inlined file: juce_StringArray.h ***/
  5861. /**
  5862. A container for holding a set of strings which are keyed by another string.
  5863. @see StringArray
  5864. */
  5865. class JUCE_API StringPairArray
  5866. {
  5867. public:
  5868. /** Creates an empty array */
  5869. StringPairArray (bool ignoreCaseWhenComparingKeys = true);
  5870. /** Creates a copy of another array */
  5871. StringPairArray (const StringPairArray& other);
  5872. /** Destructor. */
  5873. ~StringPairArray();
  5874. /** Copies the contents of another string array into this one */
  5875. StringPairArray& operator= (const StringPairArray& other);
  5876. /** Compares two arrays.
  5877. Comparisons are case-sensitive.
  5878. @returns true only if the other array contains exactly the same strings with the same keys
  5879. */
  5880. bool operator== (const StringPairArray& other) const;
  5881. /** Compares two arrays.
  5882. Comparisons are case-sensitive.
  5883. @returns false if the other array contains exactly the same strings with the same keys
  5884. */
  5885. bool operator!= (const StringPairArray& other) const;
  5886. /** Finds the value corresponding to a key string.
  5887. If no such key is found, this will just return an empty string. To check whether
  5888. a given key actually exists (because it might actually be paired with an empty string), use
  5889. the getAllKeys() method to obtain a list.
  5890. Obviously the reference returned shouldn't be stored for later use, as the
  5891. string it refers to may disappear when the array changes.
  5892. @see getValue
  5893. */
  5894. const String& operator[] (const String& key) const;
  5895. /** Finds the value corresponding to a key string.
  5896. If no such key is found, this will just return the value provided as a default.
  5897. @see operator[]
  5898. */
  5899. const String getValue (const String& key, const String& defaultReturnValue) const;
  5900. /** Returns a list of all keys in the array. */
  5901. const StringArray& getAllKeys() const throw() { return keys; }
  5902. /** Returns a list of all values in the array. */
  5903. const StringArray& getAllValues() const throw() { return values; }
  5904. /** Returns the number of strings in the array */
  5905. inline int size() const throw() { return keys.size(); };
  5906. /** Adds or amends a key/value pair.
  5907. If a value already exists with this key, its value will be overwritten,
  5908. otherwise the key/value pair will be added to the array.
  5909. */
  5910. void set (const String& key, const String& value);
  5911. /** Adds the items from another array to this one.
  5912. This is equivalent to using set() to add each of the pairs from the other array.
  5913. */
  5914. void addArray (const StringPairArray& other);
  5915. /** Removes all elements from the array. */
  5916. void clear();
  5917. /** Removes a string from the array based on its key.
  5918. If the key isn't found, nothing will happen.
  5919. */
  5920. void remove (const String& key);
  5921. /** Removes a string from the array based on its index.
  5922. If the index is out-of-range, no action will be taken.
  5923. */
  5924. void remove (int index);
  5925. /** Indicates whether to use a case-insensitive search when looking up a key string.
  5926. */
  5927. void setIgnoresCase (bool shouldIgnoreCase);
  5928. /** Returns a descriptive string containing the items.
  5929. This is handy for dumping the contents of an array.
  5930. */
  5931. const String getDescription() const;
  5932. /** Reduces the amount of storage being used by the array.
  5933. Arrays typically allocate slightly more storage than they need, and after
  5934. removing elements, they may have quite a lot of unused space allocated.
  5935. This method will reduce the amount of allocated storage to a minimum.
  5936. */
  5937. void minimiseStorageOverheads();
  5938. juce_UseDebuggingNewOperator
  5939. private:
  5940. StringArray keys, values;
  5941. bool ignoreCase;
  5942. };
  5943. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5944. /*** End of inlined file: juce_StringPairArray.h ***/
  5945. /*** Start of inlined file: juce_XmlElement.h ***/
  5946. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  5947. #define __JUCE_XMLELEMENT_JUCEHEADER__
  5948. /*** Start of inlined file: juce_File.h ***/
  5949. #ifndef __JUCE_FILE_JUCEHEADER__
  5950. #define __JUCE_FILE_JUCEHEADER__
  5951. /*** Start of inlined file: juce_Time.h ***/
  5952. #ifndef __JUCE_TIME_JUCEHEADER__
  5953. #define __JUCE_TIME_JUCEHEADER__
  5954. /*** Start of inlined file: juce_RelativeTime.h ***/
  5955. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  5956. #define __JUCE_RELATIVETIME_JUCEHEADER__
  5957. /** A relative measure of time.
  5958. The time is stored as a number of seconds, at double-precision floating
  5959. point accuracy, and may be positive or negative.
  5960. If you need an absolute time, (i.e. a date + time), see the Time class.
  5961. */
  5962. class JUCE_API RelativeTime
  5963. {
  5964. public:
  5965. /** Creates a RelativeTime.
  5966. @param seconds the number of seconds, which may be +ve or -ve.
  5967. @see milliseconds, minutes, hours, days, weeks
  5968. */
  5969. explicit RelativeTime (double seconds = 0.0) throw();
  5970. /** Copies another relative time. */
  5971. RelativeTime (const RelativeTime& other) throw();
  5972. /** Copies another relative time. */
  5973. RelativeTime& operator= (const RelativeTime& other) throw();
  5974. /** Destructor. */
  5975. ~RelativeTime() throw();
  5976. /** Creates a new RelativeTime object representing a number of milliseconds.
  5977. @see minutes, hours, days, weeks
  5978. */
  5979. static const RelativeTime milliseconds (int milliseconds) throw();
  5980. /** Creates a new RelativeTime object representing a number of milliseconds.
  5981. @see minutes, hours, days, weeks
  5982. */
  5983. static const RelativeTime milliseconds (int64 milliseconds) throw();
  5984. /** Creates a new RelativeTime object representing a number of minutes.
  5985. @see milliseconds, hours, days, weeks
  5986. */
  5987. static const RelativeTime minutes (double numberOfMinutes) throw();
  5988. /** Creates a new RelativeTime object representing a number of hours.
  5989. @see milliseconds, minutes, days, weeks
  5990. */
  5991. static const RelativeTime hours (double numberOfHours) throw();
  5992. /** Creates a new RelativeTime object representing a number of days.
  5993. @see milliseconds, minutes, hours, weeks
  5994. */
  5995. static const RelativeTime days (double numberOfDays) throw();
  5996. /** Creates a new RelativeTime object representing a number of weeks.
  5997. @see milliseconds, minutes, hours, days
  5998. */
  5999. static const RelativeTime weeks (double numberOfWeeks) throw();
  6000. /** Returns the number of milliseconds this time represents.
  6001. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  6002. */
  6003. int64 inMilliseconds() const throw();
  6004. /** Returns the number of seconds this time represents.
  6005. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  6006. */
  6007. double inSeconds() const throw() { return seconds; }
  6008. /** Returns the number of minutes this time represents.
  6009. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  6010. */
  6011. double inMinutes() const throw();
  6012. /** Returns the number of hours this time represents.
  6013. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  6014. */
  6015. double inHours() const throw();
  6016. /** Returns the number of days this time represents.
  6017. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  6018. */
  6019. double inDays() const throw();
  6020. /** Returns the number of weeks this time represents.
  6021. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  6022. */
  6023. double inWeeks() const throw();
  6024. /** Returns a readable textual description of the time.
  6025. The exact format of the string returned will depend on
  6026. the magnitude of the time - e.g.
  6027. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  6028. so that only the two most significant units are printed.
  6029. The returnValueForZeroTime value is the result that is returned if the
  6030. length is zero. Depending on your application you might want to use this
  6031. to return something more relevant like "empty" or "0 secs", etc.
  6032. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  6033. */
  6034. const String getDescription (const String& returnValueForZeroTime = "0") const throw();
  6035. /** Compares two RelativeTimes. */
  6036. bool operator== (const RelativeTime& other) const throw();
  6037. /** Compares two RelativeTimes. */
  6038. bool operator!= (const RelativeTime& other) const throw();
  6039. /** Compares two RelativeTimes. */
  6040. bool operator> (const RelativeTime& other) const throw();
  6041. /** Compares two RelativeTimes. */
  6042. bool operator< (const RelativeTime& other) const throw();
  6043. /** Compares two RelativeTimes. */
  6044. bool operator>= (const RelativeTime& other) const throw();
  6045. /** Compares two RelativeTimes. */
  6046. bool operator<= (const RelativeTime& other) const throw();
  6047. /** Adds another RelativeTime to this one and returns the result. */
  6048. const RelativeTime operator+ (const RelativeTime& timeToAdd) const throw();
  6049. /** Subtracts another RelativeTime from this one and returns the result. */
  6050. const RelativeTime operator- (const RelativeTime& timeToSubtract) const throw();
  6051. /** Adds a number of seconds to this RelativeTime and returns the result. */
  6052. const RelativeTime operator+ (double secondsToAdd) const throw();
  6053. /** Subtracts a number of seconds from this RelativeTime and returns the result. */
  6054. const RelativeTime operator- (double secondsToSubtract) const throw();
  6055. /** Adds another RelativeTime to this one. */
  6056. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  6057. /** Subtracts another RelativeTime from this one. */
  6058. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  6059. /** Adds a number of seconds to this time. */
  6060. const RelativeTime& operator+= (double secondsToAdd) throw();
  6061. /** Subtracts a number of seconds from this time. */
  6062. const RelativeTime& operator-= (double secondsToSubtract) throw();
  6063. juce_UseDebuggingNewOperator
  6064. private:
  6065. double seconds;
  6066. };
  6067. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  6068. /*** End of inlined file: juce_RelativeTime.h ***/
  6069. /**
  6070. Holds an absolute date and time.
  6071. Internally, the time is stored at millisecond precision.
  6072. @see RelativeTime
  6073. */
  6074. class JUCE_API Time
  6075. {
  6076. public:
  6077. /** Creates a Time object.
  6078. This default constructor creates a time of 1st January 1970, (which is
  6079. represented internally as 0ms).
  6080. To create a time object representing the current time, use getCurrentTime().
  6081. @see getCurrentTime
  6082. */
  6083. Time() throw();
  6084. /** Creates a copy of another Time object. */
  6085. Time (const Time& other) throw();
  6086. /** Creates a time based on a number of milliseconds.
  6087. The internal millisecond count is set to 0 (1st January 1970). To create a
  6088. time object set to the current time, use getCurrentTime().
  6089. @param millisecondsSinceEpoch the number of milliseconds since the unix
  6090. 'epoch' (midnight Jan 1st 1970).
  6091. @see getCurrentTime, currentTimeMillis
  6092. */
  6093. Time (int64 millisecondsSinceEpoch) throw();
  6094. /** Creates a time from a set of date components.
  6095. The timezone is assumed to be whatever the system is using as its locale.
  6096. @param year the year, in 4-digit format, e.g. 2004
  6097. @param month the month, in the range 0 to 11
  6098. @param day the day of the month, in the range 1 to 31
  6099. @param hours hours in 24-hour clock format, 0 to 23
  6100. @param minutes minutes 0 to 59
  6101. @param seconds seconds 0 to 59
  6102. @param milliseconds milliseconds 0 to 999
  6103. @param useLocalTime if true, encode using the current machine's local time; if
  6104. false, it will always work in GMT.
  6105. */
  6106. Time (int year,
  6107. int month,
  6108. int day,
  6109. int hours,
  6110. int minutes,
  6111. int seconds = 0,
  6112. int milliseconds = 0,
  6113. bool useLocalTime = true) throw();
  6114. /** Destructor. */
  6115. ~Time() throw();
  6116. /** Copies this time from another one. */
  6117. Time& operator= (const Time& other) throw();
  6118. /** Returns a Time object that is set to the current system time.
  6119. @see currentTimeMillis
  6120. */
  6121. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  6122. /** Returns the time as a number of milliseconds.
  6123. @returns the number of milliseconds this Time object represents, since
  6124. midnight jan 1st 1970.
  6125. @see getMilliseconds
  6126. */
  6127. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  6128. /** Returns the year.
  6129. A 4-digit format is used, e.g. 2004.
  6130. */
  6131. int getYear() const throw();
  6132. /** Returns the number of the month.
  6133. The value returned is in the range 0 to 11.
  6134. @see getMonthName
  6135. */
  6136. int getMonth() const throw();
  6137. /** Returns the name of the month.
  6138. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  6139. it'll return the long form, e.g. "January"
  6140. @see getMonth
  6141. */
  6142. const String getMonthName (bool threeLetterVersion) const throw();
  6143. /** Returns the day of the month.
  6144. The value returned is in the range 1 to 31.
  6145. */
  6146. int getDayOfMonth() const throw();
  6147. /** Returns the number of the day of the week.
  6148. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  6149. */
  6150. int getDayOfWeek() const throw();
  6151. /** Returns the name of the weekday.
  6152. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  6153. false, it'll return the full version, e.g. "Tuesday".
  6154. */
  6155. const String getWeekdayName (bool threeLetterVersion) const throw();
  6156. /** Returns the number of hours since midnight.
  6157. This is in 24-hour clock format, in the range 0 to 23.
  6158. @see getHoursInAmPmFormat, isAfternoon
  6159. */
  6160. int getHours() const throw();
  6161. /** Returns true if the time is in the afternoon.
  6162. So it returns true for "PM", false for "AM".
  6163. @see getHoursInAmPmFormat, getHours
  6164. */
  6165. bool isAfternoon() const throw();
  6166. /** Returns the hours in 12-hour clock format.
  6167. This will return a value 1 to 12 - use isAfternoon() to find out
  6168. whether this is in the afternoon or morning.
  6169. @see getHours, isAfternoon
  6170. */
  6171. int getHoursInAmPmFormat() const throw();
  6172. /** Returns the number of minutes, 0 to 59. */
  6173. int getMinutes() const throw();
  6174. /** Returns the number of seconds, 0 to 59. */
  6175. int getSeconds() const throw();
  6176. /** Returns the number of milliseconds, 0 to 999.
  6177. Unlike toMilliseconds(), this just returns the position within the
  6178. current second rather than the total number since the epoch.
  6179. @see toMilliseconds
  6180. */
  6181. int getMilliseconds() const throw();
  6182. /** Returns true if the local timezone uses a daylight saving correction. */
  6183. bool isDaylightSavingTime() const throw();
  6184. /** Returns a 3-character string to indicate the local timezone. */
  6185. const String getTimeZone() const throw();
  6186. /** Quick way of getting a string version of a date and time.
  6187. For a more powerful way of formatting the date and time, see the formatted() method.
  6188. @param includeDate whether to include the date in the string
  6189. @param includeTime whether to include the time in the string
  6190. @param includeSeconds if the time is being included, this provides an option not to include
  6191. the seconds in it
  6192. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  6193. hour notation.
  6194. @see formatted
  6195. */
  6196. const String toString (bool includeDate,
  6197. bool includeTime,
  6198. bool includeSeconds = true,
  6199. bool use24HourClock = false) const throw();
  6200. /** Converts this date/time to a string with a user-defined format.
  6201. This uses the C strftime() function to format this time as a string. To save you
  6202. looking it up, these are the escape codes that strftime uses (other codes might
  6203. work on some platforms and not others, but these are the common ones):
  6204. %a is replaced by the locale's abbreviated weekday name.
  6205. %A is replaced by the locale's full weekday name.
  6206. %b is replaced by the locale's abbreviated month name.
  6207. %B is replaced by the locale's full month name.
  6208. %c is replaced by the locale's appropriate date and time representation.
  6209. %d is replaced by the day of the month as a decimal number [01,31].
  6210. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  6211. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  6212. %j is replaced by the day of the year as a decimal number [001,366].
  6213. %m is replaced by the month as a decimal number [01,12].
  6214. %M is replaced by the minute as a decimal number [00,59].
  6215. %p is replaced by the locale's equivalent of either a.m. or p.m.
  6216. %S is replaced by the second as a decimal number [00,61].
  6217. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  6218. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  6219. %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.
  6220. %x is replaced by the locale's appropriate date representation.
  6221. %X is replaced by the locale's appropriate time representation.
  6222. %y is replaced by the year without century as a decimal number [00,99].
  6223. %Y is replaced by the year with century as a decimal number.
  6224. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  6225. %% is replaced by %.
  6226. @see toString
  6227. */
  6228. const String formatted (const String& format) const throw();
  6229. /** Adds a RelativeTime to this time and returns the result. */
  6230. const Time operator+ (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch + delta.inMilliseconds()); }
  6231. /** Subtracts a RelativeTime from this time and returns the result. */
  6232. const Time operator- (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch - delta.inMilliseconds()); }
  6233. /** Returns the relative time difference between this time and another one. */
  6234. const RelativeTime operator- (const Time& other) const throw() { return RelativeTime::milliseconds (millisSinceEpoch - other.millisSinceEpoch); }
  6235. /** Compares two Time objects. */
  6236. bool operator== (const Time& other) const throw() { return millisSinceEpoch == other.millisSinceEpoch; }
  6237. /** Compares two Time objects. */
  6238. bool operator!= (const Time& other) const throw() { return millisSinceEpoch != other.millisSinceEpoch; }
  6239. /** Compares two Time objects. */
  6240. bool operator< (const Time& other) const throw() { return millisSinceEpoch < other.millisSinceEpoch; }
  6241. /** Compares two Time objects. */
  6242. bool operator<= (const Time& other) const throw() { return millisSinceEpoch <= other.millisSinceEpoch; }
  6243. /** Compares two Time objects. */
  6244. bool operator> (const Time& other) const throw() { return millisSinceEpoch > other.millisSinceEpoch; }
  6245. /** Compares two Time objects. */
  6246. bool operator>= (const Time& other) const throw() { return millisSinceEpoch >= other.millisSinceEpoch; }
  6247. /** Tries to set the computer's clock.
  6248. @returns true if this succeeds, although depending on the system, the
  6249. application might not have sufficient privileges to do this.
  6250. */
  6251. bool setSystemTimeToThisTime() const;
  6252. /** Returns the name of a day of the week.
  6253. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  6254. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  6255. false, it'll return the full version, e.g. "Tuesday".
  6256. */
  6257. static const String getWeekdayName (int dayNumber,
  6258. bool threeLetterVersion) throw();
  6259. /** Returns the name of one of the months.
  6260. @param monthNumber the month, 0 to 11
  6261. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  6262. it'll return the long form, e.g. "January"
  6263. */
  6264. static const String getMonthName (int monthNumber,
  6265. bool threeLetterVersion) throw();
  6266. // Static methods for getting system timers directly..
  6267. /** Returns the current system time.
  6268. Returns the number of milliseconds since midnight jan 1st 1970.
  6269. Should be accurate to within a few millisecs, depending on platform,
  6270. hardware, etc.
  6271. */
  6272. static int64 currentTimeMillis() throw();
  6273. /** Returns the number of millisecs since system startup.
  6274. Should be accurate to within a few millisecs, depending on platform,
  6275. hardware, etc.
  6276. @see getApproximateMillisecondCounter
  6277. */
  6278. static uint32 getMillisecondCounter() throw();
  6279. /** Returns the number of millisecs since system startup.
  6280. Same as getMillisecondCounter(), but returns a more accurate value, using
  6281. the high-res timer.
  6282. @see getMillisecondCounter
  6283. */
  6284. static double getMillisecondCounterHiRes() throw();
  6285. /** Waits until the getMillisecondCounter() reaches a given value.
  6286. This will make the thread sleep as efficiently as it can while it's waiting.
  6287. */
  6288. static void waitForMillisecondCounter (uint32 targetTime) throw();
  6289. /** Less-accurate but faster version of getMillisecondCounter().
  6290. This will return the last value that getMillisecondCounter() returned, so doesn't
  6291. need to make a system call, but is less accurate - it shouldn't be more than
  6292. 100ms away from the correct time, though, so is still accurate enough for a
  6293. lot of purposes.
  6294. @see getMillisecondCounter
  6295. */
  6296. static uint32 getApproximateMillisecondCounter() throw();
  6297. // High-resolution timers..
  6298. /** Returns the current high-resolution counter's tick-count.
  6299. This is a similar idea to getMillisecondCounter(), but with a higher
  6300. resolution.
  6301. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  6302. secondsToHighResolutionTicks
  6303. */
  6304. static int64 getHighResolutionTicks() throw();
  6305. /** Returns the resolution of the high-resolution counter in ticks per second.
  6306. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  6307. secondsToHighResolutionTicks
  6308. */
  6309. static int64 getHighResolutionTicksPerSecond() throw();
  6310. /** Converts a number of high-resolution ticks into seconds.
  6311. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  6312. secondsToHighResolutionTicks
  6313. */
  6314. static double highResolutionTicksToSeconds (int64 ticks) throw();
  6315. /** Converts a number seconds into high-resolution ticks.
  6316. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  6317. highResolutionTicksToSeconds
  6318. */
  6319. static int64 secondsToHighResolutionTicks (double seconds) throw();
  6320. private:
  6321. int64 millisSinceEpoch;
  6322. };
  6323. #endif // __JUCE_TIME_JUCEHEADER__
  6324. /*** End of inlined file: juce_Time.h ***/
  6325. class FileInputStream;
  6326. class FileOutputStream;
  6327. /**
  6328. Represents a local file or directory.
  6329. This class encapsulates the absolute pathname of a file or directory, and
  6330. has methods for finding out about the file and changing its properties.
  6331. To read or write to the file, there are methods for returning an input or
  6332. output stream.
  6333. @see FileInputStream, FileOutputStream
  6334. */
  6335. class JUCE_API File
  6336. {
  6337. public:
  6338. /** Creates an (invalid) file object.
  6339. The file is initially set to an empty path, so getFullPath() will return
  6340. an empty string, and comparing the file to File::nonexistent will return
  6341. true.
  6342. You can use its operator= method to point it at a proper file.
  6343. */
  6344. File() {}
  6345. /** Creates a file from an absolute path.
  6346. If the path supplied is a relative path, it is taken to be relative
  6347. to the current working directory (see File::getCurrentWorkingDirectory()),
  6348. but this isn't a recommended way of creating a file, because you
  6349. never know what the CWD is going to be.
  6350. On the Mac/Linux, the path can include "~" notation for referring to
  6351. user home directories.
  6352. */
  6353. File (const String& path);
  6354. /** Creates a copy of another file object. */
  6355. File (const File& other);
  6356. /** Destructor. */
  6357. ~File() {}
  6358. /** Sets the file based on an absolute pathname.
  6359. If the path supplied is a relative path, it is taken to be relative
  6360. to the current working directory (see File::getCurrentWorkingDirectory()),
  6361. but this isn't a recommended way of creating a file, because you
  6362. never know what the CWD is going to be.
  6363. On the Mac/Linux, the path can include "~" notation for referring to
  6364. user home directories.
  6365. */
  6366. File& operator= (const String& newFilePath);
  6367. /** Copies from another file object. */
  6368. File& operator= (const File& otherFile);
  6369. /** This static constant is used for referring to an 'invalid' file. */
  6370. static const File nonexistent;
  6371. /** Checks whether the file actually exists.
  6372. @returns true if the file exists, either as a file or a directory.
  6373. @see existsAsFile, isDirectory
  6374. */
  6375. bool exists() const;
  6376. /** Checks whether the file exists and is a file rather than a directory.
  6377. @returns true only if this is a real file, false if it's a directory
  6378. or doesn't exist
  6379. @see exists, isDirectory
  6380. */
  6381. bool existsAsFile() const;
  6382. /** Checks whether the file is a directory that exists.
  6383. @returns true only if the file is a directory which actually exists, so
  6384. false if it's a file or doesn't exist at all
  6385. @see exists, existsAsFile
  6386. */
  6387. bool isDirectory() const;
  6388. /** Returns the size of the file in bytes.
  6389. @returns the number of bytes in the file, or 0 if it doesn't exist.
  6390. */
  6391. int64 getSize() const;
  6392. /** Utility function to convert a file size in bytes to a neat string description.
  6393. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  6394. 2000000 would produce "2 MB", etc.
  6395. */
  6396. static const String descriptionOfSizeInBytes (int64 bytes);
  6397. /** Returns the complete, absolute path of this file.
  6398. This includes the filename and all its parent folders. On Windows it'll
  6399. also include the drive letter prefix; on Mac or Linux it'll be a complete
  6400. path starting from the root folder.
  6401. If you just want the file's name, you should use getFileName() or
  6402. getFileNameWithoutExtension().
  6403. @see getFileName, getRelativePathFrom
  6404. */
  6405. const String& getFullPathName() const throw() { return fullPath; }
  6406. /** Returns the last section of the pathname.
  6407. Returns just the final part of the path - e.g. if the whole path
  6408. is "/moose/fish/foo.txt" this will return "foo.txt".
  6409. For a directory, it returns the final part of the path - e.g. for the
  6410. directory "/moose/fish" it'll return "fish".
  6411. If the filename begins with a dot, it'll return the whole filename, e.g. for
  6412. "/moose/.fish", it'll return ".fish"
  6413. @see getFullPathName, getFileNameWithoutExtension
  6414. */
  6415. const String getFileName() const;
  6416. /** Creates a relative path that refers to a file relatively to a given directory.
  6417. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  6418. would return "../../foo.txt".
  6419. If it's not possible to navigate from one file to the other, an absolute
  6420. path is returned. If the paths are invalid, an empty string may also be
  6421. returned.
  6422. @param directoryToBeRelativeTo the directory which the resultant string will
  6423. be relative to. If this is actually a file rather than
  6424. a directory, its parent directory will be used instead.
  6425. If it doesn't exist, it's assumed to be a directory.
  6426. @see getChildFile, isAbsolutePath
  6427. */
  6428. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  6429. /** Returns the file's extension.
  6430. Returns the file extension of this file, also including the dot.
  6431. e.g. "/moose/fish/foo.txt" would return ".txt"
  6432. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  6433. */
  6434. const String getFileExtension() const;
  6435. /** Checks whether the file has a given extension.
  6436. @param extensionToTest the extension to look for - it doesn't matter whether or
  6437. not this string has a dot at the start, so ".wav" and "wav"
  6438. will have the same effect. The comparison used is
  6439. case-insensitve. To compare with multiple extensions, this
  6440. parameter can contain multiple strings, separated by semi-colons -
  6441. so, for example: hasFileExtension (".jpeg;png;gif") would return
  6442. true if the file has any of those three extensions.
  6443. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  6444. */
  6445. bool hasFileExtension (const String& extensionToTest) const;
  6446. /** Returns a version of this file with a different file extension.
  6447. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  6448. @param newExtension the new extension, either with or without a dot at the start (this
  6449. doesn't make any difference). To get remove a file's extension altogether,
  6450. pass an empty string into this function.
  6451. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  6452. */
  6453. const File withFileExtension (const String& newExtension) const;
  6454. /** Returns the last part of the filename, without its file extension.
  6455. e.g. for "/moose/fish/foo.txt" this will return "foo".
  6456. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  6457. */
  6458. const String getFileNameWithoutExtension() const;
  6459. /** Returns a 32-bit hash-code that identifies this file.
  6460. This is based on the filename. Obviously it's possible, although unlikely, that
  6461. two files will have the same hash-code.
  6462. */
  6463. int hashCode() const;
  6464. /** Returns a 64-bit hash-code that identifies this file.
  6465. This is based on the filename. Obviously it's possible, although unlikely, that
  6466. two files will have the same hash-code.
  6467. */
  6468. int64 hashCode64() const;
  6469. /** Returns a file based on a relative path.
  6470. This will find a child file or directory of the current object.
  6471. e.g.
  6472. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  6473. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  6474. If the string is actually an absolute path, it will be treated as such, e.g.
  6475. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  6476. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  6477. */
  6478. const File getChildFile (String relativePath) const;
  6479. /** Returns a file which is in the same directory as this one.
  6480. This is equivalent to getParentDirectory().getChildFile (name).
  6481. @see getChildFile, getParentDirectory
  6482. */
  6483. const File getSiblingFile (const String& siblingFileName) const;
  6484. /** Returns the directory that contains this file or directory.
  6485. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  6486. */
  6487. const File getParentDirectory() const;
  6488. /** Checks whether a file is somewhere inside a directory.
  6489. Returns true if this file is somewhere inside a subdirectory of the directory
  6490. that is passed in. Neither file actually has to exist, because the function
  6491. just checks the paths for similarities.
  6492. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  6493. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  6494. */
  6495. bool isAChildOf (const File& potentialParentDirectory) const;
  6496. /** Chooses a filename relative to this one that doesn't already exist.
  6497. If this file is a directory, this will return a child file of this
  6498. directory that doesn't exist, by adding numbers to a prefix and suffix until
  6499. it finds one that isn't already there.
  6500. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  6501. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  6502. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  6503. @param prefix the string to use for the filename before the number
  6504. @param suffix the string to add to the filename after the number
  6505. @param putNumbersInBrackets if true, this will create filenames in the
  6506. format "prefix(number)suffix", if false, it will leave the
  6507. brackets out.
  6508. */
  6509. const File getNonexistentChildFile (const String& prefix,
  6510. const String& suffix,
  6511. bool putNumbersInBrackets = true) const;
  6512. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  6513. If this file doesn't exist, this will just return itself, otherwise it
  6514. will return an appropriate sibling that doesn't exist, e.g. if a file
  6515. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  6516. @param putNumbersInBrackets whether to add brackets around the numbers that
  6517. get appended to the new filename.
  6518. */
  6519. const File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  6520. /** Compares the pathnames for two files. */
  6521. bool operator== (const File& otherFile) const;
  6522. /** Compares the pathnames for two files. */
  6523. bool operator!= (const File& otherFile) const;
  6524. /** Compares the pathnames for two files. */
  6525. bool operator< (const File& otherFile) const;
  6526. /** Compares the pathnames for two files. */
  6527. bool operator> (const File& otherFile) const;
  6528. /** Checks whether a file can be created or written to.
  6529. @returns true if it's possible to create and write to this file. If the file
  6530. doesn't already exist, this will check its parent directory to
  6531. see if writing is allowed.
  6532. @see setReadOnly
  6533. */
  6534. bool hasWriteAccess() const;
  6535. /** Changes the write-permission of a file or directory.
  6536. @param shouldBeReadOnly whether to add or remove write-permission
  6537. @param applyRecursively if the file is a directory and this is true, it will
  6538. recurse through all the subfolders changing the permissions
  6539. of all files
  6540. @returns true if it manages to change the file's permissions.
  6541. @see hasWriteAccess
  6542. */
  6543. bool setReadOnly (bool shouldBeReadOnly,
  6544. bool applyRecursively = false) const;
  6545. /** Returns true if this file is a hidden or system file.
  6546. The criteria for deciding whether a file is hidden are platform-dependent.
  6547. */
  6548. bool isHidden() const;
  6549. /** If this file is a link, this returns the file that it points to.
  6550. If this file isn't actually link, it'll just return itself.
  6551. */
  6552. const File getLinkedTarget() const;
  6553. /** Returns the last modification time of this file.
  6554. @returns the time, or an invalid time if the file doesn't exist.
  6555. @see setLastModificationTime, getLastAccessTime, getCreationTime
  6556. */
  6557. const Time getLastModificationTime() const;
  6558. /** Returns the last time this file was accessed.
  6559. @returns the time, or an invalid time if the file doesn't exist.
  6560. @see setLastAccessTime, getLastModificationTime, getCreationTime
  6561. */
  6562. const Time getLastAccessTime() const;
  6563. /** Returns the time that this file was created.
  6564. @returns the time, or an invalid time if the file doesn't exist.
  6565. @see getLastModificationTime, getLastAccessTime
  6566. */
  6567. const Time getCreationTime() const;
  6568. /** Changes the modification time for this file.
  6569. @param newTime the time to apply to the file
  6570. @returns true if it manages to change the file's time.
  6571. @see getLastModificationTime, setLastAccessTime, setCreationTime
  6572. */
  6573. bool setLastModificationTime (const Time& newTime) const;
  6574. /** Changes the last-access time for this file.
  6575. @param newTime the time to apply to the file
  6576. @returns true if it manages to change the file's time.
  6577. @see getLastAccessTime, setLastModificationTime, setCreationTime
  6578. */
  6579. bool setLastAccessTime (const Time& newTime) const;
  6580. /** Changes the creation date for this file.
  6581. @param newTime the time to apply to the file
  6582. @returns true if it manages to change the file's time.
  6583. @see getCreationTime, setLastModificationTime, setLastAccessTime
  6584. */
  6585. bool setCreationTime (const Time& newTime) const;
  6586. /** If possible, this will try to create a version string for the given file.
  6587. The OS may be able to look at the file and give a version for it - e.g. with
  6588. executables, bundles, dlls, etc. If no version is available, this will
  6589. return an empty string.
  6590. */
  6591. const String getVersion() const;
  6592. /** Creates an empty file if it doesn't already exist.
  6593. If the file that this object refers to doesn't exist, this will create a file
  6594. of zero size.
  6595. If it already exists or is a directory, this method will do nothing.
  6596. @returns true if the file has been created (or if it already existed).
  6597. @see createDirectory
  6598. */
  6599. bool create() const;
  6600. /** Creates a new directory for this filename.
  6601. This will try to create the file as a directory, and fill also create
  6602. any parent directories it needs in order to complete the operation.
  6603. @returns true if the directory has been created successfully, (or if it
  6604. already existed beforehand).
  6605. @see create
  6606. */
  6607. bool createDirectory() const;
  6608. /** Deletes a file.
  6609. If this file is actually a directory, it may not be deleted correctly if it
  6610. contains files. See deleteRecursively() as a better way of deleting directories.
  6611. @returns true if the file has been successfully deleted (or if it didn't exist to
  6612. begin with).
  6613. @see deleteRecursively
  6614. */
  6615. bool deleteFile() const;
  6616. /** Deletes a file or directory and all its subdirectories.
  6617. If this file is a directory, this will try to delete it and all its subfolders. If
  6618. it's just a file, it will just try to delete the file.
  6619. @returns true if the file and all its subfolders have been successfully deleted
  6620. (or if it didn't exist to begin with).
  6621. @see deleteFile
  6622. */
  6623. bool deleteRecursively() const;
  6624. /** Moves this file or folder to the trash.
  6625. @returns true if the operation succeeded. It could fail if the trash is full, or
  6626. if the file is write-protected, so you should check the return value
  6627. and act appropriately.
  6628. */
  6629. bool moveToTrash() const;
  6630. /** Moves or renames a file.
  6631. Tries to move a file to a different location.
  6632. If the target file already exists, this will attempt to delete it first, and
  6633. will fail if this can't be done.
  6634. Note that the destination file isn't the directory to put it in, it's the actual
  6635. filename that you want the new file to have.
  6636. @returns true if the operation succeeds
  6637. */
  6638. bool moveFileTo (const File& targetLocation) const;
  6639. /** Copies a file.
  6640. Tries to copy a file to a different location.
  6641. If the target file already exists, this will attempt to delete it first, and
  6642. will fail if this can't be done.
  6643. @returns true if the operation succeeds
  6644. */
  6645. bool copyFileTo (const File& targetLocation) const;
  6646. /** Copies a directory.
  6647. Tries to copy an entire directory, recursively.
  6648. If this file isn't a directory or if any target files can't be created, this
  6649. will return false.
  6650. @param newDirectory the directory that this one should be copied to. Note that this
  6651. is the name of the actual directory to create, not the directory
  6652. into which the new one should be placed, so there must be enough
  6653. write privileges to create it if it doesn't exist. Any files inside
  6654. it will be overwritten by similarly named ones that are copied.
  6655. */
  6656. bool copyDirectoryTo (const File& newDirectory) const;
  6657. /** Used in file searching, to specify whether to return files, directories, or both.
  6658. */
  6659. enum TypesOfFileToFind
  6660. {
  6661. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  6662. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  6663. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  6664. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  6665. };
  6666. /** Searches inside a directory for files matching a wildcard pattern.
  6667. Assuming that this file is a directory, this method will search it
  6668. for either files or subdirectories whose names match a filename pattern.
  6669. @param results an array to which File objects will be added for the
  6670. files that the search comes up with
  6671. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  6672. return files, directories, or both. If the ignoreHiddenFiles flag
  6673. is also added to this value, hidden files won't be returned
  6674. @param searchRecursively if true, all subdirectories will be recursed into to do
  6675. an exhaustive search
  6676. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  6677. @returns the number of results that have been found
  6678. @see getNumberOfChildFiles, DirectoryIterator
  6679. */
  6680. int findChildFiles (Array<File>& results,
  6681. int whatToLookFor,
  6682. bool searchRecursively,
  6683. const String& wildCardPattern = "*") const;
  6684. /** Searches inside a directory and counts how many files match a wildcard pattern.
  6685. Assuming that this file is a directory, this method will search it
  6686. for either files or subdirectories whose names match a filename pattern,
  6687. and will return the number of matches found.
  6688. This isn't a recursive call, and will only search this directory, not
  6689. its children.
  6690. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  6691. count files, directories, or both. If the ignoreHiddenFiles flag
  6692. is also added to this value, hidden files won't be counted
  6693. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  6694. @returns the number of matches found
  6695. @see findChildFiles, DirectoryIterator
  6696. */
  6697. int getNumberOfChildFiles (int whatToLookFor,
  6698. const String& wildCardPattern = "*") const;
  6699. /** Returns true if this file is a directory that contains one or more subdirectories.
  6700. @see isDirectory, findChildFiles
  6701. */
  6702. bool containsSubDirectories() const;
  6703. /** Creates a stream to read from this file.
  6704. @returns a stream that will read from this file (initially positioned at the
  6705. start of the file), or 0 if the file can't be opened for some reason
  6706. @see createOutputStream, loadFileAsData
  6707. */
  6708. FileInputStream* createInputStream() const;
  6709. /** Creates a stream to write to this file.
  6710. If the file exists, the stream that is returned will be positioned ready for
  6711. writing at the end of the file, so you might want to use deleteFile() first
  6712. to write to an empty file.
  6713. @returns a stream that will write to this file (initially positioned at the
  6714. end of the file), or 0 if the file can't be opened for some reason
  6715. @see createInputStream, appendData, appendText
  6716. */
  6717. FileOutputStream* createOutputStream (int bufferSize = 0x8000) const;
  6718. /** Loads a file's contents into memory as a block of binary data.
  6719. Of course, trying to load a very large file into memory will blow up, so
  6720. it's better to check first.
  6721. @param result the data block to which the file's contents should be appended - note
  6722. that if the memory block might already contain some data, you
  6723. might want to clear it first
  6724. @returns true if the file could all be read into memory
  6725. */
  6726. bool loadFileAsData (MemoryBlock& result) const;
  6727. /** Reads a file into memory as a string.
  6728. Attempts to load the entire file as a zero-terminated string.
  6729. This makes use of InputStream::readEntireStreamAsString, which should
  6730. automatically cope with unicode/acsii file formats.
  6731. */
  6732. const String loadFileAsString() const;
  6733. /** Appends a block of binary data to the end of the file.
  6734. This will try to write the given buffer to the end of the file.
  6735. @returns false if it can't write to the file for some reason
  6736. */
  6737. bool appendData (const void* dataToAppend,
  6738. int numberOfBytes) const;
  6739. /** Replaces this file's contents with a given block of data.
  6740. This will delete the file and replace it with the given data.
  6741. A nice feature of this method is that it's safe - instead of deleting
  6742. the file first and then re-writing it, it creates a new temporary file,
  6743. writes the data to that, and then moves the new file to replace the existing
  6744. file. This means that if the power gets pulled out or something crashes,
  6745. you're a lot less likely to end up with an empty file..
  6746. Returns true if the operation succeeds, or false if it fails.
  6747. @see appendText
  6748. */
  6749. bool replaceWithData (const void* dataToWrite,
  6750. int numberOfBytes) const;
  6751. /** Appends a string to the end of the file.
  6752. This will try to append a text string to the file, as either 16-bit unicode
  6753. or 8-bit characters in the default system encoding.
  6754. It can also write the 'ff fe' unicode header bytes before the text to indicate
  6755. the endianness of the file.
  6756. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  6757. @see replaceWithText
  6758. */
  6759. bool appendText (const String& textToAppend,
  6760. bool asUnicode = false,
  6761. bool writeUnicodeHeaderBytes = false) const;
  6762. /** Replaces this file's contents with a given text string.
  6763. This will delete the file and replace it with the given text.
  6764. A nice feature of this method is that it's safe - instead of deleting
  6765. the file first and then re-writing it, it creates a new temporary file,
  6766. writes the text to that, and then moves the new file to replace the existing
  6767. file. This means that if the power gets pulled out or something crashes,
  6768. you're a lot less likely to end up with an empty file..
  6769. For an explanation of the parameters here, see the appendText() method.
  6770. Returns true if the operation succeeds, or false if it fails.
  6771. @see appendText
  6772. */
  6773. bool replaceWithText (const String& textToWrite,
  6774. bool asUnicode = false,
  6775. bool writeUnicodeHeaderBytes = false) const;
  6776. /** Attempts to scan the contents of this file and compare it to another file, returning
  6777. true if this is possible and they match byte-for-byte.
  6778. */
  6779. bool hasIdenticalContentTo (const File& other) const;
  6780. /** Creates a set of files to represent each file root.
  6781. e.g. on Windows this will create files for "c:\", "d:\" etc according
  6782. to which ones are available. On the Mac/Linux, this will probably
  6783. just add a single entry for "/".
  6784. */
  6785. static void findFileSystemRoots (Array<File>& results);
  6786. /** Finds the name of the drive on which this file lives.
  6787. @returns the volume label of the drive, or an empty string if this isn't possible
  6788. */
  6789. const String getVolumeLabel() const;
  6790. /** Returns the serial number of the volume on which this file lives.
  6791. @returns the serial number, or zero if there's a problem doing this
  6792. */
  6793. int getVolumeSerialNumber() const;
  6794. /** Returns the number of bytes free on the drive that this file lives on.
  6795. @returns the number of bytes free, or 0 if there's a problem finding this out
  6796. @see getVolumeTotalSize
  6797. */
  6798. int64 getBytesFreeOnVolume() const;
  6799. /** Returns the total size of the drive that contains this file.
  6800. @returns the total number of bytes that the volume can hold
  6801. @see getBytesFreeOnVolume
  6802. */
  6803. int64 getVolumeTotalSize() const;
  6804. /** Returns true if this file is on a CD or DVD drive. */
  6805. bool isOnCDRomDrive() const;
  6806. /** Returns true if this file is on a hard disk.
  6807. This will fail if it's a network drive, but will still be true for
  6808. removable hard-disks.
  6809. */
  6810. bool isOnHardDisk() const;
  6811. /** Returns true if this file is on a removable disk drive.
  6812. This might be a usb-drive, a CD-rom, or maybe a network drive.
  6813. */
  6814. bool isOnRemovableDrive() const;
  6815. /** Launches the file as a process.
  6816. - if the file is executable, this will run it.
  6817. - if it's a document of some kind, it will launch the document with its
  6818. default viewer application.
  6819. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  6820. @see revealToUser
  6821. */
  6822. bool startAsProcess (const String& parameters = String::empty) const;
  6823. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  6824. @see startAsProcess
  6825. */
  6826. void revealToUser() const;
  6827. /** A set of types of location that can be passed to the getSpecialLocation() method.
  6828. */
  6829. enum SpecialLocationType
  6830. {
  6831. /** The user's home folder. This is the same as using File ("~"). */
  6832. userHomeDirectory,
  6833. /** The user's default documents folder. On Windows, this might be the user's
  6834. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  6835. doesn't tend to have one of these, so it might just return their home folder.
  6836. */
  6837. userDocumentsDirectory,
  6838. /** The folder that contains the user's desktop objects. */
  6839. userDesktopDirectory,
  6840. /** The folder in which applications store their persistent user-specific settings.
  6841. On Windows, this might be "\Documents and Settings\username\Application Data".
  6842. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  6843. always create your own sub-folder to put them in, to avoid making a mess.
  6844. */
  6845. userApplicationDataDirectory,
  6846. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  6847. of the computer, rather than just the current user.
  6848. On the Mac it'll be "/Library", on Windows, it could be something like
  6849. "\Documents and Settings\All Users\Application Data".
  6850. Depending on the setup, this folder may be read-only.
  6851. */
  6852. commonApplicationDataDirectory,
  6853. /** The folder that should be used for temporary files.
  6854. Always delete them when you're finished, to keep the user's computer tidy!
  6855. */
  6856. tempDirectory,
  6857. /** Returns this application's executable file.
  6858. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  6859. host app.
  6860. On the mac this will return the unix binary, not the package folder - see
  6861. currentApplicationFile for that.
  6862. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  6863. file link, invokedExecutableFile will return the name of the link.
  6864. */
  6865. currentExecutableFile,
  6866. /** Returns this application's location.
  6867. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  6868. host app.
  6869. On the mac this will return the package folder (if it's in one), not the unix binary
  6870. that's inside it - compare with currentExecutableFile.
  6871. */
  6872. currentApplicationFile,
  6873. /** Returns the file that was invoked to launch this executable.
  6874. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  6875. will return the name of the link that was used, whereas currentExecutableFile will return
  6876. the actual location of the target executable.
  6877. */
  6878. invokedExecutableFile,
  6879. /** The directory in which applications normally get installed.
  6880. So on windows, this would be something like "c:\program files", on the
  6881. Mac "/Applications", or "/usr" on linux.
  6882. */
  6883. globalApplicationsDirectory,
  6884. /** The most likely place where a user might store their music files.
  6885. */
  6886. userMusicDirectory,
  6887. /** The most likely place where a user might store their movie files.
  6888. */
  6889. userMoviesDirectory,
  6890. };
  6891. /** Finds the location of a special type of file or directory, such as a home folder or
  6892. documents folder.
  6893. @see SpecialLocationType
  6894. */
  6895. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  6896. /** Returns a temporary file in the system's temp directory.
  6897. This will try to return the name of a non-existent temp file.
  6898. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  6899. */
  6900. static const File createTempFile (const String& fileNameEnding);
  6901. /** Returns the current working directory.
  6902. @see setAsCurrentWorkingDirectory
  6903. */
  6904. static const File getCurrentWorkingDirectory();
  6905. /** Sets the current working directory to be this file.
  6906. For this to work the file must point to a valid directory.
  6907. @returns true if the current directory has been changed.
  6908. @see getCurrentWorkingDirectory
  6909. */
  6910. bool setAsCurrentWorkingDirectory() const;
  6911. /** The system-specific file separator character.
  6912. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  6913. */
  6914. static const juce_wchar separator;
  6915. /** The system-specific file separator character, as a string.
  6916. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  6917. */
  6918. static const String separatorString;
  6919. /** Removes illegal characters from a filename.
  6920. This will return a copy of the given string after removing characters
  6921. that are not allowed in a legal filename, and possibly shortening the
  6922. string if it's too long.
  6923. Because this will remove slashes, don't use it on an absolute pathname.
  6924. @see createLegalPathName
  6925. */
  6926. static const String createLegalFileName (const String& fileNameToFix);
  6927. /** Removes illegal characters from a pathname.
  6928. Similar to createLegalFileName(), but this won't remove slashes, so can
  6929. be used on a complete pathname.
  6930. @see createLegalFileName
  6931. */
  6932. static const String createLegalPathName (const String& pathNameToFix);
  6933. /** Indicates whether filenames are case-sensitive on the current operating system.
  6934. */
  6935. static bool areFileNamesCaseSensitive();
  6936. /** Returns true if the string seems to be a fully-specified absolute path.
  6937. */
  6938. static bool isAbsolutePath (const String& path);
  6939. /** Creates a file that simply contains this string, without doing the sanity-checking
  6940. that the normal constructors do.
  6941. Best to avoid this unless you really know what you're doing.
  6942. */
  6943. static const File createFileWithoutCheckingPath (const String& path);
  6944. /** Adds a separator character to the end of a path if it doesn't already have one. */
  6945. static const String addTrailingSeparator (const String& path);
  6946. juce_UseDebuggingNewOperator
  6947. private:
  6948. String fullPath;
  6949. // internal way of contructing a file without checking the path
  6950. friend class DirectoryIterator;
  6951. File (const String&, int);
  6952. const String getPathUpToLastSlash() const;
  6953. void createDirectoryInternal (const String& fileName) const;
  6954. bool copyInternal (const File& dest) const;
  6955. bool moveInternal (const File& dest) const;
  6956. bool setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const;
  6957. void getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const;
  6958. bool setFileReadOnlyInternal (bool shouldBeReadOnly) const;
  6959. static const String parseAbsolutePath (const String& path);
  6960. static bool fileTypeMatches (int whatToLookFor, bool isDir, bool isHidden);
  6961. };
  6962. #endif // __JUCE_FILE_JUCEHEADER__
  6963. /*** End of inlined file: juce_File.h ***/
  6964. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  6965. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6966. will be the name of a pointer to each child element.
  6967. E.g. @code
  6968. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6969. forEachXmlChildElement (*myParentXml, child)
  6970. {
  6971. if (child->hasTagName ("FOO"))
  6972. doSomethingWithXmlElement (child);
  6973. }
  6974. @endcode
  6975. @see forEachXmlChildElementWithTagName
  6976. */
  6977. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  6978. \
  6979. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  6980. childElementVariableName != 0; \
  6981. childElementVariableName = childElementVariableName->getNextElement())
  6982. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  6983. which have a specified tag.
  6984. This does the same job as the forEachXmlChildElement macro, but only for those
  6985. elements that have a particular tag name.
  6986. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6987. will be the name of a pointer to each child element. The requiredTagName is the
  6988. tag name to match.
  6989. E.g. @code
  6990. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6991. forEachXmlChildElementWithTagName (*myParentXml, child, "MYTAG")
  6992. {
  6993. // the child object is now guaranteed to be a <MYTAG> element..
  6994. doSomethingWithMYTAGElement (child);
  6995. }
  6996. @endcode
  6997. @see forEachXmlChildElement
  6998. */
  6999. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  7000. \
  7001. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  7002. childElementVariableName != 0; \
  7003. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  7004. /** Used to build a tree of elements representing an XML document.
  7005. An XML document can be parsed into a tree of XmlElements, each of which
  7006. represents an XML tag structure, and which may itself contain other
  7007. nested elements.
  7008. An XmlElement can also be converted back into a text document, and has
  7009. lots of useful methods for manipulating its attributes and sub-elements,
  7010. so XmlElements can actually be used as a handy general-purpose data
  7011. structure.
  7012. Here's an example of parsing some elements: @code
  7013. // check we're looking at the right kind of document..
  7014. if (myElement->hasTagName ("ANIMALS"))
  7015. {
  7016. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  7017. forEachXmlChildElement (*myElement, e)
  7018. {
  7019. if (e->hasTagName ("GIRAFFE"))
  7020. {
  7021. // found a giraffe, so use some of its attributes..
  7022. String giraffeName = e->getStringAttribute ("name");
  7023. int giraffeAge = e->getIntAttribute ("age");
  7024. bool isFriendly = e->getBoolAttribute ("friendly");
  7025. }
  7026. }
  7027. }
  7028. @endcode
  7029. And here's an example of how to create an XML document from scratch: @code
  7030. // create an outer node called "ANIMALS"
  7031. XmlElement animalsList ("ANIMALS");
  7032. for (int i = 0; i < numAnimals; ++i)
  7033. {
  7034. // create an inner element..
  7035. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  7036. giraffe->setAttribute ("name", "nigel");
  7037. giraffe->setAttribute ("age", 10);
  7038. giraffe->setAttribute ("friendly", true);
  7039. // ..and add our new element to the parent node
  7040. animalsList.addChildElement (giraffe);
  7041. }
  7042. // now we can turn the whole thing into a text document..
  7043. String myXmlDoc = animalsList.createDocument (String::empty);
  7044. @endcode
  7045. @see XmlDocument
  7046. */
  7047. class JUCE_API XmlElement
  7048. {
  7049. public:
  7050. /** Creates an XmlElement with this tag name. */
  7051. explicit XmlElement (const String& tagName) throw();
  7052. /** Creates a (deep) copy of another element. */
  7053. XmlElement (const XmlElement& other);
  7054. /** Creates a (deep) copy of another element. */
  7055. XmlElement& operator= (const XmlElement& other);
  7056. /** Deleting an XmlElement will also delete all its child elements. */
  7057. ~XmlElement() throw();
  7058. /** Compares two XmlElements to see if they contain the same text and attiributes.
  7059. The elements are only considered equivalent if they contain the same attiributes
  7060. with the same values, and have the same sub-nodes.
  7061. @param other the other element to compare to
  7062. @param ignoreOrderOfAttributes if true, this means that two elements with the
  7063. same attributes in a different order will be
  7064. considered the same; if false, the attributes must
  7065. be in the same order as well
  7066. */
  7067. bool isEquivalentTo (const XmlElement* other,
  7068. bool ignoreOrderOfAttributes) const throw();
  7069. /** Returns an XML text document that represents this element.
  7070. The string returned can be parsed to recreate the same XmlElement that
  7071. was used to create it.
  7072. @param dtdToUse the DTD to add to the document
  7073. @param allOnOneLine if true, this means that the document will not contain any
  7074. linefeeds, so it'll be smaller but not very easy to read.
  7075. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  7076. document
  7077. @param encodingType the character encoding format string to put into the xml
  7078. header
  7079. @param lineWrapLength the line length that will be used before items get placed on
  7080. a new line. This isn't an absolute maximum length, it just
  7081. determines how lists of attributes get broken up
  7082. @see writeToStream, writeToFile
  7083. */
  7084. const String createDocument (const String& dtdToUse,
  7085. bool allOnOneLine = false,
  7086. bool includeXmlHeader = true,
  7087. const String& encodingType = "UTF-8",
  7088. int lineWrapLength = 60) const;
  7089. /** Writes the document to a stream as UTF-8.
  7090. @param output the stream to write to
  7091. @param dtdToUse the DTD to add to the document
  7092. @param allOnOneLine if true, this means that the document will not contain any
  7093. linefeeds, so it'll be smaller but not very easy to read.
  7094. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  7095. document
  7096. @param encodingType the character encoding format string to put into the xml
  7097. header
  7098. @param lineWrapLength the line length that will be used before items get placed on
  7099. a new line. This isn't an absolute maximum length, it just
  7100. determines how lists of attributes get broken up
  7101. @see writeToFile, createDocument
  7102. */
  7103. void writeToStream (OutputStream& output,
  7104. const String& dtdToUse,
  7105. bool allOnOneLine = false,
  7106. bool includeXmlHeader = true,
  7107. const String& encodingType = "UTF-8",
  7108. int lineWrapLength = 60) const;
  7109. /** Writes the element to a file as an XML document.
  7110. To improve safety in case something goes wrong while writing the file, this
  7111. will actually write the document to a new temporary file in the same
  7112. directory as the destination file, and if this succeeds, it will rename this
  7113. new file as the destination file (overwriting any existing file that was there).
  7114. @param destinationFile the file to write to. If this already exists, it will be
  7115. overwritten.
  7116. @param dtdToUse the DTD to add to the document
  7117. @param encodingType the character encoding format string to put into the xml
  7118. header
  7119. @param lineWrapLength the line length that will be used before items get placed on
  7120. a new line. This isn't an absolute maximum length, it just
  7121. determines how lists of attributes get broken up
  7122. @returns true if the file is written successfully; false if something goes wrong
  7123. in the process
  7124. @see createDocument
  7125. */
  7126. bool writeToFile (const File& destinationFile,
  7127. const String& dtdToUse,
  7128. const String& encodingType = "UTF-8",
  7129. int lineWrapLength = 60) const;
  7130. /** Returns this element's tag type name.
  7131. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  7132. "MOOSE".
  7133. @see hasTagName
  7134. */
  7135. inline const String& getTagName() const throw() { return tagName; }
  7136. /** Tests whether this element has a particular tag name.
  7137. @param possibleTagName the tag name you're comparing it with
  7138. @see getTagName
  7139. */
  7140. bool hasTagName (const String& possibleTagName) const throw();
  7141. /** Returns the number of XML attributes this element contains.
  7142. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  7143. return 2.
  7144. */
  7145. int getNumAttributes() const throw();
  7146. /** Returns the name of one of the elements attributes.
  7147. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7148. getAttributeName(1) would return "antlers".
  7149. @see getAttributeValue, getStringAttribute
  7150. */
  7151. const String& getAttributeName (int attributeIndex) const throw();
  7152. /** Returns the value of one of the elements attributes.
  7153. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7154. getAttributeName(1) would return "2".
  7155. @see getAttributeName, getStringAttribute
  7156. */
  7157. const String& getAttributeValue (int attributeIndex) const throw();
  7158. // Attribute-handling methods..
  7159. /** Checks whether the element contains an attribute with a certain name. */
  7160. bool hasAttribute (const String& attributeName) const throw();
  7161. /** Returns the value of a named attribute.
  7162. @param attributeName the name of the attribute to look up
  7163. */
  7164. const String& getStringAttribute (const String& attributeName) const throw();
  7165. /** Returns the value of a named attribute.
  7166. @param attributeName the name of the attribute to look up
  7167. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7168. with this name
  7169. */
  7170. const String getStringAttribute (const String& attributeName,
  7171. const String& defaultReturnValue) const;
  7172. /** Compares the value of a named attribute with a value passed-in.
  7173. @param attributeName the name of the attribute to look up
  7174. @param stringToCompareAgainst the value to compare it with
  7175. @param ignoreCase whether the comparison should be case-insensitive
  7176. @returns true if the value of the attribute is the same as the string passed-in;
  7177. false if it's different (or if no such attribute exists)
  7178. */
  7179. bool compareAttribute (const String& attributeName,
  7180. const String& stringToCompareAgainst,
  7181. bool ignoreCase = false) const throw();
  7182. /** Returns the value of a named attribute as an integer.
  7183. This will try to find the attribute and convert it to an integer (using
  7184. the String::getIntValue() method).
  7185. @param attributeName the name of the attribute to look up
  7186. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7187. with this name
  7188. @see setAttribute
  7189. */
  7190. int getIntAttribute (const String& attributeName,
  7191. int defaultReturnValue = 0) const;
  7192. /** Returns the value of a named attribute as floating-point.
  7193. This will try to find the attribute and convert it to an integer (using
  7194. the String::getDoubleValue() method).
  7195. @param attributeName the name of the attribute to look up
  7196. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7197. with this name
  7198. @see setAttribute
  7199. */
  7200. double getDoubleAttribute (const String& attributeName,
  7201. double defaultReturnValue = 0.0) const;
  7202. /** Returns the value of a named attribute as a boolean.
  7203. This will try to find the attribute and interpret it as a boolean. To do this,
  7204. it'll return true if the value is "1", "true", "y", etc, or false for other
  7205. values.
  7206. @param attributeName the name of the attribute to look up
  7207. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7208. with this name
  7209. */
  7210. bool getBoolAttribute (const String& attributeName,
  7211. bool defaultReturnValue = false) const;
  7212. /** Adds a named attribute to the element.
  7213. If the element already contains an attribute with this name, it's value will
  7214. be updated to the new value. If there's no such attribute yet, a new one will
  7215. be added.
  7216. Note that there are other setAttribute() methods that take integers,
  7217. doubles, etc. to make it easy to store numbers.
  7218. @param attributeName the name of the attribute to set
  7219. @param newValue the value to set it to
  7220. @see removeAttribute
  7221. */
  7222. void setAttribute (const String& attributeName,
  7223. const String& newValue);
  7224. /** Adds a named attribute to the element, setting it to an integer value.
  7225. If the element already contains an attribute with this name, it's value will
  7226. be updated to the new value. If there's no such attribute yet, a new one will
  7227. be added.
  7228. Note that there are other setAttribute() methods that take integers,
  7229. doubles, etc. to make it easy to store numbers.
  7230. @param attributeName the name of the attribute to set
  7231. @param newValue the value to set it to
  7232. */
  7233. void setAttribute (const String& attributeName,
  7234. int newValue);
  7235. /** Adds a named attribute to the element, setting it to a floating-point value.
  7236. If the element already contains an attribute with this name, it's value will
  7237. be updated to the new value. If there's no such attribute yet, a new one will
  7238. be added.
  7239. Note that there are other setAttribute() methods that take integers,
  7240. doubles, etc. to make it easy to store numbers.
  7241. @param attributeName the name of the attribute to set
  7242. @param newValue the value to set it to
  7243. */
  7244. void setAttribute (const String& attributeName,
  7245. double newValue);
  7246. /** Removes a named attribute from the element.
  7247. @param attributeName the name of the attribute to remove
  7248. @see removeAllAttributes
  7249. */
  7250. void removeAttribute (const String& attributeName) throw();
  7251. /** Removes all attributes from this element.
  7252. */
  7253. void removeAllAttributes() throw();
  7254. // Child element methods..
  7255. /** Returns the first of this element's sub-elements.
  7256. see getNextElement() for an example of how to iterate the sub-elements.
  7257. @see forEachXmlChildElement
  7258. */
  7259. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  7260. /** Returns the next of this element's siblings.
  7261. This can be used for iterating an element's sub-elements, e.g.
  7262. @code
  7263. XmlElement* child = myXmlDocument->getFirstChildElement();
  7264. while (child != 0)
  7265. {
  7266. ...do stuff with this child..
  7267. child = child->getNextElement();
  7268. }
  7269. @endcode
  7270. Note that when iterating the child elements, some of them might be
  7271. text elements as well as XML tags - use isTextElement() to work this
  7272. out.
  7273. Also, it's much easier and neater to use this method indirectly via the
  7274. forEachXmlChildElement macro.
  7275. @returns the sibling element that follows this one, or zero if this is the last
  7276. element in its parent
  7277. @see getNextElement, isTextElement, forEachXmlChildElement
  7278. */
  7279. inline XmlElement* getNextElement() const throw() { return nextElement; }
  7280. /** Returns the next of this element's siblings which has the specified tag
  7281. name.
  7282. This is like getNextElement(), but will scan through the list until it
  7283. finds an element with the given tag name.
  7284. @see getNextElement, forEachXmlChildElementWithTagName
  7285. */
  7286. XmlElement* getNextElementWithTagName (const String& requiredTagName) const;
  7287. /** Returns the number of sub-elements in this element.
  7288. @see getChildElement
  7289. */
  7290. int getNumChildElements() const throw();
  7291. /** Returns the sub-element at a certain index.
  7292. It's not very efficient to iterate the sub-elements by index - see
  7293. getNextElement() for an example of how best to iterate.
  7294. @returns the n'th child of this element, or 0 if the index is out-of-range
  7295. @see getNextElement, isTextElement, getChildByName
  7296. */
  7297. XmlElement* getChildElement (int index) const throw();
  7298. /** Returns the first sub-element with a given tag-name.
  7299. @param tagNameToLookFor the tag name of the element you want to find
  7300. @returns the first element with this tag name, or 0 if none is found
  7301. @see getNextElement, isTextElement, getChildElement
  7302. */
  7303. XmlElement* getChildByName (const String& tagNameToLookFor) const throw();
  7304. /** Appends an element to this element's list of children.
  7305. Child elements are deleted automatically when their parent is deleted, so
  7306. make sure the object that you pass in will not be deleted by anything else,
  7307. and make sure it's not already the child of another element.
  7308. @see getFirstChildElement, getNextElement, getNumChildElements,
  7309. getChildElement, removeChildElement
  7310. */
  7311. void addChildElement (XmlElement* const newChildElement) throw();
  7312. /** Inserts an element into this element's list of children.
  7313. Child elements are deleted automatically when their parent is deleted, so
  7314. make sure the object that you pass in will not be deleted by anything else,
  7315. and make sure it's not already the child of another element.
  7316. @param newChildNode the element to add
  7317. @param indexToInsertAt the index at which to insert the new element - if this is
  7318. below zero, it will be added to the end of the list
  7319. @see addChildElement, insertChildElement
  7320. */
  7321. void insertChildElement (XmlElement* newChildNode,
  7322. int indexToInsertAt) throw();
  7323. /** Creates a new element with the given name and returns it, after adding it
  7324. as a child element.
  7325. This is a handy method that means that instead of writing this:
  7326. @code
  7327. XmlElement* newElement = new XmlElement ("foobar");
  7328. myParentElement->addChildElement (newElement);
  7329. @endcode
  7330. ..you could just write this:
  7331. @code
  7332. XmlElement* newElement = myParentElement->createNewChildElement ("foobar");
  7333. @endcode
  7334. */
  7335. XmlElement* createNewChildElement (const String& tagName);
  7336. /** Replaces one of this element's children with another node.
  7337. If the current element passed-in isn't actually a child of this element,
  7338. this will return false and the new one won't be added. Otherwise, the
  7339. existing element will be deleted, replaced with the new one, and it
  7340. will return true.
  7341. */
  7342. bool replaceChildElement (XmlElement* currentChildElement,
  7343. XmlElement* newChildNode) throw();
  7344. /** Removes a child element.
  7345. @param childToRemove the child to look for and remove
  7346. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  7347. just remove it
  7348. */
  7349. void removeChildElement (XmlElement* childToRemove,
  7350. bool shouldDeleteTheChild) throw();
  7351. /** Deletes all the child elements in the element.
  7352. @see removeChildElement, deleteAllChildElementsWithTagName
  7353. */
  7354. void deleteAllChildElements() throw();
  7355. /** Deletes all the child elements with a given tag name.
  7356. @see removeChildElement
  7357. */
  7358. void deleteAllChildElementsWithTagName (const String& tagName) throw();
  7359. /** Returns true if the given element is a child of this one. */
  7360. bool containsChildElement (const XmlElement* const possibleChild) const throw();
  7361. /** Recursively searches all sub-elements to find one that contains the specified
  7362. child element.
  7363. */
  7364. XmlElement* findParentElementOf (const XmlElement* elementToLookFor) throw();
  7365. /** Sorts the child elements using a comparator.
  7366. This will use a comparator object to sort the elements into order. The object
  7367. passed must have a method of the form:
  7368. @code
  7369. int compareElements (const XmlElement* first, const XmlElement* second);
  7370. @endcode
  7371. ..and this method must return:
  7372. - a value of < 0 if the first comes before the second
  7373. - a value of 0 if the two objects are equivalent
  7374. - a value of > 0 if the second comes before the first
  7375. To improve performance, the compareElements() method can be declared as static or const.
  7376. @param comparator the comparator to use for comparing elements.
  7377. @param retainOrderOfEquivalentItems if this is true, then items
  7378. which the comparator says are equivalent will be
  7379. kept in the order in which they currently appear
  7380. in the array. This is slower to perform, but may
  7381. be important in some cases. If it's false, a faster
  7382. algorithm is used, but equivalent elements may be
  7383. rearranged.
  7384. */
  7385. template <class ElementComparator>
  7386. void sortChildElements (ElementComparator& comparator,
  7387. bool retainOrderOfEquivalentItems = false)
  7388. {
  7389. const int num = getNumChildElements();
  7390. if (num > 1)
  7391. {
  7392. HeapBlock <XmlElement*> elems (num);
  7393. getChildElementsAsArray (elems);
  7394. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  7395. reorderChildElements (elems, num);
  7396. }
  7397. }
  7398. /** Returns true if this element is a section of text.
  7399. Elements can either be an XML tag element or a secton of text, so this
  7400. is used to find out what kind of element this one is.
  7401. @see getAllText, addTextElement, deleteAllTextElements
  7402. */
  7403. bool isTextElement() const throw();
  7404. /** Returns the text for a text element.
  7405. Note that if you have an element like this:
  7406. @code<xyz>hello</xyz>@endcode
  7407. then calling getText on the "xyz" element won't return "hello", because that is
  7408. actually stored in a special text sub-element inside the xyz element. To get the
  7409. "hello" string, you could either call getText on the (unnamed) sub-element, or
  7410. use getAllSubText() to do this automatically.
  7411. @see isTextElement, getAllSubText, getChildElementAllSubText
  7412. */
  7413. const String& getText() const throw();
  7414. /** Sets the text in a text element.
  7415. Note that this is only a valid call if this element is a text element. If it's
  7416. not, then no action will be performed.
  7417. */
  7418. void setText (const String& newText);
  7419. /** Returns all the text from this element's child nodes.
  7420. This iterates all the child elements and when it finds text elements,
  7421. it concatenates their text into a big string which it returns.
  7422. E.g. @code<xyz> hello <x></x> there </xyz>@endcode
  7423. if you called getAllSubText on the "xyz" element, it'd return "hello there".
  7424. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  7425. */
  7426. const String getAllSubText() const;
  7427. /** Returns all the sub-text of a named child element.
  7428. If there is a child element with the given tag name, this will return
  7429. all of its sub-text (by calling getAllSubText() on it). If there is
  7430. no such child element, this will return the default string passed-in.
  7431. @see getAllSubText
  7432. */
  7433. const String getChildElementAllSubText (const String& childTagName,
  7434. const String& defaultReturnValue) const;
  7435. /** Appends a section of text to this element.
  7436. @see isTextElement, getText, getAllSubText
  7437. */
  7438. void addTextElement (const String& text);
  7439. /** Removes all the text elements from this element.
  7440. @see isTextElement, getText, getAllSubText, addTextElement
  7441. */
  7442. void deleteAllTextElements() throw();
  7443. /** Creates a text element that can be added to a parent element.
  7444. */
  7445. static XmlElement* createTextElement (const String& text);
  7446. juce_UseDebuggingNewOperator
  7447. private:
  7448. friend class XmlDocument;
  7449. String tagName;
  7450. XmlElement* firstChildElement;
  7451. XmlElement* nextElement;
  7452. struct XmlAttributeNode
  7453. {
  7454. XmlAttributeNode (const XmlAttributeNode& other) throw();
  7455. XmlAttributeNode (const String& name, const String& value) throw();
  7456. String name, value;
  7457. XmlAttributeNode* next;
  7458. private:
  7459. XmlAttributeNode& operator= (const XmlAttributeNode&);
  7460. };
  7461. XmlAttributeNode* attributes;
  7462. XmlElement (int) throw();
  7463. void copyChildrenAndAttributesFrom (const XmlElement& other);
  7464. void writeElementAsText (OutputStream& out, int indentationLevel, int lineWrapLength) const;
  7465. void getChildElementsAsArray (XmlElement**) const throw();
  7466. void reorderChildElements (XmlElement** const, const int) throw();
  7467. };
  7468. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  7469. /*** End of inlined file: juce_XmlElement.h ***/
  7470. /**
  7471. A set of named property values, which can be strings, integers, floating point, etc.
  7472. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  7473. to load and save types other than strings.
  7474. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  7475. messages and saves/loads the list from a file.
  7476. */
  7477. class JUCE_API PropertySet
  7478. {
  7479. public:
  7480. /** Creates an empty PropertySet.
  7481. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  7482. case-insensitive way
  7483. */
  7484. PropertySet (const bool ignoreCaseOfKeyNames = false) throw();
  7485. /** Creates a copy of another PropertySet.
  7486. */
  7487. PropertySet (const PropertySet& other) throw();
  7488. /** Copies another PropertySet over this one.
  7489. */
  7490. PropertySet& operator= (const PropertySet& other) throw();
  7491. /** Destructor. */
  7492. virtual ~PropertySet();
  7493. /** Returns one of the properties as a string.
  7494. If the value isn't found in this set, then this will look for it in a fallback
  7495. property set (if you've specified one with the setFallbackPropertySet() method),
  7496. and if it can't find one there, it'll return the default value passed-in.
  7497. @param keyName the name of the property to retrieve
  7498. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7499. */
  7500. const String getValue (const String& keyName,
  7501. const String& defaultReturnValue = String::empty) const throw();
  7502. /** Returns one of the properties as an integer.
  7503. If the value isn't found in this set, then this will look for it in a fallback
  7504. property set (if you've specified one with the setFallbackPropertySet() method),
  7505. and if it can't find one there, it'll return the default value passed-in.
  7506. @param keyName the name of the property to retrieve
  7507. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7508. */
  7509. int getIntValue (const String& keyName,
  7510. const int defaultReturnValue = 0) const throw();
  7511. /** Returns one of the properties as an double.
  7512. If the value isn't found in this set, then this will look for it in a fallback
  7513. property set (if you've specified one with the setFallbackPropertySet() method),
  7514. and if it can't find one there, it'll return the default value passed-in.
  7515. @param keyName the name of the property to retrieve
  7516. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7517. */
  7518. double getDoubleValue (const String& keyName,
  7519. const double defaultReturnValue = 0.0) const throw();
  7520. /** Returns one of the properties as an boolean.
  7521. The result will be true if the string found for this key name can be parsed as a non-zero
  7522. integer.
  7523. If the value isn't found in this set, then this will look for it in a fallback
  7524. property set (if you've specified one with the setFallbackPropertySet() method),
  7525. and if it can't find one there, it'll return the default value passed-in.
  7526. @param keyName the name of the property to retrieve
  7527. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7528. */
  7529. bool getBoolValue (const String& keyName,
  7530. const bool defaultReturnValue = false) const throw();
  7531. /** Returns one of the properties as an XML element.
  7532. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  7533. key isn't found, or if the entry contains an string that isn't valid XML.
  7534. If the value isn't found in this set, then this will look for it in a fallback
  7535. property set (if you've specified one with the setFallbackPropertySet() method),
  7536. and if it can't find one there, it'll return the default value passed-in.
  7537. @param keyName the name of the property to retrieve
  7538. */
  7539. XmlElement* getXmlValue (const String& keyName) const;
  7540. /** Sets a named property as a string.
  7541. @param keyName the name of the property to set. (This mustn't be an empty string)
  7542. @param value the new value to set it to
  7543. */
  7544. void setValue (const String& keyName, const String& value) throw();
  7545. /** Sets a named property to an integer.
  7546. @param keyName the name of the property to set. (This mustn't be an empty string)
  7547. @param value the new value to set it to
  7548. */
  7549. void setValue (const String& keyName, const int value) throw();
  7550. /** Sets a named property to a double.
  7551. @param keyName the name of the property to set. (This mustn't be an empty string)
  7552. @param value the new value to set it to
  7553. */
  7554. void setValue (const String& keyName, const double value) throw();
  7555. /** Sets a named property to a boolean.
  7556. @param keyName the name of the property to set. (This mustn't be an empty string)
  7557. @param value the new value to set it to
  7558. */
  7559. void setValue (const String& keyName, const bool value) throw();
  7560. /** Sets a named property to an XML element.
  7561. @param keyName the name of the property to set. (This mustn't be an empty string)
  7562. @param xml the new element to set it to. If this is zero, the value will be set to
  7563. an empty string
  7564. @see getXmlValue
  7565. */
  7566. void setValue (const String& keyName, const XmlElement* const xml);
  7567. /** Deletes a property.
  7568. @param keyName the name of the property to delete. (This mustn't be an empty string)
  7569. */
  7570. void removeValue (const String& keyName) throw();
  7571. /** Returns true if the properies include the given key. */
  7572. bool containsKey (const String& keyName) const throw();
  7573. /** Removes all values. */
  7574. void clear();
  7575. /** Returns the keys/value pair array containing all the properties. */
  7576. StringPairArray& getAllProperties() throw() { return properties; }
  7577. /** Returns the lock used when reading or writing to this set */
  7578. const CriticalSection& getLock() const throw() { return lock; }
  7579. /** Returns an XML element which encapsulates all the items in this property set.
  7580. The string parameter is the tag name that should be used for the node.
  7581. @see restoreFromXml
  7582. */
  7583. XmlElement* createXml (const String& nodeName) const throw();
  7584. /** Reloads a set of properties that were previously stored as XML.
  7585. The node passed in must have been created by the createXml() method.
  7586. @see createXml
  7587. */
  7588. void restoreFromXml (const XmlElement& xml) throw();
  7589. /** Sets up a second PopertySet that will be used to look up any values that aren't
  7590. set in this one.
  7591. If you set this up to be a pointer to a second property set, then whenever one
  7592. of the getValue() methods fails to find an entry in this set, it will look up that
  7593. value in the fallback set, and if it finds it, it will return that.
  7594. Make sure that you don't delete the fallback set while it's still being used by
  7595. another set! To remove the fallback set, just call this method with a null pointer.
  7596. @see getFallbackPropertySet
  7597. */
  7598. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  7599. /** Returns the fallback property set.
  7600. @see setFallbackPropertySet
  7601. */
  7602. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  7603. juce_UseDebuggingNewOperator
  7604. protected:
  7605. /** Subclasses can override this to be told when one of the properies has been changed.
  7606. */
  7607. virtual void propertyChanged();
  7608. private:
  7609. StringPairArray properties;
  7610. PropertySet* fallbackProperties;
  7611. CriticalSection lock;
  7612. bool ignoreCaseOfKeys;
  7613. };
  7614. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  7615. /*** End of inlined file: juce_PropertySet.h ***/
  7616. #endif
  7617. #ifndef __JUCE_RANGE_JUCEHEADER__
  7618. /*** Start of inlined file: juce_Range.h ***/
  7619. #ifndef __JUCE_RANGE_JUCEHEADER__
  7620. #define __JUCE_RANGE_JUCEHEADER__
  7621. /** A general-purpose range object, that simply represents any linear range with
  7622. a start and end point.
  7623. The templated parameter is expected to be a primitive integer or floating point
  7624. type, though class types could also be used if they behave in a number-like way.
  7625. */
  7626. template <typename ValueType>
  7627. class Range
  7628. {
  7629. public:
  7630. /** Constructs an empty range. */
  7631. Range() throw()
  7632. : start (ValueType()), end (ValueType())
  7633. {
  7634. }
  7635. /** Constructs a range with given start and end values. */
  7636. Range (const ValueType start_, const ValueType end_) throw()
  7637. : start (start_), end (jmax (start_, end_))
  7638. {
  7639. }
  7640. /** Constructs a copy of another range. */
  7641. Range (const Range& other) throw()
  7642. : start (other.start), end (other.end)
  7643. {
  7644. }
  7645. /** Copies another range object. */
  7646. Range& operator= (const Range& other) throw()
  7647. {
  7648. start = other.start;
  7649. end = other.end;
  7650. return *this;
  7651. }
  7652. /** Destructor. */
  7653. ~Range() throw()
  7654. {
  7655. }
  7656. /** Returns the range that lies between two positions (in either order). */
  7657. static const Range between (const ValueType position1, const ValueType position2) throw()
  7658. {
  7659. return (position1 < position2) ? Range (position1, position2)
  7660. : Range (position2, position1);
  7661. }
  7662. /** Returns a range with the specified start position and a length of zero. */
  7663. static const Range emptyRange (const ValueType start) throw()
  7664. {
  7665. return Range (start, start);
  7666. }
  7667. /** Returns the start of the range. */
  7668. inline ValueType getStart() const throw() { return start; }
  7669. /** Returns the length of the range. */
  7670. inline ValueType getLength() const throw() { return end - start; }
  7671. /** Returns the end of the range. */
  7672. inline ValueType getEnd() const throw() { return end; }
  7673. /** Returns true if the range has a length of zero. */
  7674. inline bool isEmpty() const throw() { return start == end; }
  7675. /** Changes the start position of the range, leaving the end position unchanged.
  7676. If the new start position is higher than the current end of the range, the end point
  7677. will be pushed along to equal it, leaving an empty range at the new position.
  7678. */
  7679. void setStart (const ValueType newStart) throw()
  7680. {
  7681. start = newStart;
  7682. if (end < newStart)
  7683. end = newStart;
  7684. }
  7685. /** Returns a range with the same end as this one, but a different start.
  7686. If the new start position is higher than the current end of the range, the end point
  7687. will be pushed along to equal it, returning an empty range at the new position.
  7688. */
  7689. const Range withStart (const ValueType newStart) const throw()
  7690. {
  7691. return Range (newStart, jmax (newStart, end));
  7692. }
  7693. /** Returns a range with the same length as this one, but moved to have the given start position. */
  7694. const Range movedToStartAt (const ValueType newStart) const throw()
  7695. {
  7696. return Range (newStart, newStart + getLength());
  7697. }
  7698. /** Changes the end position of the range, leaving the start unchanged.
  7699. If the new end position is below the current start of the range, the start point
  7700. will be pushed back to equal the new end point.
  7701. */
  7702. void setEnd (const ValueType newEnd) throw()
  7703. {
  7704. end = newEnd;
  7705. if (newEnd < start)
  7706. start = newEnd;
  7707. }
  7708. /** Returns a range with the same start position as this one, but a different end.
  7709. If the new end position is below the current start of the range, the start point
  7710. will be pushed back to equal the new end point.
  7711. */
  7712. const Range withEnd (const ValueType newEnd) const throw()
  7713. {
  7714. return Range (jmin (start, newEnd), newEnd);
  7715. }
  7716. /** Returns a range with the same length as this one, but moved to have the given start position. */
  7717. const Range movedToEndAt (const ValueType newEnd) const throw()
  7718. {
  7719. return Range (newEnd - getLength(), newEnd);
  7720. }
  7721. /** Changes the length of the range.
  7722. Lengths less than zero are treated as zero.
  7723. */
  7724. void setLength (const ValueType newLength) throw()
  7725. {
  7726. end = start + jmax (ValueType(), newLength);
  7727. }
  7728. /** Returns a range with the same start as this one, but a different length.
  7729. Lengths less than zero are treated as zero.
  7730. */
  7731. const Range withLength (const ValueType newLength) const throw()
  7732. {
  7733. return Range (start, start + newLength);
  7734. }
  7735. /** Adds an amount to the start and end of the range. */
  7736. inline const Range& operator+= (const ValueType amountToAdd) throw()
  7737. {
  7738. start += amountToAdd;
  7739. end += amountToAdd;
  7740. return *this;
  7741. }
  7742. /** Subtracts an amount from the start and end of the range. */
  7743. inline const Range& operator-= (const ValueType amountToSubtract) throw()
  7744. {
  7745. start -= amountToSubtract;
  7746. end -= amountToSubtract;
  7747. return *this;
  7748. }
  7749. /** Returns a range that is equal to this one with an amount added to its
  7750. start and end.
  7751. */
  7752. const Range operator+ (const ValueType amountToAdd) const throw()
  7753. {
  7754. return Range (start + amountToAdd, end + amountToAdd);
  7755. }
  7756. /** Returns a range that is equal to this one with the specified amount
  7757. subtracted from its start and end. */
  7758. const Range operator- (const ValueType amountToSubtract) const throw()
  7759. {
  7760. return Range (start - amountToSubtract, end - amountToSubtract);
  7761. }
  7762. bool operator== (const Range& other) const throw() { return start == other.start && end == other.end; }
  7763. bool operator!= (const Range& other) const throw() { return start != other.start || end != other.end; }
  7764. /** Returns true if the given position lies inside this range. */
  7765. bool contains (const ValueType position) const throw()
  7766. {
  7767. return start <= position && position < end;
  7768. }
  7769. /** Returns the nearest value to the one supplied, which lies within the range. */
  7770. ValueType clipValue (const ValueType value) const throw()
  7771. {
  7772. return jlimit (start, end, value);
  7773. }
  7774. /** Returns true if the given range lies entirely inside this range. */
  7775. bool contains (const Range& other) const throw()
  7776. {
  7777. return start <= other.start && end >= other.end;
  7778. }
  7779. /** Returns true if the given range intersects this one. */
  7780. bool intersects (const Range& other) const throw()
  7781. {
  7782. return other.start < end && start < other.end;
  7783. }
  7784. /** Returns the range that is the intersection of the two ranges, or an empty range
  7785. with an undefined start position if they don't overlap. */
  7786. const Range getIntersectionWith (const Range& other) const throw()
  7787. {
  7788. return Range (jmax (start, other.start),
  7789. jmin (end, other.end));
  7790. }
  7791. /** Returns the smallest range that contains both this one and the other one. */
  7792. const Range getUnionWith (const Range& other) const throw()
  7793. {
  7794. return Range (jmin (start, other.start),
  7795. jmax (end, other.end));
  7796. }
  7797. /** Returns a given range, after moving it forwards or backwards to fit it
  7798. within this range.
  7799. If the supplied range has a greater length than this one, the return value
  7800. will be this range.
  7801. Otherwise, if the supplied range is smaller than this one, the return value
  7802. will be the new range, shifted forwards or backwards so that it doesn't extend
  7803. beyond this one, but keeping its original length.
  7804. */
  7805. const Range constrainRange (const Range& rangeToConstrain) const throw()
  7806. {
  7807. const ValueType otherLen = rangeToConstrain.getLength();
  7808. return getLength() <= otherLen
  7809. ? *this
  7810. : rangeToConstrain.movedToStartAt (jlimit (start, end - otherLen, rangeToConstrain.getStart()));
  7811. }
  7812. juce_UseDebuggingNewOperator
  7813. private:
  7814. ValueType start, end;
  7815. };
  7816. #endif // __JUCE_RANGE_JUCEHEADER__
  7817. /*** End of inlined file: juce_Range.h ***/
  7818. #endif
  7819. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7820. /*** Start of inlined file: juce_ReferenceCountedArray.h ***/
  7821. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7822. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7823. /**
  7824. Holds a list of objects derived from ReferenceCountedObject.
  7825. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  7826. and takes care of incrementing and decrementing their ref counts when they
  7827. are added and removed from the array.
  7828. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7829. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7830. @see Array, OwnedArray, StringArray
  7831. */
  7832. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7833. class ReferenceCountedArray
  7834. {
  7835. public:
  7836. /** Creates an empty array.
  7837. @see ReferenceCountedObject, Array, OwnedArray
  7838. */
  7839. ReferenceCountedArray() throw()
  7840. : numUsed (0)
  7841. {
  7842. }
  7843. /** Creates a copy of another array */
  7844. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7845. {
  7846. const ScopedLockType lock (other.getLock());
  7847. numUsed = other.numUsed;
  7848. data.setAllocatedSize (numUsed);
  7849. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  7850. for (int i = numUsed; --i >= 0;)
  7851. if (data.elements[i] != 0)
  7852. data.elements[i]->incReferenceCount();
  7853. }
  7854. /** Copies another array into this one.
  7855. Any existing objects in this array will first be released.
  7856. */
  7857. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7858. {
  7859. if (this != &other)
  7860. {
  7861. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse> otherCopy (other);
  7862. swapWithArray (otherCopy);
  7863. }
  7864. return *this;
  7865. }
  7866. /** Destructor.
  7867. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  7868. */
  7869. ~ReferenceCountedArray()
  7870. {
  7871. clear();
  7872. }
  7873. /** Removes all objects from the array.
  7874. Any objects in the array that are not referenced from elsewhere will be deleted.
  7875. */
  7876. void clear()
  7877. {
  7878. const ScopedLockType lock (getLock());
  7879. while (numUsed > 0)
  7880. if (data.elements [--numUsed] != 0)
  7881. data.elements [numUsed]->decReferenceCount();
  7882. jassert (numUsed == 0);
  7883. data.setAllocatedSize (0);
  7884. }
  7885. /** Returns the current number of objects in the array. */
  7886. inline int size() const throw()
  7887. {
  7888. return numUsed;
  7889. }
  7890. /** Returns a pointer to the object at this index in the array.
  7891. If the index is out-of-range, this will return a null pointer, (and
  7892. it could be null anyway, because it's ok for the array to hold null
  7893. pointers as well as objects).
  7894. @see getUnchecked
  7895. */
  7896. inline const ReferenceCountedObjectPtr<ObjectClass> operator[] (const int index) const throw()
  7897. {
  7898. const ScopedLockType lock (getLock());
  7899. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  7900. : static_cast <ObjectClass*> (0);
  7901. }
  7902. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7903. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7904. it can be used when you're sure the index if always going to be legal.
  7905. */
  7906. inline const ReferenceCountedObjectPtr<ObjectClass> getUnchecked (const int index) const throw()
  7907. {
  7908. const ScopedLockType lock (getLock());
  7909. jassert (((unsigned int) index) < (unsigned int) numUsed);
  7910. return data.elements [index];
  7911. }
  7912. /** Returns a pointer to the first object in the array.
  7913. This will return a null pointer if the array's empty.
  7914. @see getLast
  7915. */
  7916. inline const ReferenceCountedObjectPtr<ObjectClass> getFirst() const throw()
  7917. {
  7918. const ScopedLockType lock (getLock());
  7919. return numUsed > 0 ? data.elements [0]
  7920. : static_cast <ObjectClass*> (0);
  7921. }
  7922. /** Returns a pointer to the last object in the array.
  7923. This will return a null pointer if the array's empty.
  7924. @see getFirst
  7925. */
  7926. inline const ReferenceCountedObjectPtr<ObjectClass> getLast() const throw()
  7927. {
  7928. const ScopedLockType lock (getLock());
  7929. return numUsed > 0 ? data.elements [numUsed - 1]
  7930. : static_cast <ObjectClass*> (0);
  7931. }
  7932. /** Finds the index of the first occurrence of an object in the array.
  7933. @param objectToLookFor the object to look for
  7934. @returns the index at which the object was found, or -1 if it's not found
  7935. */
  7936. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7937. {
  7938. const ScopedLockType lock (getLock());
  7939. ObjectClass** e = data.elements.getData();
  7940. ObjectClass** const end = e + numUsed;
  7941. while (e != end)
  7942. {
  7943. if (objectToLookFor == *e)
  7944. return static_cast <int> (e - data.elements.getData());
  7945. ++e;
  7946. }
  7947. return -1;
  7948. }
  7949. /** Returns true if the array contains a specified object.
  7950. @param objectToLookFor the object to look for
  7951. @returns true if the object is in the array
  7952. */
  7953. bool contains (const ObjectClass* const objectToLookFor) const throw()
  7954. {
  7955. const ScopedLockType lock (getLock());
  7956. ObjectClass** e = data.elements.getData();
  7957. ObjectClass** const end = e + numUsed;
  7958. while (e != end)
  7959. {
  7960. if (objectToLookFor == *e)
  7961. return true;
  7962. ++e;
  7963. }
  7964. return false;
  7965. }
  7966. /** Appends a new object to the end of the array.
  7967. This will increase the new object's reference count.
  7968. @param newObject the new object to add to the array
  7969. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  7970. */
  7971. void add (ObjectClass* const newObject) throw()
  7972. {
  7973. const ScopedLockType lock (getLock());
  7974. data.ensureAllocatedSize (numUsed + 1);
  7975. data.elements [numUsed++] = newObject;
  7976. if (newObject != 0)
  7977. newObject->incReferenceCount();
  7978. }
  7979. /** Inserts a new object into the array at the given index.
  7980. If the index is less than 0 or greater than the size of the array, the
  7981. element will be added to the end of the array.
  7982. Otherwise, it will be inserted into the array, moving all the later elements
  7983. along to make room.
  7984. This will increase the new object's reference count.
  7985. @param indexToInsertAt the index at which the new element should be inserted
  7986. @param newObject the new object to add to the array
  7987. @see add, addSorted, addIfNotAlreadyThere, set
  7988. */
  7989. void insert (int indexToInsertAt,
  7990. ObjectClass* const newObject) throw()
  7991. {
  7992. if (indexToInsertAt >= 0)
  7993. {
  7994. const ScopedLockType lock (getLock());
  7995. if (indexToInsertAt > numUsed)
  7996. indexToInsertAt = numUsed;
  7997. data.ensureAllocatedSize (numUsed + 1);
  7998. ObjectClass** const e = data.elements + indexToInsertAt;
  7999. const int numToMove = numUsed - indexToInsertAt;
  8000. if (numToMove > 0)
  8001. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  8002. *e = newObject;
  8003. if (newObject != 0)
  8004. newObject->incReferenceCount();
  8005. ++numUsed;
  8006. }
  8007. else
  8008. {
  8009. add (newObject);
  8010. }
  8011. }
  8012. /** Appends a new object at the end of the array as long as the array doesn't
  8013. already contain it.
  8014. If the array already contains a matching object, nothing will be done.
  8015. @param newObject the new object to add to the array
  8016. */
  8017. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  8018. {
  8019. const ScopedLockType lock (getLock());
  8020. if (! contains (newObject))
  8021. add (newObject);
  8022. }
  8023. /** Replaces an object in the array with a different one.
  8024. If the index is less than zero, this method does nothing.
  8025. If the index is beyond the end of the array, the new object is added to the end of the array.
  8026. The object being added has its reference count increased, and if it's replacing
  8027. another object, then that one has its reference count decreased, and may be deleted.
  8028. @param indexToChange the index whose value you want to change
  8029. @param newObject the new value to set for this index.
  8030. @see add, insert, remove
  8031. */
  8032. void set (const int indexToChange,
  8033. ObjectClass* const newObject)
  8034. {
  8035. if (indexToChange >= 0)
  8036. {
  8037. const ScopedLockType lock (getLock());
  8038. if (newObject != 0)
  8039. newObject->incReferenceCount();
  8040. if (indexToChange < numUsed)
  8041. {
  8042. if (data.elements [indexToChange] != 0)
  8043. data.elements [indexToChange]->decReferenceCount();
  8044. data.elements [indexToChange] = newObject;
  8045. }
  8046. else
  8047. {
  8048. data.ensureAllocatedSize (numUsed + 1);
  8049. data.elements [numUsed++] = newObject;
  8050. }
  8051. }
  8052. }
  8053. /** Adds elements from another array to the end of this array.
  8054. @param arrayToAddFrom the array from which to copy the elements
  8055. @param startIndex the first element of the other array to start copying from
  8056. @param numElementsToAdd how many elements to add from the other array. If this
  8057. value is negative or greater than the number of available elements,
  8058. all available elements will be copied.
  8059. @see add
  8060. */
  8061. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  8062. int startIndex = 0,
  8063. int numElementsToAdd = -1) throw()
  8064. {
  8065. arrayToAddFrom.lockArray();
  8066. const ScopedLockType lock (getLock());
  8067. if (startIndex < 0)
  8068. {
  8069. jassertfalse;
  8070. startIndex = 0;
  8071. }
  8072. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  8073. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  8074. if (numElementsToAdd > 0)
  8075. {
  8076. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  8077. while (--numElementsToAdd >= 0)
  8078. add (arrayToAddFrom.getUnchecked (startIndex++));
  8079. }
  8080. arrayToAddFrom.unlockArray();
  8081. }
  8082. /** Inserts a new object into the array assuming that the array is sorted.
  8083. This will use a comparator to find the position at which the new object
  8084. should go. If the array isn't sorted, the behaviour of this
  8085. method will be unpredictable.
  8086. @param comparator the comparator object to use to compare the elements - see the
  8087. sort() method for details about this object's form
  8088. @param newObject the new object to insert to the array
  8089. @see add, sort
  8090. */
  8091. template <class ElementComparator>
  8092. void addSorted (ElementComparator& comparator,
  8093. ObjectClass* newObject) throw()
  8094. {
  8095. const ScopedLockType lock (getLock());
  8096. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  8097. }
  8098. /** Inserts or replaces an object in the array, assuming it is sorted.
  8099. This is similar to addSorted, but if a matching element already exists, then it will be
  8100. replaced by the new one, rather than the new one being added as well.
  8101. */
  8102. template <class ElementComparator>
  8103. void addOrReplaceSorted (ElementComparator& comparator,
  8104. ObjectClass* newObject) throw()
  8105. {
  8106. const ScopedLockType lock (getLock());
  8107. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  8108. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  8109. set (index - 1, newObject); // replace an existing object that matches
  8110. else
  8111. insert (index, newObject); // no match, so insert the new one
  8112. }
  8113. /** Removes an object from the array.
  8114. This will remove the object at a given index and move back all the
  8115. subsequent objects to close the gap.
  8116. If the index passed in is out-of-range, nothing will happen.
  8117. The object that is removed will have its reference count decreased,
  8118. and may be deleted if not referenced from elsewhere.
  8119. @param indexToRemove the index of the element to remove
  8120. @see removeObject, removeRange
  8121. */
  8122. void remove (const int indexToRemove)
  8123. {
  8124. const ScopedLockType lock (getLock());
  8125. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8126. {
  8127. ObjectClass** const e = data.elements + indexToRemove;
  8128. if (*e != 0)
  8129. (*e)->decReferenceCount();
  8130. --numUsed;
  8131. const int numberToShift = numUsed - indexToRemove;
  8132. if (numberToShift > 0)
  8133. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  8134. if ((numUsed << 1) < data.numAllocated)
  8135. minimiseStorageOverheads();
  8136. }
  8137. }
  8138. /** Removes the first occurrence of a specified object from the array.
  8139. If the item isn't found, no action is taken. If it is found, it is
  8140. removed and has its reference count decreased.
  8141. @param objectToRemove the object to try to remove
  8142. @see remove, removeRange
  8143. */
  8144. void removeObject (ObjectClass* const objectToRemove)
  8145. {
  8146. const ScopedLockType lock (getLock());
  8147. remove (indexOf (objectToRemove));
  8148. }
  8149. /** Removes a range of objects from the array.
  8150. This will remove a set of objects, starting from the given index,
  8151. and move any subsequent elements down to close the gap.
  8152. If the range extends beyond the bounds of the array, it will
  8153. be safely clipped to the size of the array.
  8154. The objects that are removed will have their reference counts decreased,
  8155. and may be deleted if not referenced from elsewhere.
  8156. @param startIndex the index of the first object to remove
  8157. @param numberToRemove how many objects should be removed
  8158. @see remove, removeObject
  8159. */
  8160. void removeRange (const int startIndex,
  8161. const int numberToRemove)
  8162. {
  8163. const ScopedLockType lock (getLock());
  8164. const int start = jlimit (0, numUsed, startIndex);
  8165. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  8166. if (end > start)
  8167. {
  8168. int i;
  8169. for (i = start; i < end; ++i)
  8170. {
  8171. if (data.elements[i] != 0)
  8172. {
  8173. data.elements[i]->decReferenceCount();
  8174. data.elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  8175. }
  8176. }
  8177. const int rangeSize = end - start;
  8178. ObjectClass** e = data.elements + start;
  8179. i = numUsed - end;
  8180. numUsed -= rangeSize;
  8181. while (--i >= 0)
  8182. {
  8183. *e = e [rangeSize];
  8184. ++e;
  8185. }
  8186. if ((numUsed << 1) < data.numAllocated)
  8187. minimiseStorageOverheads();
  8188. }
  8189. }
  8190. /** Removes the last n objects from the array.
  8191. The objects that are removed will have their reference counts decreased,
  8192. and may be deleted if not referenced from elsewhere.
  8193. @param howManyToRemove how many objects to remove from the end of the array
  8194. @see remove, removeObject, removeRange
  8195. */
  8196. void removeLast (int howManyToRemove = 1)
  8197. {
  8198. const ScopedLockType lock (getLock());
  8199. if (howManyToRemove > numUsed)
  8200. howManyToRemove = numUsed;
  8201. while (--howManyToRemove >= 0)
  8202. remove (numUsed - 1);
  8203. }
  8204. /** Swaps a pair of objects in the array.
  8205. If either of the indexes passed in is out-of-range, nothing will happen,
  8206. otherwise the two objects at these positions will be exchanged.
  8207. */
  8208. void swap (const int index1,
  8209. const int index2) throw()
  8210. {
  8211. const ScopedLockType lock (getLock());
  8212. if (((unsigned int) index1) < (unsigned int) numUsed
  8213. && ((unsigned int) index2) < (unsigned int) numUsed)
  8214. {
  8215. swapVariables (data.elements [index1],
  8216. data.elements [index2]);
  8217. }
  8218. }
  8219. /** Moves one of the objects to a different position.
  8220. This will move the object to a specified index, shuffling along
  8221. any intervening elements as required.
  8222. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8223. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8224. @param currentIndex the index of the object to be moved. If this isn't a
  8225. valid index, then nothing will be done
  8226. @param newIndex the index at which you'd like this object to end up. If this
  8227. is less than zero, it will be moved to the end of the array
  8228. */
  8229. void move (const int currentIndex,
  8230. int newIndex) throw()
  8231. {
  8232. if (currentIndex != newIndex)
  8233. {
  8234. const ScopedLockType lock (getLock());
  8235. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  8236. {
  8237. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  8238. newIndex = numUsed - 1;
  8239. ObjectClass* const value = data.elements [currentIndex];
  8240. if (newIndex > currentIndex)
  8241. {
  8242. memmove (data.elements + currentIndex,
  8243. data.elements + currentIndex + 1,
  8244. (newIndex - currentIndex) * sizeof (ObjectClass*));
  8245. }
  8246. else
  8247. {
  8248. memmove (data.elements + newIndex + 1,
  8249. data.elements + newIndex,
  8250. (currentIndex - newIndex) * sizeof (ObjectClass*));
  8251. }
  8252. data.elements [newIndex] = value;
  8253. }
  8254. }
  8255. }
  8256. /** This swaps the contents of this array with those of another array.
  8257. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  8258. because it just swaps their internal pointers.
  8259. */
  8260. void swapWithArray (ReferenceCountedArray& otherArray) throw()
  8261. {
  8262. const ScopedLockType lock1 (getLock());
  8263. const ScopedLockType lock2 (otherArray.getLock());
  8264. data.swapWith (otherArray.data);
  8265. swapVariables (numUsed, otherArray.numUsed);
  8266. }
  8267. /** Compares this array to another one.
  8268. @returns true only if the other array contains the same objects in the same order
  8269. */
  8270. bool operator== (const ReferenceCountedArray& other) const throw()
  8271. {
  8272. const ScopedLockType lock2 (other.getLock());
  8273. const ScopedLockType lock1 (getLock());
  8274. if (numUsed != other.numUsed)
  8275. return false;
  8276. for (int i = numUsed; --i >= 0;)
  8277. if (data.elements [i] != other.data.elements [i])
  8278. return false;
  8279. return true;
  8280. }
  8281. /** Compares this array to another one.
  8282. @see operator==
  8283. */
  8284. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  8285. {
  8286. return ! operator== (other);
  8287. }
  8288. /** Sorts the elements in the array.
  8289. This will use a comparator object to sort the elements into order. The object
  8290. passed must have a method of the form:
  8291. @code
  8292. int compareElements (ElementType first, ElementType second);
  8293. @endcode
  8294. ..and this method must return:
  8295. - a value of < 0 if the first comes before the second
  8296. - a value of 0 if the two objects are equivalent
  8297. - a value of > 0 if the second comes before the first
  8298. To improve performance, the compareElements() method can be declared as static or const.
  8299. @param comparator the comparator to use for comparing elements.
  8300. @param retainOrderOfEquivalentItems if this is true, then items
  8301. which the comparator says are equivalent will be
  8302. kept in the order in which they currently appear
  8303. in the array. This is slower to perform, but may
  8304. be important in some cases. If it's false, a faster
  8305. algorithm is used, but equivalent elements may be
  8306. rearranged.
  8307. @see sortArray
  8308. */
  8309. template <class ElementComparator>
  8310. void sort (ElementComparator& comparator,
  8311. const bool retainOrderOfEquivalentItems = false) const throw()
  8312. {
  8313. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8314. // avoids getting warning messages about the parameter being unused
  8315. const ScopedLockType lock (getLock());
  8316. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  8317. }
  8318. /** Reduces the amount of storage being used by the array.
  8319. Arrays typically allocate slightly more storage than they need, and after
  8320. removing elements, they may have quite a lot of unused space allocated.
  8321. This method will reduce the amount of allocated storage to a minimum.
  8322. */
  8323. void minimiseStorageOverheads() throw()
  8324. {
  8325. const ScopedLockType lock (getLock());
  8326. data.shrinkToNoMoreThan (numUsed);
  8327. }
  8328. /** Returns the CriticalSection that locks this array.
  8329. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8330. an object of ScopedLockType as an RAII lock for it.
  8331. */
  8332. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  8333. /** Returns the type of scoped lock to use for locking this array */
  8334. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8335. juce_UseDebuggingNewOperator
  8336. private:
  8337. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  8338. int numUsed;
  8339. };
  8340. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  8341. /*** End of inlined file: juce_ReferenceCountedArray.h ***/
  8342. #endif
  8343. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  8344. #endif
  8345. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8346. #endif
  8347. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8348. /*** Start of inlined file: juce_SortedSet.h ***/
  8349. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8350. #define __JUCE_SORTEDSET_JUCEHEADER__
  8351. #if JUCE_MSVC
  8352. #pragma warning (push)
  8353. #pragma warning (disable: 4512)
  8354. #endif
  8355. /**
  8356. Holds a set of unique primitive objects, such as ints or doubles.
  8357. A set can only hold one item with a given value, so if for example it's a
  8358. set of integers, attempting to add the same integer twice will do nothing
  8359. the second time.
  8360. Internally, the list of items is kept sorted (which means that whatever
  8361. kind of primitive type is used must support the ==, <, >, <= and >= operators
  8362. to determine the order), and searching the set for known values is very fast
  8363. because it uses a binary-chop method.
  8364. Note that if you're using a class or struct as the element type, it must be
  8365. capable of being copied or moved with a straightforward memcpy, rather than
  8366. needing construction and destruction code.
  8367. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  8368. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  8369. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  8370. */
  8371. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8372. class SortedSet
  8373. {
  8374. public:
  8375. /** Creates an empty set. */
  8376. SortedSet() throw()
  8377. : numUsed (0)
  8378. {
  8379. }
  8380. /** Creates a copy of another set.
  8381. @param other the set to copy
  8382. */
  8383. SortedSet (const SortedSet& other) throw()
  8384. {
  8385. const ScopedLockType lock (other.getLock());
  8386. numUsed = other.numUsed;
  8387. data.setAllocatedSize (other.numUsed);
  8388. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  8389. }
  8390. /** Destructor. */
  8391. ~SortedSet() throw()
  8392. {
  8393. }
  8394. /** Copies another set over this one.
  8395. @param other the set to copy
  8396. */
  8397. SortedSet& operator= (const SortedSet& other) throw()
  8398. {
  8399. if (this != &other)
  8400. {
  8401. const ScopedLockType lock1 (other.getLock());
  8402. const ScopedLockType lock2 (getLock());
  8403. data.ensureAllocatedSize (other.size());
  8404. numUsed = other.numUsed;
  8405. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  8406. minimiseStorageOverheads();
  8407. }
  8408. return *this;
  8409. }
  8410. /** Compares this set to another one.
  8411. Two sets are considered equal if they both contain the same set of
  8412. elements.
  8413. @param other the other set to compare with
  8414. */
  8415. bool operator== (const SortedSet<ElementType>& other) const throw()
  8416. {
  8417. const ScopedLockType lock (getLock());
  8418. if (numUsed != other.numUsed)
  8419. return false;
  8420. for (int i = numUsed; --i >= 0;)
  8421. if (data.elements[i] != other.data.elements[i])
  8422. return false;
  8423. return true;
  8424. }
  8425. /** Compares this set to another one.
  8426. Two sets are considered equal if they both contain the same set of
  8427. elements.
  8428. @param other the other set to compare with
  8429. */
  8430. bool operator!= (const SortedSet<ElementType>& other) const throw()
  8431. {
  8432. return ! operator== (other);
  8433. }
  8434. /** Removes all elements from the set.
  8435. This will remove all the elements, and free any storage that the set is
  8436. using. To clear it without freeing the storage, use the clearQuick()
  8437. method instead.
  8438. @see clearQuick
  8439. */
  8440. void clear() throw()
  8441. {
  8442. const ScopedLockType lock (getLock());
  8443. data.setAllocatedSize (0);
  8444. numUsed = 0;
  8445. }
  8446. /** Removes all elements from the set without freeing the array's allocated storage.
  8447. @see clear
  8448. */
  8449. void clearQuick() throw()
  8450. {
  8451. const ScopedLockType lock (getLock());
  8452. numUsed = 0;
  8453. }
  8454. /** Returns the current number of elements in the set.
  8455. */
  8456. inline int size() const throw()
  8457. {
  8458. return numUsed;
  8459. }
  8460. /** Returns one of the elements in the set.
  8461. If the index passed in is beyond the range of valid elements, this
  8462. will return zero.
  8463. If you're certain that the index will always be a valid element, you
  8464. can call getUnchecked() instead, which is faster.
  8465. @param index the index of the element being requested (0 is the first element in the set)
  8466. @see getUnchecked, getFirst, getLast
  8467. */
  8468. inline ElementType operator[] (const int index) const throw()
  8469. {
  8470. const ScopedLockType lock (getLock());
  8471. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  8472. : ElementType();
  8473. }
  8474. /** Returns one of the elements in the set, without checking the index passed in.
  8475. Unlike the operator[] method, this will try to return an element without
  8476. checking that the index is within the bounds of the set, so should only
  8477. be used when you're confident that it will always be a valid index.
  8478. @param index the index of the element being requested (0 is the first element in the set)
  8479. @see operator[], getFirst, getLast
  8480. */
  8481. inline ElementType getUnchecked (const int index) const throw()
  8482. {
  8483. const ScopedLockType lock (getLock());
  8484. jassert (((unsigned int) index) < (unsigned int) numUsed);
  8485. return data.elements [index];
  8486. }
  8487. /** Returns the first element in the set, or 0 if the set is empty.
  8488. @see operator[], getUnchecked, getLast
  8489. */
  8490. inline ElementType getFirst() const throw()
  8491. {
  8492. const ScopedLockType lock (getLock());
  8493. return numUsed > 0 ? data.elements [0] : ElementType();
  8494. }
  8495. /** Returns the last element in the set, or 0 if the set is empty.
  8496. @see operator[], getUnchecked, getFirst
  8497. */
  8498. inline ElementType getLast() const throw()
  8499. {
  8500. const ScopedLockType lock (getLock());
  8501. return numUsed > 0 ? data.elements [numUsed - 1] : ElementType();
  8502. }
  8503. /** Finds the index of the first element which matches the value passed in.
  8504. This will search the set for the given object, and return the index
  8505. of its first occurrence. If the object isn't found, the method will return -1.
  8506. @param elementToLookFor the value or object to look for
  8507. @returns the index of the object, or -1 if it's not found
  8508. */
  8509. int indexOf (const ElementType elementToLookFor) const throw()
  8510. {
  8511. const ScopedLockType lock (getLock());
  8512. int start = 0;
  8513. int end = numUsed;
  8514. for (;;)
  8515. {
  8516. if (start >= end)
  8517. {
  8518. return -1;
  8519. }
  8520. else if (elementToLookFor == data.elements [start])
  8521. {
  8522. return start;
  8523. }
  8524. else
  8525. {
  8526. const int halfway = (start + end) >> 1;
  8527. if (halfway == start)
  8528. return -1;
  8529. else if (elementToLookFor >= data.elements [halfway])
  8530. start = halfway;
  8531. else
  8532. end = halfway;
  8533. }
  8534. }
  8535. }
  8536. /** Returns true if the set contains at least one occurrence of an object.
  8537. @param elementToLookFor the value or object to look for
  8538. @returns true if the item is found
  8539. */
  8540. bool contains (const ElementType elementToLookFor) const throw()
  8541. {
  8542. const ScopedLockType lock (getLock());
  8543. int start = 0;
  8544. int end = numUsed;
  8545. for (;;)
  8546. {
  8547. if (start >= end)
  8548. {
  8549. return false;
  8550. }
  8551. else if (elementToLookFor == data.elements [start])
  8552. {
  8553. return true;
  8554. }
  8555. else
  8556. {
  8557. const int halfway = (start + end) >> 1;
  8558. if (halfway == start)
  8559. return false;
  8560. else if (elementToLookFor >= data.elements [halfway])
  8561. start = halfway;
  8562. else
  8563. end = halfway;
  8564. }
  8565. }
  8566. }
  8567. /** Adds a new element to the set, (as long as it's not already in there).
  8568. @param newElement the new object to add to the set
  8569. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  8570. */
  8571. void add (const ElementType newElement) throw()
  8572. {
  8573. const ScopedLockType lock (getLock());
  8574. int start = 0;
  8575. int end = numUsed;
  8576. for (;;)
  8577. {
  8578. if (start >= end)
  8579. {
  8580. jassert (start <= end);
  8581. insertInternal (start, newElement);
  8582. break;
  8583. }
  8584. else if (newElement == data.elements [start])
  8585. {
  8586. break;
  8587. }
  8588. else
  8589. {
  8590. const int halfway = (start + end) >> 1;
  8591. if (halfway == start)
  8592. {
  8593. if (newElement >= data.elements [halfway])
  8594. insertInternal (start + 1, newElement);
  8595. else
  8596. insertInternal (start, newElement);
  8597. break;
  8598. }
  8599. else if (newElement >= data.elements [halfway])
  8600. start = halfway;
  8601. else
  8602. end = halfway;
  8603. }
  8604. }
  8605. }
  8606. /** Adds elements from an array to this set.
  8607. @param elementsToAdd the array of elements to add
  8608. @param numElementsToAdd how many elements are in this other array
  8609. @see add
  8610. */
  8611. void addArray (const ElementType* elementsToAdd,
  8612. int numElementsToAdd) throw()
  8613. {
  8614. const ScopedLockType lock (getLock());
  8615. while (--numElementsToAdd >= 0)
  8616. add (*elementsToAdd++);
  8617. }
  8618. /** Adds elements from another set to this one.
  8619. @param setToAddFrom the set from which to copy the elements
  8620. @param startIndex the first element of the other set to start copying from
  8621. @param numElementsToAdd how many elements to add from the other set. If this
  8622. value is negative or greater than the number of available elements,
  8623. all available elements will be copied.
  8624. @see add
  8625. */
  8626. template <class OtherSetType>
  8627. void addSet (const OtherSetType& setToAddFrom,
  8628. int startIndex = 0,
  8629. int numElementsToAdd = -1) throw()
  8630. {
  8631. const typename OtherSetType::ScopedLockType lock1 (setToAddFrom.getLock());
  8632. const ScopedLockType lock2 (getLock());
  8633. jassert (this != &setToAddFrom);
  8634. if (this != &setToAddFrom)
  8635. {
  8636. if (startIndex < 0)
  8637. {
  8638. jassertfalse;
  8639. startIndex = 0;
  8640. }
  8641. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  8642. numElementsToAdd = setToAddFrom.size() - startIndex;
  8643. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  8644. }
  8645. }
  8646. /** Removes an element from the set.
  8647. This will remove the element at a given index.
  8648. If the index passed in is out-of-range, nothing will happen.
  8649. @param indexToRemove the index of the element to remove
  8650. @returns the element that has been removed
  8651. @see removeValue, removeRange
  8652. */
  8653. ElementType remove (const int indexToRemove) throw()
  8654. {
  8655. const ScopedLockType lock (getLock());
  8656. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8657. {
  8658. --numUsed;
  8659. ElementType* const e = data.elements + indexToRemove;
  8660. ElementType const removed = *e;
  8661. const int numberToShift = numUsed - indexToRemove;
  8662. if (numberToShift > 0)
  8663. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  8664. if ((numUsed << 1) < data.numAllocated)
  8665. minimiseStorageOverheads();
  8666. return removed;
  8667. }
  8668. return 0;
  8669. }
  8670. /** Removes an item from the set.
  8671. This will remove the given element from the set, if it's there.
  8672. @param valueToRemove the object to try to remove
  8673. @see remove, removeRange
  8674. */
  8675. void removeValue (const ElementType valueToRemove) throw()
  8676. {
  8677. const ScopedLockType lock (getLock());
  8678. remove (indexOf (valueToRemove));
  8679. }
  8680. /** Removes any elements which are also in another set.
  8681. @param otherSet the other set in which to look for elements to remove
  8682. @see removeValuesNotIn, remove, removeValue, removeRange
  8683. */
  8684. template <class OtherSetType>
  8685. void removeValuesIn (const OtherSetType& otherSet) throw()
  8686. {
  8687. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  8688. const ScopedLockType lock2 (getLock());
  8689. if (this == &otherSet)
  8690. {
  8691. clear();
  8692. }
  8693. else
  8694. {
  8695. if (otherSet.size() > 0)
  8696. {
  8697. for (int i = numUsed; --i >= 0;)
  8698. if (otherSet.contains (data.elements [i]))
  8699. remove (i);
  8700. }
  8701. }
  8702. }
  8703. /** Removes any elements which are not found in another set.
  8704. Only elements which occur in this other set will be retained.
  8705. @param otherSet the set in which to look for elements NOT to remove
  8706. @see removeValuesIn, remove, removeValue, removeRange
  8707. */
  8708. template <class OtherSetType>
  8709. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  8710. {
  8711. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  8712. const ScopedLockType lock2 (getLock());
  8713. if (this != &otherSet)
  8714. {
  8715. if (otherSet.size() <= 0)
  8716. {
  8717. clear();
  8718. }
  8719. else
  8720. {
  8721. for (int i = numUsed; --i >= 0;)
  8722. if (! otherSet.contains (data.elements [i]))
  8723. remove (i);
  8724. }
  8725. }
  8726. }
  8727. /** Reduces the amount of storage being used by the set.
  8728. Sets typically allocate slightly more storage than they need, and after
  8729. removing elements, they may have quite a lot of unused space allocated.
  8730. This method will reduce the amount of allocated storage to a minimum.
  8731. */
  8732. void minimiseStorageOverheads() throw()
  8733. {
  8734. const ScopedLockType lock (getLock());
  8735. data.shrinkToNoMoreThan (numUsed);
  8736. }
  8737. /** Returns the CriticalSection that locks this array.
  8738. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8739. an object of ScopedLockType as an RAII lock for it.
  8740. */
  8741. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  8742. /** Returns the type of scoped lock to use for locking this array */
  8743. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8744. juce_UseDebuggingNewOperator
  8745. private:
  8746. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  8747. int numUsed;
  8748. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  8749. {
  8750. data.ensureAllocatedSize (numUsed + 1);
  8751. ElementType* const insertPos = data.elements + indexToInsertAt;
  8752. const int numberToMove = numUsed - indexToInsertAt;
  8753. if (numberToMove > 0)
  8754. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  8755. *insertPos = newElement;
  8756. ++numUsed;
  8757. }
  8758. };
  8759. #if JUCE_MSVC
  8760. #pragma warning (pop)
  8761. #endif
  8762. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  8763. /*** End of inlined file: juce_SortedSet.h ***/
  8764. #endif
  8765. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8766. /*** Start of inlined file: juce_SparseSet.h ***/
  8767. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8768. #define __JUCE_SPARSESET_JUCEHEADER__
  8769. /**
  8770. Holds a set of primitive values, storing them as a set of ranges.
  8771. This container acts like an array, but can efficiently hold large continguous
  8772. ranges of values. It's quite a specialised class, mostly useful for things
  8773. like keeping the set of selected rows in a listbox.
  8774. The type used as a template paramter must be an integer type, such as int, short,
  8775. int64, etc.
  8776. */
  8777. template <class Type>
  8778. class SparseSet
  8779. {
  8780. public:
  8781. /** Creates a new empty set. */
  8782. SparseSet()
  8783. {
  8784. }
  8785. /** Creates a copy of another SparseSet. */
  8786. SparseSet (const SparseSet<Type>& other)
  8787. : values (other.values)
  8788. {
  8789. }
  8790. /** Destructor. */
  8791. ~SparseSet()
  8792. {
  8793. }
  8794. /** Clears the set. */
  8795. void clear()
  8796. {
  8797. values.clear();
  8798. }
  8799. /** Checks whether the set is empty.
  8800. This is much quicker than using (size() == 0).
  8801. */
  8802. bool isEmpty() const throw()
  8803. {
  8804. return values.size() == 0;
  8805. }
  8806. /** Returns the number of values in the set.
  8807. Because of the way the data is stored, this method can take longer if there
  8808. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  8809. are any items.
  8810. */
  8811. Type size() const
  8812. {
  8813. Type total (0);
  8814. for (int i = 0; i < values.size(); i += 2)
  8815. total += values.getUnchecked (i + 1) - values.getUnchecked (i);
  8816. return total;
  8817. }
  8818. /** Returns one of the values in the set.
  8819. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  8820. @returns the value at this index, or 0 if it's out-of-range
  8821. */
  8822. Type operator[] (Type index) const
  8823. {
  8824. for (int i = 0; i < values.size(); i += 2)
  8825. {
  8826. const Type start (values.getUnchecked (i));
  8827. const Type len (values.getUnchecked (i + 1) - start);
  8828. if (index < len)
  8829. return start + index;
  8830. index -= len;
  8831. }
  8832. return Type (0);
  8833. }
  8834. /** Checks whether a particular value is in the set. */
  8835. bool contains (const Type valueToLookFor) const
  8836. {
  8837. for (int i = 0; i < values.size(); ++i)
  8838. if (valueToLookFor < values.getUnchecked(i))
  8839. return (i & 1) != 0;
  8840. return false;
  8841. }
  8842. /** Returns the number of contiguous blocks of values.
  8843. @see getRange
  8844. */
  8845. int getNumRanges() const throw()
  8846. {
  8847. return values.size() >> 1;
  8848. }
  8849. /** Returns one of the contiguous ranges of values stored.
  8850. @param rangeIndex the index of the range to look up, between 0
  8851. and (getNumRanges() - 1)
  8852. @see getTotalRange
  8853. */
  8854. const Range<Type> getRange (const int rangeIndex) const
  8855. {
  8856. if (((unsigned int) rangeIndex) < (unsigned int) getNumRanges())
  8857. return Range<Type> (values.getUnchecked (rangeIndex << 1),
  8858. values.getUnchecked ((rangeIndex << 1) + 1));
  8859. else
  8860. return Range<Type>();
  8861. }
  8862. /** Returns the range between the lowest and highest values in the set.
  8863. @see getRange
  8864. */
  8865. const Range<Type> getTotalRange() const
  8866. {
  8867. if (values.size() > 0)
  8868. {
  8869. jassert ((values.size() & 1) == 0);
  8870. return Range<Type> (values.getUnchecked (0),
  8871. values.getUnchecked (values.size() - 1));
  8872. }
  8873. return Range<Type>();
  8874. }
  8875. /** Adds a range of contiguous values to the set.
  8876. e.g. addRange (Range \<int\> (10, 14)) will add (10, 11, 12, 13) to the set.
  8877. */
  8878. void addRange (const Range<Type>& range)
  8879. {
  8880. jassert (range.getLength() >= 0);
  8881. if (range.getLength() > 0)
  8882. {
  8883. removeRange (range);
  8884. values.addUsingDefaultSort (range.getStart());
  8885. values.addUsingDefaultSort (range.getEnd());
  8886. simplify();
  8887. }
  8888. }
  8889. /** Removes a range of values from the set.
  8890. e.g. removeRange (Range\<int\> (10, 14)) will remove (10, 11, 12, 13) from the set.
  8891. */
  8892. void removeRange (const Range<Type>& rangeToRemove)
  8893. {
  8894. jassert (rangeToRemove.getLength() >= 0);
  8895. if (rangeToRemove.getLength() > 0
  8896. && values.size() > 0
  8897. && rangeToRemove.getStart() < values.getUnchecked (values.size() - 1)
  8898. && values.getUnchecked(0) < rangeToRemove.getEnd())
  8899. {
  8900. const bool onAtStart = contains (rangeToRemove.getStart() - 1);
  8901. const Type lastValue (jmin (rangeToRemove.getEnd(), values.getLast()));
  8902. const bool onAtEnd = contains (lastValue);
  8903. for (int i = values.size(); --i >= 0;)
  8904. {
  8905. if (values.getUnchecked(i) <= lastValue)
  8906. {
  8907. while (values.getUnchecked(i) >= rangeToRemove.getStart())
  8908. {
  8909. values.remove (i);
  8910. if (--i < 0)
  8911. break;
  8912. }
  8913. break;
  8914. }
  8915. }
  8916. if (onAtStart) values.addUsingDefaultSort (rangeToRemove.getStart());
  8917. if (onAtEnd) values.addUsingDefaultSort (lastValue);
  8918. simplify();
  8919. }
  8920. }
  8921. /** Does an XOR of the values in a given range. */
  8922. void invertRange (const Range<Type>& range)
  8923. {
  8924. SparseSet newItems;
  8925. newItems.addRange (range);
  8926. int i;
  8927. for (i = getNumRanges(); --i >= 0;)
  8928. newItems.removeRange (getRange (i));
  8929. removeRange (range);
  8930. for (i = newItems.getNumRanges(); --i >= 0;)
  8931. addRange (newItems.getRange(i));
  8932. }
  8933. /** Checks whether any part of a given range overlaps any part of this set. */
  8934. bool overlapsRange (const Range<Type>& range)
  8935. {
  8936. if (range.getLength() > 0)
  8937. {
  8938. for (int i = getNumRanges(); --i >= 0;)
  8939. {
  8940. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  8941. return false;
  8942. if (values.getUnchecked (i << 1) < range.getEnd())
  8943. return true;
  8944. }
  8945. }
  8946. return false;
  8947. }
  8948. /** Checks whether the whole of a given range is contained within this one. */
  8949. bool containsRange (const Range<Type>& range)
  8950. {
  8951. if (range.getLength() > 0)
  8952. {
  8953. for (int i = getNumRanges(); --i >= 0;)
  8954. {
  8955. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  8956. return false;
  8957. if (values.getUnchecked (i << 1) <= range.getStart()
  8958. && range.getEnd() <= values.getUnchecked ((i << 1) + 1))
  8959. return true;
  8960. }
  8961. }
  8962. return false;
  8963. }
  8964. bool operator== (const SparseSet<Type>& other) throw()
  8965. {
  8966. return values == other.values;
  8967. }
  8968. bool operator!= (const SparseSet<Type>& other) throw()
  8969. {
  8970. return values != other.values;
  8971. }
  8972. juce_UseDebuggingNewOperator
  8973. private:
  8974. // alternating start/end values of ranges of values that are present.
  8975. Array<Type, DummyCriticalSection> values;
  8976. void simplify()
  8977. {
  8978. jassert ((values.size() & 1) == 0);
  8979. for (int i = values.size(); --i > 0;)
  8980. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  8981. values.removeRange (--i, 2);
  8982. }
  8983. };
  8984. #endif // __JUCE_SPARSESET_JUCEHEADER__
  8985. /*** End of inlined file: juce_SparseSet.h ***/
  8986. #endif
  8987. #ifndef __JUCE_VALUE_JUCEHEADER__
  8988. /*** Start of inlined file: juce_Value.h ***/
  8989. #ifndef __JUCE_VALUE_JUCEHEADER__
  8990. #define __JUCE_VALUE_JUCEHEADER__
  8991. /*** Start of inlined file: juce_AsyncUpdater.h ***/
  8992. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  8993. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  8994. /*** Start of inlined file: juce_MessageListener.h ***/
  8995. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  8996. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  8997. /*** Start of inlined file: juce_Message.h ***/
  8998. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  8999. #define __JUCE_MESSAGE_JUCEHEADER__
  9000. class MessageListener;
  9001. class MessageManager;
  9002. /** The base class for objects that can be delivered to a MessageListener.
  9003. The simplest Message object contains a few integer and pointer parameters
  9004. that the user can set, and this is enough for a lot of purposes. For passing more
  9005. complex data, subclasses of Message can also be used.
  9006. @see MessageListener, MessageManager, ActionListener, ChangeListener
  9007. */
  9008. class JUCE_API Message
  9009. {
  9010. public:
  9011. /** Creates an uninitialised message.
  9012. The class's variables will also be left uninitialised.
  9013. */
  9014. Message() throw();
  9015. /** Creates a message object, filling in the member variables.
  9016. The corresponding public member variables will be set from the parameters
  9017. passed in.
  9018. */
  9019. Message (int intParameter1,
  9020. int intParameter2,
  9021. int intParameter3,
  9022. void* pointerParameter) throw();
  9023. /** Destructor. */
  9024. virtual ~Message() throw();
  9025. // These values can be used for carrying simple data that the application needs to
  9026. // pass around. For more complex messages, just create a subclass.
  9027. int intParameter1; /**< user-defined integer value. */
  9028. int intParameter2; /**< user-defined integer value. */
  9029. int intParameter3; /**< user-defined integer value. */
  9030. void* pointerParameter; /**< user-defined pointer value. */
  9031. juce_UseDebuggingNewOperator
  9032. private:
  9033. friend class MessageListener;
  9034. friend class MessageManager;
  9035. MessageListener* messageRecipient;
  9036. Message (const Message&);
  9037. Message& operator= (const Message&);
  9038. };
  9039. #endif // __JUCE_MESSAGE_JUCEHEADER__
  9040. /*** End of inlined file: juce_Message.h ***/
  9041. /**
  9042. MessageListener subclasses can post and receive Message objects.
  9043. @see Message, MessageManager, ActionListener, ChangeListener
  9044. */
  9045. class JUCE_API MessageListener
  9046. {
  9047. protected:
  9048. /** Creates a MessageListener. */
  9049. MessageListener() throw();
  9050. public:
  9051. /** Destructor.
  9052. When a MessageListener is deleted, it removes itself from a global list
  9053. of registered listeners, so that the isValidMessageListener() method
  9054. will no longer return true.
  9055. */
  9056. virtual ~MessageListener();
  9057. /** This is the callback method that receives incoming messages.
  9058. This is called by the MessageManager from its dispatch loop.
  9059. @see postMessage
  9060. */
  9061. virtual void handleMessage (const Message& message) = 0;
  9062. /** Sends a message to the message queue, for asynchronous delivery to this listener
  9063. later on.
  9064. This method can be called safely by any thread.
  9065. @param message the message object to send - this will be deleted
  9066. automatically by the message queue, so don't keep any
  9067. references to it after calling this method.
  9068. @see handleMessage
  9069. */
  9070. void postMessage (Message* message) const throw();
  9071. /** Checks whether this MessageListener has been deleted.
  9072. Although not foolproof, this method is safe to call on dangling or null
  9073. pointers. A list of active MessageListeners is kept internally, so this
  9074. checks whether the object is on this list or not.
  9075. Note that it's possible to get a false-positive here, if an object is
  9076. deleted and another is subsequently created that happens to be at the
  9077. exact same memory location, but I can't think of a good way of avoiding
  9078. this.
  9079. */
  9080. bool isValidMessageListener() const throw();
  9081. };
  9082. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  9083. /*** End of inlined file: juce_MessageListener.h ***/
  9084. /**
  9085. Has a callback method that is triggered asynchronously.
  9086. This object allows an asynchronous callback function to be triggered, for
  9087. tasks such as coalescing multiple updates into a single callback later on.
  9088. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  9089. message thread calling handleAsyncUpdate() as soon as it can.
  9090. */
  9091. class JUCE_API AsyncUpdater
  9092. {
  9093. public:
  9094. /** Creates an AsyncUpdater object. */
  9095. AsyncUpdater() throw();
  9096. /** Destructor.
  9097. If there are any pending callbacks when the object is deleted, these are lost.
  9098. */
  9099. virtual ~AsyncUpdater();
  9100. /** Causes the callback to be triggered at a later time.
  9101. This method returns immediately, having made sure that a callback
  9102. to the handleAsyncUpdate() method will occur as soon as possible.
  9103. If an update callback is already pending but hasn't happened yet, calls
  9104. to this method will be ignored.
  9105. It's thread-safe to call this method from any number of threads without
  9106. needing to worry about locking.
  9107. */
  9108. void triggerAsyncUpdate() throw();
  9109. /** This will stop any pending updates from happening.
  9110. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  9111. callback happens, this will cancel the handleAsyncUpdate() callback.
  9112. */
  9113. void cancelPendingUpdate() throw();
  9114. /** If an update has been triggered and is pending, this will invoke it
  9115. synchronously.
  9116. Use this as a kind of "flush" operation - if an update is pending, the
  9117. handleAsyncUpdate() method will be called immediately; if no update is
  9118. pending, then nothing will be done.
  9119. */
  9120. void handleUpdateNowIfNeeded();
  9121. /** Called back to do whatever your class needs to do.
  9122. This method is called by the message thread at the next convenient time
  9123. after the triggerAsyncUpdate() method has been called.
  9124. */
  9125. virtual void handleAsyncUpdate() = 0;
  9126. private:
  9127. class AsyncUpdaterInternal : public MessageListener
  9128. {
  9129. public:
  9130. AsyncUpdaterInternal() throw() {}
  9131. ~AsyncUpdaterInternal() {}
  9132. void handleMessage (const Message&);
  9133. AsyncUpdater* owner;
  9134. private:
  9135. AsyncUpdaterInternal (const AsyncUpdaterInternal&);
  9136. AsyncUpdaterInternal& operator= (const AsyncUpdaterInternal&);
  9137. };
  9138. AsyncUpdaterInternal internalAsyncHandler;
  9139. bool asyncMessagePending;
  9140. };
  9141. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  9142. /*** End of inlined file: juce_AsyncUpdater.h ***/
  9143. /*** Start of inlined file: juce_ListenerList.h ***/
  9144. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  9145. #define __JUCE_LISTENERLIST_JUCEHEADER__
  9146. /**
  9147. Holds a set of objects and can invoke a member function callback on each object
  9148. in the set with a single call.
  9149. Use a ListenerList to manage a set of objects which need a callback, and you
  9150. can invoke a member function by simply calling call() or callChecked().
  9151. E.g.
  9152. @code
  9153. class MyListenerType
  9154. {
  9155. public:
  9156. void myCallbackMethod (int foo, bool bar);
  9157. };
  9158. ListenerList <MyListenerType> listeners;
  9159. listeners.add (someCallbackObjects...);
  9160. // This will invoke myCallbackMethod (1234, true) on each of the objects
  9161. // in the list...
  9162. listeners.call (&MyListenerType::myCallbackMethod, 1234, true);
  9163. @endcode
  9164. If you add or remove listeners from the list during one of the callbacks - i.e. while
  9165. it's in the middle of iterating the listeners, then it's guaranteed that no listeners
  9166. will be mistakenly called after they've been removed, but it may mean that some of the
  9167. listeners could be called more than once, or not at all, depending on the list's order.
  9168. Sometimes, there's a chance that invoking one of the callbacks might result in the
  9169. list itself being deleted while it's still iterating - to survive this situation, you can
  9170. use callChecked() instead of call(), passing it a local object to act as a "BailOutChecker".
  9171. The BailOutChecker must implement a method of the form "bool shouldBailOut()", and
  9172. the list will check this after each callback to determine whether it should abort the
  9173. operation. For an example of a bail-out checker, see the Component::BailOutChecker class,
  9174. which can be used to check when a Component has been deleted. See also
  9175. ListenerList::DummyBailOutChecker, which is a dummy checker that always returns false.
  9176. */
  9177. template <class ListenerClass,
  9178. class ArrayType = Array <ListenerClass*> >
  9179. class ListenerList
  9180. {
  9181. // Horrible macros required to support VC6/7..
  9182. #if defined (_MSC_VER) && _MSC_VER <= 1400
  9183. #define LL_TEMPLATE(a) typename P##a, typename Q##a
  9184. #define LL_PARAM(a) Q##a& param##a
  9185. #else
  9186. #define LL_TEMPLATE(a) typename P##a
  9187. #define LL_PARAM(a) PARAMETER_TYPE(P##a) param##a
  9188. #endif
  9189. public:
  9190. /** Creates an empty list. */
  9191. ListenerList()
  9192. {
  9193. }
  9194. /** Destructor. */
  9195. ~ListenerList()
  9196. {
  9197. }
  9198. /** Adds a listener to the list.
  9199. A listener can only be added once, so if the listener is already in the list,
  9200. this method has no effect.
  9201. @see remove
  9202. */
  9203. void add (ListenerClass* const listenerToAdd)
  9204. {
  9205. // Listeners can't be null pointers!
  9206. jassert (listenerToAdd != 0);
  9207. if (listenerToAdd != 0)
  9208. listeners.addIfNotAlreadyThere (listenerToAdd);
  9209. }
  9210. /** Removes a listener from the list.
  9211. If the listener wasn't in the list, this has no effect.
  9212. */
  9213. void remove (ListenerClass* const listenerToRemove)
  9214. {
  9215. // Listeners can't be null pointers!
  9216. jassert (listenerToRemove != 0);
  9217. listeners.removeValue (listenerToRemove);
  9218. }
  9219. /** Returns the number of registered listeners. */
  9220. int size() const throw()
  9221. {
  9222. return listeners.size();
  9223. }
  9224. /** Returns true if any listeners are registered. */
  9225. bool isEmpty() const throw()
  9226. {
  9227. return listeners.size() == 0;
  9228. }
  9229. /** Returns true if the specified listener has been added to the list. */
  9230. bool contains (ListenerClass* const listener) const throw()
  9231. {
  9232. return listeners.contains (listener);
  9233. }
  9234. /** Calls a member function on each listener in the list, with no parameters. */
  9235. void call (void (ListenerClass::*callbackFunction) ())
  9236. {
  9237. callChecked (static_cast <const DummyBailOutChecker&> (DummyBailOutChecker()), callbackFunction);
  9238. }
  9239. /** Calls a member function on each listener in the list, with no parameters and a bail-out-checker.
  9240. See the class description for info about writing a bail-out checker. */
  9241. template <class BailOutCheckerType>
  9242. void callChecked (const BailOutCheckerType& bailOutChecker,
  9243. void (ListenerClass::*callbackFunction) ())
  9244. {
  9245. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9246. (iter.getListener()->*callbackFunction) ();
  9247. }
  9248. /** Calls a member function on each listener in the list, with 1 parameter. */
  9249. template <LL_TEMPLATE(1)>
  9250. void call (void (ListenerClass::*callbackFunction) (P1), LL_PARAM(1))
  9251. {
  9252. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9253. (iter.getListener()->*callbackFunction) (param1);
  9254. }
  9255. /** Calls a member function on each listener in the list, with one parameter and a bail-out-checker.
  9256. See the class description for info about writing a bail-out checker. */
  9257. template <class BailOutCheckerType, LL_TEMPLATE(1)>
  9258. void callChecked (const BailOutCheckerType& bailOutChecker,
  9259. void (ListenerClass::*callbackFunction) (P1),
  9260. LL_PARAM(1))
  9261. {
  9262. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9263. (iter.getListener()->*callbackFunction) (param1);
  9264. }
  9265. /** Calls a member function on each listener in the list, with 2 parameters. */
  9266. template <LL_TEMPLATE(1), LL_TEMPLATE(2)>
  9267. void call (void (ListenerClass::*callbackFunction) (P1, P2),
  9268. LL_PARAM(1), LL_PARAM(2))
  9269. {
  9270. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9271. (iter.getListener()->*callbackFunction) (param1, param2);
  9272. }
  9273. /** Calls a member function on each listener in the list, with 2 parameters and a bail-out-checker.
  9274. See the class description for info about writing a bail-out checker. */
  9275. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2)>
  9276. void callChecked (const BailOutCheckerType& bailOutChecker,
  9277. void (ListenerClass::*callbackFunction) (P1, P2),
  9278. LL_PARAM(1), LL_PARAM(2))
  9279. {
  9280. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9281. (iter.getListener()->*callbackFunction) (param1, param2);
  9282. }
  9283. /** Calls a member function on each listener in the list, with 3 parameters. */
  9284. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  9285. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3),
  9286. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  9287. {
  9288. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9289. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  9290. }
  9291. /** Calls a member function on each listener in the list, with 3 parameters and a bail-out-checker.
  9292. See the class description for info about writing a bail-out checker. */
  9293. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  9294. void callChecked (const BailOutCheckerType& bailOutChecker,
  9295. void (ListenerClass::*callbackFunction) (P1, P2, P3),
  9296. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  9297. {
  9298. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9299. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  9300. }
  9301. /** Calls a member function on each listener in the list, with 4 parameters. */
  9302. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  9303. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  9304. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  9305. {
  9306. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9307. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  9308. }
  9309. /** Calls a member function on each listener in the list, with 4 parameters and a bail-out-checker.
  9310. See the class description for info about writing a bail-out checker. */
  9311. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  9312. void callChecked (const BailOutCheckerType& bailOutChecker,
  9313. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  9314. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  9315. {
  9316. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9317. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  9318. }
  9319. /** Calls a member function on each listener in the list, with 5 parameters. */
  9320. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  9321. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  9322. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  9323. {
  9324. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9325. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  9326. }
  9327. /** Calls a member function on each listener in the list, with 5 parameters and a bail-out-checker.
  9328. See the class description for info about writing a bail-out checker. */
  9329. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  9330. void callChecked (const BailOutCheckerType& bailOutChecker,
  9331. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  9332. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  9333. {
  9334. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9335. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  9336. }
  9337. /** A dummy bail-out checker that always returns false.
  9338. See the ListenerList notes for more info about bail-out checkers.
  9339. */
  9340. class DummyBailOutChecker
  9341. {
  9342. public:
  9343. inline bool shouldBailOut() const throw() { return false; }
  9344. };
  9345. /** Iterates the listeners in a ListenerList. */
  9346. template <class BailOutCheckerType, class ListType>
  9347. class Iterator
  9348. {
  9349. public:
  9350. Iterator (const ListType& list_, const BailOutCheckerType& bailOutChecker_)
  9351. : list (list_), bailOutChecker (bailOutChecker_), index (list_.size())
  9352. {}
  9353. ~Iterator() {}
  9354. bool next()
  9355. {
  9356. if (index <= 0 || bailOutChecker.shouldBailOut())
  9357. return false;
  9358. const int listSize = list.size();
  9359. if (--index < listSize)
  9360. return true;
  9361. index = listSize - 1;
  9362. return index >= 0;
  9363. }
  9364. typename ListType::ListenerType* getListener() const throw()
  9365. {
  9366. return list.getListeners().getUnchecked (index);
  9367. }
  9368. private:
  9369. const ListType& list;
  9370. const BailOutCheckerType& bailOutChecker;
  9371. int index;
  9372. Iterator (const Iterator&);
  9373. Iterator& operator= (const Iterator&);
  9374. };
  9375. typedef ListenerList<ListenerClass, ArrayType> ThisType;
  9376. typedef ListenerClass ListenerType;
  9377. const ArrayType& getListeners() const throw() { return listeners; }
  9378. private:
  9379. ArrayType listeners;
  9380. ListenerList (const ListenerList&);
  9381. ListenerList& operator= (const ListenerList&);
  9382. #undef LL_TEMPLATE
  9383. #undef LL_PARAM
  9384. };
  9385. #endif // __JUCE_LISTENERLIST_JUCEHEADER__
  9386. /*** End of inlined file: juce_ListenerList.h ***/
  9387. /**
  9388. Represents a shared variant value.
  9389. A Value object contains a reference to a var object, and can get and set its value.
  9390. Listeners can be attached to be told when the value is changed.
  9391. The Value class is a wrapper around a shared, reference-counted underlying data
  9392. object - this means that multiple Value objects can all refer to the same piece of
  9393. data, allowing all of them to be notified when any of them changes it.
  9394. When you create a Value with its default constructor, it acts as a wrapper around a
  9395. simple var object, but by creating a Value that refers to a custom subclass of ValueSource,
  9396. you can map the Value onto any kind of underlying data.
  9397. */
  9398. class JUCE_API Value
  9399. {
  9400. public:
  9401. /** Creates an empty Value, containing a void var. */
  9402. Value();
  9403. /** Creates a Value that refers to the same value as another one.
  9404. Note that this doesn't make a copy of the other value - both this and the other
  9405. Value will share the same underlying value, so that when either one alters it, both
  9406. will see it change.
  9407. */
  9408. Value (const Value& other);
  9409. /** Creates a Value that is set to the specified value. */
  9410. explicit Value (const var& initialValue);
  9411. /** Destructor. */
  9412. ~Value();
  9413. /** Returns the current value. */
  9414. const var getValue() const;
  9415. /** Returns the current value. */
  9416. operator const var() const;
  9417. /** Returns the value as a string.
  9418. This is alternative to writing things like "myValue.getValue().toString()".
  9419. */
  9420. const String toString() const;
  9421. /** Sets the current value.
  9422. You can also use operator= to set the value.
  9423. If there are any listeners registered, they will be notified of the
  9424. change asynchronously.
  9425. */
  9426. void setValue (const var& newValue);
  9427. /** Sets the current value.
  9428. This is the same as calling setValue().
  9429. If there are any listeners registered, they will be notified of the
  9430. change asynchronously.
  9431. */
  9432. Value& operator= (const var& newValue);
  9433. /** Makes this object refer to the same underlying ValueSource as another one.
  9434. Once this object has been connected to another one, changing either one
  9435. will update the other.
  9436. Existing listeners will still be registered after you call this method, and
  9437. they'll continue to receive messages when the new value changes.
  9438. */
  9439. void referTo (const Value& valueToReferTo);
  9440. /** Returns true if this value and the other one are references to the same value.
  9441. */
  9442. bool refersToSameSourceAs (const Value& other) const;
  9443. /** Compares two values.
  9444. This is a compare-by-value comparison, so is effectively the same as
  9445. saying (this->getValue() == other.getValue()).
  9446. */
  9447. bool operator== (const Value& other) const;
  9448. /** Compares two values.
  9449. This is a compare-by-value comparison, so is effectively the same as
  9450. saying (this->getValue() != other.getValue()).
  9451. */
  9452. bool operator!= (const Value& other) const;
  9453. /** Receives callbacks when a Value object changes.
  9454. @see Value::addListener
  9455. */
  9456. class JUCE_API Listener
  9457. {
  9458. public:
  9459. Listener() {}
  9460. virtual ~Listener() {}
  9461. /** Called when a Value object is changed.
  9462. Note that the Value object passed as a parameter may not be exactly the same
  9463. object that you registered the listener with - it might be a copy that refers
  9464. to the same underlying ValueSource. To find out, you can call Value::refersToSameSourceAs().
  9465. */
  9466. virtual void valueChanged (Value& value) = 0;
  9467. };
  9468. /** Adds a listener to receive callbacks when the value changes.
  9469. The listener is added to this specific Value object, and not to the shared
  9470. object that it refers to. When this object is deleted, all the listeners will
  9471. be lost, even if other references to the same Value still exist. So when you're
  9472. adding a listener, make sure that you add it to a ValueTree instance that will last
  9473. for as long as you need the listener. In general, you'd never want to add a listener
  9474. to a local stack-based ValueTree, but more likely to one that's a member variable.
  9475. @see removeListener
  9476. */
  9477. void addListener (Listener* listener);
  9478. /** Removes a listener that was previously added with addListener(). */
  9479. void removeListener (Listener* listener);
  9480. /**
  9481. Used internally by the Value class as the base class for its shared value objects.
  9482. The Value class is essentially a reference-counted pointer to a shared instance
  9483. of a ValueSource object. If you're feeling adventurous, you can create your own custom
  9484. ValueSource classes to allow Value objects to represent your own custom data items.
  9485. */
  9486. class JUCE_API ValueSource : public ReferenceCountedObject,
  9487. public AsyncUpdater
  9488. {
  9489. public:
  9490. ValueSource();
  9491. virtual ~ValueSource();
  9492. /** Returns the current value of this object. */
  9493. virtual const var getValue() const = 0;
  9494. /** Changes the current value.
  9495. This must also trigger a change message if the value actually changes.
  9496. */
  9497. virtual void setValue (const var& newValue) = 0;
  9498. /** Delivers a change message to all the listeners that are registered with
  9499. this value.
  9500. If dispatchSynchronously is true, the method will call all the listeners
  9501. before returning; otherwise it'll dispatch a message and make the call later.
  9502. */
  9503. void sendChangeMessage (bool dispatchSynchronously);
  9504. juce_UseDebuggingNewOperator
  9505. protected:
  9506. friend class Value;
  9507. SortedSet <Value*> valuesWithListeners;
  9508. void handleAsyncUpdate();
  9509. ValueSource (const ValueSource&);
  9510. ValueSource& operator= (const ValueSource&);
  9511. };
  9512. /** Creates a Value object that uses this valueSource object as its underlying data. */
  9513. explicit Value (ValueSource* valueSource);
  9514. /** Returns the ValueSource that this value is referring to. */
  9515. ValueSource& getValueSource() throw() { return *value; }
  9516. juce_UseDebuggingNewOperator
  9517. private:
  9518. friend class ValueSource;
  9519. ReferenceCountedObjectPtr <ValueSource> value;
  9520. ListenerList <Listener> listeners;
  9521. void callListeners();
  9522. // This is disallowed to avoid confusion about whether it should
  9523. // do a by-value or by-reference copy.
  9524. Value& operator= (const Value& other);
  9525. };
  9526. /** Writes a Value to an OutputStream as a UTF8 string. */
  9527. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value);
  9528. #endif // __JUCE_VALUE_JUCEHEADER__
  9529. /*** End of inlined file: juce_Value.h ***/
  9530. #endif
  9531. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  9532. /*** Start of inlined file: juce_ValueTree.h ***/
  9533. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  9534. #define __JUCE_VALUETREE_JUCEHEADER__
  9535. /*** Start of inlined file: juce_UndoManager.h ***/
  9536. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  9537. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  9538. /*** Start of inlined file: juce_ChangeBroadcaster.h ***/
  9539. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9540. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9541. /*** Start of inlined file: juce_ChangeListenerList.h ***/
  9542. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9543. #define __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9544. /*** Start of inlined file: juce_ChangeListener.h ***/
  9545. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  9546. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  9547. /**
  9548. Receives callbacks about changes to some kind of object.
  9549. Many objects use a ChangeListenerList to keep a set of listeners which they
  9550. will inform when something changes. A subclass of ChangeListener
  9551. is used to receive these callbacks.
  9552. Note that the major difference between an ActionListener and a ChangeListener
  9553. is that for a ChangeListener, multiple changes will be coalesced into fewer
  9554. callbacks, but ActionListeners perform one callback for every event posted.
  9555. @see ChangeListenerList, ChangeBroadcaster, ActionListener
  9556. */
  9557. class JUCE_API ChangeListener
  9558. {
  9559. public:
  9560. /** Destructor. */
  9561. virtual ~ChangeListener() {}
  9562. /** Overridden by your subclass to receive the callback.
  9563. @param objectThatHasChanged the value that was passed to the
  9564. ChangeListenerList::sendChangeMessage() method
  9565. */
  9566. virtual void changeListenerCallback (void* objectThatHasChanged) = 0;
  9567. };
  9568. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  9569. /*** End of inlined file: juce_ChangeListener.h ***/
  9570. /*** Start of inlined file: juce_ScopedLock.h ***/
  9571. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  9572. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  9573. /**
  9574. Automatically locks and unlocks a CriticalSection object.
  9575. Use one of these as a local variable to control access to a CriticalSection.
  9576. e.g. @code
  9577. CriticalSection myCriticalSection;
  9578. for (;;)
  9579. {
  9580. const ScopedLock myScopedLock (myCriticalSection);
  9581. // myCriticalSection is now locked
  9582. ...do some stuff...
  9583. // myCriticalSection gets unlocked here.
  9584. }
  9585. @endcode
  9586. @see CriticalSection, ScopedUnlock
  9587. */
  9588. class JUCE_API ScopedLock
  9589. {
  9590. public:
  9591. /** Creates a ScopedLock.
  9592. As soon as it is created, this will lock the CriticalSection, and
  9593. when the ScopedLock object is deleted, the CriticalSection will
  9594. be unlocked.
  9595. Make sure this object is created and deleted by the same thread,
  9596. otherwise there are no guarantees what will happen! Best just to use it
  9597. as a local stack object, rather than creating one with the new() operator.
  9598. */
  9599. inline explicit ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  9600. /** Destructor.
  9601. The CriticalSection will be unlocked when the destructor is called.
  9602. Make sure this object is created and deleted by the same thread,
  9603. otherwise there are no guarantees what will happen!
  9604. */
  9605. inline ~ScopedLock() throw() { lock_.exit(); }
  9606. private:
  9607. const CriticalSection& lock_;
  9608. ScopedLock (const ScopedLock&);
  9609. ScopedLock& operator= (const ScopedLock&);
  9610. };
  9611. /**
  9612. Automatically unlocks and re-locks a CriticalSection object.
  9613. This is the reverse of a ScopedLock object - instead of locking the critical
  9614. section for the lifetime of this object, it unlocks it.
  9615. Make sure you don't try to unlock critical sections that aren't actually locked!
  9616. e.g. @code
  9617. CriticalSection myCriticalSection;
  9618. for (;;)
  9619. {
  9620. const ScopedLock myScopedLock (myCriticalSection);
  9621. // myCriticalSection is now locked
  9622. ... do some stuff with it locked ..
  9623. while (xyz)
  9624. {
  9625. ... do some stuff with it locked ..
  9626. const ScopedUnlock unlocker (myCriticalSection);
  9627. // myCriticalSection is now unlocked for the remainder of this block,
  9628. // and re-locked at the end.
  9629. ...do some stuff with it unlocked ...
  9630. }
  9631. // myCriticalSection gets unlocked here.
  9632. }
  9633. @endcode
  9634. @see CriticalSection, ScopedLock
  9635. */
  9636. class ScopedUnlock
  9637. {
  9638. public:
  9639. /** Creates a ScopedUnlock.
  9640. As soon as it is created, this will unlock the CriticalSection, and
  9641. when the ScopedLock object is deleted, the CriticalSection will
  9642. be re-locked.
  9643. Make sure this object is created and deleted by the same thread,
  9644. otherwise there are no guarantees what will happen! Best just to use it
  9645. as a local stack object, rather than creating one with the new() operator.
  9646. */
  9647. inline explicit ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  9648. /** Destructor.
  9649. The CriticalSection will be unlocked when the destructor is called.
  9650. Make sure this object is created and deleted by the same thread,
  9651. otherwise there are no guarantees what will happen!
  9652. */
  9653. inline ~ScopedUnlock() throw() { lock_.enter(); }
  9654. private:
  9655. const CriticalSection& lock_;
  9656. ScopedUnlock (const ScopedLock&);
  9657. ScopedUnlock& operator= (const ScopedUnlock&);
  9658. };
  9659. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  9660. /*** End of inlined file: juce_ScopedLock.h ***/
  9661. /**
  9662. A set of ChangeListeners.
  9663. Listeners can be added and removed from the list, and change messages can be
  9664. broadcast to all the listeners.
  9665. @see ChangeListener, ChangeBroadcaster
  9666. */
  9667. class JUCE_API ChangeListenerList : public MessageListener
  9668. {
  9669. public:
  9670. /** Creates an empty list. */
  9671. ChangeListenerList() throw();
  9672. /** Destructor. */
  9673. ~ChangeListenerList() throw();
  9674. /** Adds a listener to the list.
  9675. (Trying to add a listener that's already on the list will have no effect).
  9676. */
  9677. void addChangeListener (ChangeListener* listener) throw();
  9678. /** Removes a listener from the list.
  9679. If the listener isn't on the list, this won't have any effect.
  9680. */
  9681. void removeChangeListener (ChangeListener* listener) throw();
  9682. /** Removes all listeners from the list. */
  9683. void removeAllChangeListeners() throw();
  9684. /** Posts an asynchronous change message to all the listeners.
  9685. If a message has already been sent and hasn't yet been delivered, this
  9686. method won't send another - in this way it coalesces multiple frequent
  9687. changes into fewer actual callbacks to the ChangeListeners. Contrast this
  9688. with the ActionListener, which posts a new event for every call to its
  9689. sendActionMessage() method.
  9690. Only listeners which are on the list when the change event is delivered
  9691. will receive the event - and this may include listeners that weren't on
  9692. the list when the change message was sent.
  9693. @param objectThatHasChanged this pointer is passed to the
  9694. ChangeListener::changeListenerCallback() method,
  9695. and can be any value the application needs
  9696. @see sendSynchronousChangeMessage
  9697. */
  9698. void sendChangeMessage (void* objectThatHasChanged) throw();
  9699. /** This will synchronously callback all the ChangeListeners.
  9700. Use this if you need to synchronously force a call to all the
  9701. listeners' ChangeListener::changeListenerCallback() methods.
  9702. */
  9703. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  9704. /** If a change message has been sent but not yet dispatched, this will
  9705. use sendSynchronousChangeMessage() to make the callback immediately.
  9706. */
  9707. void dispatchPendingMessages();
  9708. /** @internal */
  9709. void handleMessage (const Message&);
  9710. juce_UseDebuggingNewOperator
  9711. private:
  9712. SortedSet <void*> listeners;
  9713. CriticalSection lock;
  9714. void* lastChangedObject;
  9715. bool messagePending;
  9716. ChangeListenerList (const ChangeListenerList&);
  9717. ChangeListenerList& operator= (const ChangeListenerList&);
  9718. };
  9719. #endif // __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9720. /*** End of inlined file: juce_ChangeListenerList.h ***/
  9721. /** Manages a list of ChangeListeners, and can send them messages.
  9722. To quickly add methods to your class that can add/remove change
  9723. listeners and broadcast to them, you can derive from this.
  9724. @see ChangeListenerList, ChangeListener
  9725. */
  9726. class JUCE_API ChangeBroadcaster
  9727. {
  9728. public:
  9729. /** Creates an ChangeBroadcaster. */
  9730. ChangeBroadcaster() throw();
  9731. /** Destructor. */
  9732. virtual ~ChangeBroadcaster();
  9733. /** Adds a listener to the list.
  9734. (Trying to add a listener that's already on the list will have no effect).
  9735. */
  9736. void addChangeListener (ChangeListener* listener) throw();
  9737. /** Removes a listener from the list.
  9738. If the listener isn't on the list, this won't have any effect.
  9739. */
  9740. void removeChangeListener (ChangeListener* listener) throw();
  9741. /** Removes all listeners from the list. */
  9742. void removeAllChangeListeners() throw();
  9743. /** Broadcasts a change message to all the registered listeners.
  9744. The message will be delivered asynchronously by the event thread, so this
  9745. method will not directly call any of the listeners. For a synchronous
  9746. message, use sendSynchronousChangeMessage().
  9747. @see ChangeListenerList::sendActionMessage
  9748. */
  9749. void sendChangeMessage (void* objectThatHasChanged) throw();
  9750. /** Sends a synchronous change message to all the registered listeners.
  9751. @see ChangeListenerList::sendSynchronousChangeMessage
  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. private:
  9759. ChangeListenerList changeListenerList;
  9760. ChangeBroadcaster (const ChangeBroadcaster&);
  9761. ChangeBroadcaster& operator= (const ChangeBroadcaster&);
  9762. };
  9763. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9764. /*** End of inlined file: juce_ChangeBroadcaster.h ***/
  9765. /*** Start of inlined file: juce_UndoableAction.h ***/
  9766. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  9767. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  9768. /**
  9769. Used by the UndoManager class to store an action which can be done
  9770. and undone.
  9771. @see UndoManager
  9772. */
  9773. class JUCE_API UndoableAction
  9774. {
  9775. protected:
  9776. /** Creates an action. */
  9777. UndoableAction() throw() {}
  9778. public:
  9779. /** Destructor. */
  9780. virtual ~UndoableAction() {}
  9781. /** Overridden by a subclass to perform the action.
  9782. This method is called by the UndoManager, and shouldn't be used directly by
  9783. applications.
  9784. Be careful not to make any calls in a perform() method that could call
  9785. recursively back into the UndoManager::perform() method
  9786. @returns true if the action could be performed.
  9787. @see UndoManager::perform
  9788. */
  9789. virtual bool perform() = 0;
  9790. /** Overridden by a subclass to undo the action.
  9791. This method is called by the UndoManager, and shouldn't be used directly by
  9792. applications.
  9793. Be careful not to make any calls in an undo() method that could call
  9794. recursively back into the UndoManager::perform() method
  9795. @returns true if the action could be undone without any errors.
  9796. @see UndoManager::perform
  9797. */
  9798. virtual bool undo() = 0;
  9799. /** Returns a value to indicate how much memory this object takes up.
  9800. Because the UndoManager keeps a list of UndoableActions, this is used
  9801. to work out how much space each one will take up, so that the UndoManager
  9802. can work out how many to keep.
  9803. The default value returned here is 10 - units are arbitrary and
  9804. don't have to be accurate.
  9805. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  9806. UndoManager::setMaxNumberOfStoredUnits
  9807. */
  9808. virtual int getSizeInUnits() { return 10; }
  9809. /** Allows multiple actions to be coalesced into a single action object, to reduce storage space.
  9810. If possible, this method should create and return a single action that does the same job as
  9811. this one followed by the supplied action.
  9812. If it's not possible to merge the two actions, the method should return zero.
  9813. */
  9814. virtual UndoableAction* createCoalescedAction (UndoableAction* nextAction) { (void) nextAction; return 0; }
  9815. };
  9816. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  9817. /*** End of inlined file: juce_UndoableAction.h ***/
  9818. /**
  9819. Manages a list of undo/redo commands.
  9820. An UndoManager object keeps a list of past actions and can use these actions
  9821. to move backwards and forwards through an undo history.
  9822. To use it, create subclasses of UndoableAction which perform all the
  9823. actions you need, then when you need to actually perform an action, create one
  9824. and pass it to the UndoManager's perform() method.
  9825. The manager also uses the concept of 'transactions' to group the actions
  9826. together - all actions performed between calls to beginNewTransaction() are
  9827. grouped together and are all undone/redone as a group.
  9828. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  9829. when actions are performed or undone.
  9830. @see UndoableAction
  9831. */
  9832. class JUCE_API UndoManager : public ChangeBroadcaster
  9833. {
  9834. public:
  9835. /** Creates an UndoManager.
  9836. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  9837. to indicate how much storage it takes up
  9838. (UndoableAction::getSizeInUnits()), so this
  9839. lets you specify the maximum total number of
  9840. units that the undomanager is allowed to
  9841. keep in memory before letting the older actions
  9842. drop off the end of the list.
  9843. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  9844. that will be kept, even if this involves exceeding
  9845. the amount of space specified in maxNumberOfUnitsToKeep
  9846. */
  9847. UndoManager (int maxNumberOfUnitsToKeep = 30000,
  9848. int minimumTransactionsToKeep = 30);
  9849. /** Destructor. */
  9850. ~UndoManager();
  9851. /** Deletes all stored actions in the list. */
  9852. void clearUndoHistory();
  9853. /** Returns the current amount of space to use for storing UndoableAction objects.
  9854. @see setMaxNumberOfStoredUnits
  9855. */
  9856. int getNumberOfUnitsTakenUpByStoredCommands() const;
  9857. /** Sets the amount of space that can be used for storing UndoableAction objects.
  9858. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  9859. to indicate how much storage it takes up
  9860. (UndoableAction::getSizeInUnits()), so this
  9861. lets you specify the maximum total number of
  9862. units that the undomanager is allowed to
  9863. keep in memory before letting the older actions
  9864. drop off the end of the list.
  9865. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  9866. that will be kept, even if this involves exceeding
  9867. the amount of space specified in maxNumberOfUnitsToKeep
  9868. @see getNumberOfUnitsTakenUpByStoredCommands
  9869. */
  9870. void setMaxNumberOfStoredUnits (int maxNumberOfUnitsToKeep,
  9871. int minimumTransactionsToKeep);
  9872. /** Performs an action and adds it to the undo history list.
  9873. @param action the action to perform - this will be deleted by the UndoManager
  9874. when no longer needed
  9875. @param actionName if this string is non-empty, the current transaction will be
  9876. given this name; if it's empty, the current transaction name will
  9877. be left unchanged. See setCurrentTransactionName()
  9878. @returns true if the command succeeds - see UndoableAction::perform
  9879. @see beginNewTransaction
  9880. */
  9881. bool perform (UndoableAction* action,
  9882. const String& actionName = String::empty);
  9883. /** Starts a new group of actions that together will be treated as a single transaction.
  9884. All actions that are passed to the perform() method between calls to this
  9885. method are grouped together and undone/redone together by a single call to
  9886. undo() or redo().
  9887. @param actionName a description of the transaction that is about to be
  9888. performed
  9889. */
  9890. void beginNewTransaction (const String& actionName = String::empty);
  9891. /** Changes the name stored for the current transaction.
  9892. Each transaction is given a name when the beginNewTransaction() method is
  9893. called, but this can be used to change that name without starting a new
  9894. transaction.
  9895. */
  9896. void setCurrentTransactionName (const String& newName);
  9897. /** Returns true if there's at least one action in the list to undo.
  9898. @see getUndoDescription, undo, canRedo
  9899. */
  9900. bool canUndo() const;
  9901. /** Returns the description of the transaction that would be next to get undone.
  9902. The description returned is the one that was passed into beginNewTransaction
  9903. before the set of actions was performed.
  9904. @see undo
  9905. */
  9906. const String getUndoDescription() const;
  9907. /** Tries to roll-back the last transaction.
  9908. @returns true if the transaction can be undone, and false if it fails, or
  9909. if there aren't any transactions to undo
  9910. */
  9911. bool undo();
  9912. /** Tries to roll-back any actions that were added to the current transaction.
  9913. This will perform an undo() only if there are some actions in the undo list
  9914. that were added after the last call to beginNewTransaction().
  9915. This is useful because it lets you call beginNewTransaction(), then
  9916. perform an operation which may or may not actually perform some actions, and
  9917. then call this method to get rid of any actions that might have been done
  9918. without it rolling back the previous transaction if nothing was actually
  9919. done.
  9920. @returns true if any actions were undone.
  9921. */
  9922. bool undoCurrentTransactionOnly();
  9923. /** Returns a list of the UndoableAction objects that have been performed during the
  9924. transaction that is currently open.
  9925. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  9926. were to be called now.
  9927. The first item in the list is the earliest action performed.
  9928. */
  9929. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  9930. /** Returns the number of UndoableAction objects that have been performed during the
  9931. transaction that is currently open.
  9932. @see getActionsInCurrentTransaction
  9933. */
  9934. int getNumActionsInCurrentTransaction() const;
  9935. /** Returns true if there's at least one action in the list to redo.
  9936. @see getRedoDescription, redo, canUndo
  9937. */
  9938. bool canRedo() const;
  9939. /** Returns the description of the transaction that would be next to get redone.
  9940. The description returned is the one that was passed into beginNewTransaction
  9941. before the set of actions was performed.
  9942. @see redo
  9943. */
  9944. const String getRedoDescription() const;
  9945. /** Tries to redo the last transaction that was undone.
  9946. @returns true if the transaction can be redone, and false if it fails, or
  9947. if there aren't any transactions to redo
  9948. */
  9949. bool redo();
  9950. juce_UseDebuggingNewOperator
  9951. private:
  9952. OwnedArray <OwnedArray <UndoableAction> > transactions;
  9953. StringArray transactionNames;
  9954. String currentTransactionName;
  9955. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  9956. bool newTransaction, reentrancyCheck;
  9957. // disallow copy constructor
  9958. UndoManager (const UndoManager&);
  9959. UndoManager& operator= (const UndoManager&);
  9960. };
  9961. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  9962. /*** End of inlined file: juce_UndoManager.h ***/
  9963. /**
  9964. A powerful tree structure that can be used to hold free-form data, and which can
  9965. handle its own undo and redo behaviour.
  9966. A ValueTree contains a list of named properties as var objects, and also holds
  9967. any number of sub-trees.
  9968. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  9969. they're simply a lightweight reference to a shared data container. Creating a copy
  9970. of another ValueTree simply creates a new reference to the same underlying object - to
  9971. make a separate, deep copy of a tree you should explicitly call createCopy().
  9972. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  9973. and much of the structure of a ValueTree is similar to an XmlElement tree.
  9974. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  9975. contain text elements, the conversion works well and makes a good serialisation
  9976. format. They can also be serialised to a binary format, which is very fast and compact.
  9977. All the methods that change data take an optional UndoManager, which will be used
  9978. to track any changes to the object. For this to work, you have to be careful to
  9979. consistently always use the same UndoManager for all operations to any node inside
  9980. the tree.
  9981. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  9982. one tree to another, be careful to always remove it first, before adding it. This
  9983. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  9984. assertions if you try to do anything dangerous, but there are still plenty of ways it
  9985. could go wrong.
  9986. Listeners can be added to a ValueTree to be told when properies change and when
  9987. nodes are added or removed.
  9988. @see var, XmlElement
  9989. */
  9990. class JUCE_API ValueTree
  9991. {
  9992. public:
  9993. /** Creates an empty, invalid ValueTree.
  9994. A ValueTree that is created with this constructor can't actually be used for anything,
  9995. it's just a default 'null' ValueTree that can be returned to indicate some sort of failure.
  9996. To create a real one, use the constructor that takes a string.
  9997. @see ValueTree::invalid
  9998. */
  9999. ValueTree() throw();
  10000. /** Creates an empty ValueTree with the given type name.
  10001. Like an XmlElement, each ValueTree node has a type, which you can access with
  10002. getType() and hasType().
  10003. */
  10004. explicit ValueTree (const Identifier& type);
  10005. /** Creates a reference to another ValueTree. */
  10006. ValueTree (const ValueTree& other);
  10007. /** Makes this object reference another node. */
  10008. ValueTree& operator= (const ValueTree& other);
  10009. /** Destructor. */
  10010. ~ValueTree();
  10011. /** Returns true if both this and the other tree node refer to the same underlying structure.
  10012. Note that this isn't a value comparison - two independently-created trees which
  10013. contain identical data are not considered equal.
  10014. */
  10015. bool operator== (const ValueTree& other) const throw();
  10016. /** Returns true if this and the other node refer to different underlying structures.
  10017. Note that this isn't a value comparison - two independently-created trees which
  10018. contain identical data are not considered equal.
  10019. */
  10020. bool operator!= (const ValueTree& other) const throw();
  10021. /** Performs a deep comparison between the properties and children of two trees.
  10022. If all the properties and children of the two trees are the same (recursively), this
  10023. returns true.
  10024. The normal operator==() only checks whether two trees refer to the same shared data
  10025. structure, so use this method if you need to do a proper value comparison.
  10026. */
  10027. bool isEquivalentTo (const ValueTree& other) const;
  10028. /** Returns true if this node refers to some valid data.
  10029. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  10030. call to getChild().
  10031. */
  10032. bool isValid() const { return object != 0; }
  10033. /** Returns a deep copy of this tree and all its sub-nodes. */
  10034. ValueTree createCopy() const;
  10035. /** Returns the type of this node.
  10036. The type is specified when the ValueTree is created.
  10037. @see hasType
  10038. */
  10039. const Identifier getType() const;
  10040. /** Returns true if the node has this type.
  10041. The comparison is case-sensitive.
  10042. */
  10043. bool hasType (const Identifier& typeName) const;
  10044. /** Returns the value of a named property.
  10045. If no such property has been set, this will return a void variant.
  10046. You can also use operator[] to get a property.
  10047. @see var, setProperty, hasProperty
  10048. */
  10049. const var& getProperty (const Identifier& name) const;
  10050. /** Returns the value of a named property, or a user-specified default if the property doesn't exist.
  10051. If no such property has been set, this will return the value of defaultReturnValue.
  10052. You can also use operator[] and getProperty to get a property.
  10053. @see var, getProperty, setProperty, hasProperty
  10054. */
  10055. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  10056. /** Returns the value of a named property.
  10057. If no such property has been set, this will return a void variant. This is the same as
  10058. calling getProperty().
  10059. @see getProperty
  10060. */
  10061. const var& operator[] (const Identifier& name) const;
  10062. /** Changes a named property of the node.
  10063. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10064. so that this change can be undone.
  10065. @see var, getProperty, removeProperty
  10066. */
  10067. void setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager);
  10068. /** Returns true if the node contains a named property. */
  10069. bool hasProperty (const Identifier& name) const;
  10070. /** Removes a property from the node.
  10071. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10072. so that this change can be undone.
  10073. */
  10074. void removeProperty (const Identifier& name, UndoManager* undoManager);
  10075. /** Removes all properties from the node.
  10076. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10077. so that this change can be undone.
  10078. */
  10079. void removeAllProperties (UndoManager* undoManager);
  10080. /** Returns the total number of properties that the node contains.
  10081. @see getProperty.
  10082. */
  10083. int getNumProperties() const;
  10084. /** Returns the identifier of the property with a given index.
  10085. @see getNumProperties
  10086. */
  10087. const Identifier getPropertyName (int index) const;
  10088. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  10089. The Value object will maintain a reference to this tree, and will use the undo manager when
  10090. it needs to change the value. Attaching a Value::Listener to the value object will provide
  10091. callbacks whenever the property changes.
  10092. */
  10093. Value getPropertyAsValue (const Identifier& name, UndoManager* undoManager) const;
  10094. /** Returns the number of child nodes belonging to this one.
  10095. @see getChild
  10096. */
  10097. int getNumChildren() const;
  10098. /** Returns one of this node's child nodes.
  10099. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  10100. whether a node is valid).
  10101. */
  10102. ValueTree getChild (int index) const;
  10103. /** Returns the first child node with the speficied type name.
  10104. If no such node is found, it'll return an invalid node. (See isValid() to find out
  10105. whether a node is valid).
  10106. @see getOrCreateChildWithName
  10107. */
  10108. ValueTree getChildWithName (const Identifier& type) const;
  10109. /** Returns the first child node with the speficied type name, creating and adding
  10110. a child with this name if there wasn't already one there.
  10111. The only time this will return an invalid object is when the object that you're calling
  10112. the method on is itself invalid.
  10113. @see getChildWithName
  10114. */
  10115. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  10116. /** Looks for the first child node that has the speficied property value.
  10117. This will scan the child nodes in order, until it finds one that has property that matches
  10118. the specified value.
  10119. If no such node is found, it'll return an invalid node. (See isValid() to find out
  10120. whether a node is valid).
  10121. */
  10122. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  10123. /** Adds a child to this node.
  10124. Make sure that the child is removed from any former parent node before calling this, or
  10125. you'll hit an assertion.
  10126. If the index is < 0 or greater than the current number of child nodes, the new node will
  10127. be added at the end of the list.
  10128. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10129. so that this change can be undone.
  10130. */
  10131. void addChild (const ValueTree& child, int index, UndoManager* undoManager);
  10132. /** Removes the specified child from this node's child-list.
  10133. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10134. so that this change can be undone.
  10135. */
  10136. void removeChild (const ValueTree& child, UndoManager* undoManager);
  10137. /** Removes a child from this node's child-list.
  10138. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10139. so that this change can be undone.
  10140. */
  10141. void removeChild (int childIndex, UndoManager* undoManager);
  10142. /** Removes all child-nodes from this node.
  10143. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10144. so that this change can be undone.
  10145. */
  10146. void removeAllChildren (UndoManager* undoManager);
  10147. /** Moves one of the children to a different index.
  10148. This will move the child to a specified index, shuffling along any intervening
  10149. items as required. So for example, if you have a list of { 0, 1, 2, 3, 4, 5 }, then
  10150. calling move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  10151. @param currentIndex the index of the item to be moved. If this isn't a
  10152. valid index, then nothing will be done
  10153. @param newIndex the index at which you'd like this item to end up. If this
  10154. is less than zero, the value will be moved to the end
  10155. of the list
  10156. @param undoManager the optional UndoManager to use to store this transaction
  10157. */
  10158. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager);
  10159. /** Returns true if this node is anywhere below the specified parent node.
  10160. This returns true if the node is a child-of-a-child, as well as a direct child.
  10161. */
  10162. bool isAChildOf (const ValueTree& possibleParent) const;
  10163. /** Returns the index of a child item in this parent.
  10164. If the child isn't found, this returns -1.
  10165. */
  10166. int indexOf (const ValueTree& child) const;
  10167. /** Returns the parent node that contains this one.
  10168. If the node has no parent, this will return an invalid node. (See isValid() to find out
  10169. whether a node is valid).
  10170. */
  10171. ValueTree getParent() const;
  10172. /** Creates an XmlElement that holds a complete image of this node and all its children.
  10173. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  10174. be used to recreate a similar node by calling fromXml()
  10175. @see fromXml
  10176. */
  10177. XmlElement* createXml() const;
  10178. /** Tries to recreate a node from its XML representation.
  10179. This isn't designed to cope with random XML data - for a sensible result, it should only
  10180. be fed XML that was created by the createXml() method.
  10181. */
  10182. static ValueTree fromXml (const XmlElement& xml);
  10183. /** Stores this tree (and all its children) in a binary format.
  10184. Once written, the data can be read back with readFromStream().
  10185. It's much faster to load/save your tree in binary form than as XML, but
  10186. obviously isn't human-readable.
  10187. */
  10188. void writeToStream (OutputStream& output);
  10189. /** Reloads a tree from a stream that was written with writeToStream(). */
  10190. static ValueTree readFromStream (InputStream& input);
  10191. /** Reloads a tree from a data block that was written with writeToStream(). */
  10192. static ValueTree readFromData (const void* data, size_t numBytes);
  10193. /** Listener class for events that happen to a ValueTree.
  10194. To get events from a ValueTree, make your class implement this interface, and use
  10195. ValueTree::addListener() and ValueTree::removeListener() to register it.
  10196. */
  10197. class JUCE_API Listener
  10198. {
  10199. public:
  10200. /** Destructor. */
  10201. virtual ~Listener() {}
  10202. /** This method is called when a property of this node (or of one of its sub-nodes) has
  10203. changed.
  10204. The tree parameter indicates which tree has had its property changed, and the property
  10205. parameter indicates the property.
  10206. Note that when you register a listener to a tree, it will receive this callback for
  10207. property changes in that tree, and also for any of its children, (recursively, at any depth).
  10208. If your tree has sub-trees but you only want to know about changes to the top level tree,
  10209. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  10210. */
  10211. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  10212. const Identifier& property) = 0;
  10213. /** This method is called when a child sub-tree is added or removed.
  10214. The tree parameter indicates the tree whose child was added or removed.
  10215. Note that when you register a listener to a tree, it will receive this callback for
  10216. child changes in that tree, and also in any of its children, (recursively, at any depth).
  10217. If your tree has sub-trees but you only want to know about changes to the top level tree,
  10218. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  10219. */
  10220. virtual void valueTreeChildrenChanged (ValueTree& treeWhoseChildHasChanged) = 0;
  10221. /** This method is called when a tree has been added or removed from a parent node.
  10222. This callback happens when the tree to which the listener was registered is added or
  10223. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  10224. the listener is registered, and not to any of its children.
  10225. */
  10226. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  10227. };
  10228. /** Adds a listener to receive callbacks when this node is changed.
  10229. The listener is added to this specific ValueTree object, and not to the shared
  10230. object that it refers to. When this object is deleted, all the listeners will
  10231. be lost, even if other references to the same ValueTree still exist. And if you
  10232. use the operator= to make this refer to a different ValueTree, any listeners will
  10233. begin listening to changes to the new tree instead of the old one.
  10234. When you're adding a listener, make sure that you add it to a ValueTree instance that
  10235. will last for as long as you need the listener. In general, you'd never want to add a
  10236. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  10237. @see removeListener
  10238. */
  10239. void addListener (Listener* listener);
  10240. /** Removes a listener that was previously added with addListener(). */
  10241. void removeListener (Listener* listener);
  10242. /** This method uses a comparator object to sort the tree's children into order.
  10243. The object provided must have a method of the form:
  10244. @code
  10245. int compareElements (const ValueTree& first, const ValueTree& second);
  10246. @endcode
  10247. ..and this method must return:
  10248. - a value of < 0 if the first comes before the second
  10249. - a value of 0 if the two objects are equivalent
  10250. - a value of > 0 if the second comes before the first
  10251. To improve performance, the compareElements() method can be declared as static or const.
  10252. @param comparator the comparator to use for comparing elements.
  10253. @param retainOrderOfEquivalentItems if this is true, then items
  10254. which the comparator says are equivalent will be
  10255. kept in the order in which they currently appear
  10256. in the array. This is slower to perform, but may
  10257. be important in some cases. If it's false, a faster
  10258. algorithm is used, but equivalent elements may be
  10259. rearranged.
  10260. */
  10261. template <typename ElementComparator>
  10262. void sort (ElementComparator& comparator, const bool retainOrderOfEquivalentItems = false)
  10263. {
  10264. if (object != 0)
  10265. {
  10266. ComparatorAdapter <ElementComparator> adapter (comparator);
  10267. object->children.sort (adapter, retainOrderOfEquivalentItems);
  10268. object->sendChildChangeMessage();
  10269. }
  10270. }
  10271. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  10272. This invalid object is equivalent to ValueTree created with its default constructor.
  10273. */
  10274. static const ValueTree invalid;
  10275. juce_UseDebuggingNewOperator
  10276. private:
  10277. class SetPropertyAction;
  10278. friend class SetPropertyAction;
  10279. class AddOrRemoveChildAction;
  10280. friend class AddOrRemoveChildAction;
  10281. class MoveChildAction;
  10282. friend class MoveChildAction;
  10283. class JUCE_API SharedObject : public ReferenceCountedObject
  10284. {
  10285. public:
  10286. explicit SharedObject (const Identifier& type);
  10287. SharedObject (const SharedObject& other);
  10288. ~SharedObject();
  10289. const Identifier type;
  10290. NamedValueSet properties;
  10291. ReferenceCountedArray <SharedObject> children;
  10292. SortedSet <ValueTree*> valueTreesWithListeners;
  10293. SharedObject* parent;
  10294. void sendPropertyChangeMessage (const Identifier& property);
  10295. void sendPropertyChangeMessage (ValueTree& tree, const Identifier& property);
  10296. void sendChildChangeMessage();
  10297. void sendChildChangeMessage (ValueTree& tree);
  10298. void sendParentChangeMessage();
  10299. const var& getProperty (const Identifier& name) const;
  10300. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  10301. void setProperty (const Identifier& name, const var& newValue, UndoManager*);
  10302. bool hasProperty (const Identifier& name) const;
  10303. void removeProperty (const Identifier& name, UndoManager*);
  10304. void removeAllProperties (UndoManager*);
  10305. bool isAChildOf (const SharedObject* possibleParent) const;
  10306. int indexOf (const ValueTree& child) const;
  10307. ValueTree getChildWithName (const Identifier& type) const;
  10308. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  10309. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  10310. void addChild (SharedObject* child, int index, UndoManager*);
  10311. void removeChild (int childIndex, UndoManager*);
  10312. void removeAllChildren (UndoManager*);
  10313. void moveChild (int currentIndex, int newIndex, UndoManager*);
  10314. bool isEquivalentTo (const SharedObject& other) const;
  10315. XmlElement* createXml() const;
  10316. juce_UseDebuggingNewOperator
  10317. private:
  10318. SharedObject& operator= (const SharedObject&);
  10319. };
  10320. template <typename ElementComparator>
  10321. class ComparatorAdapter
  10322. {
  10323. public:
  10324. ComparatorAdapter (ElementComparator& comparator_) throw() : comparator (comparator_) {}
  10325. int compareElements (SharedObject* const first, SharedObject* const second)
  10326. {
  10327. return comparator.compareElements (ValueTree (first), ValueTree (second));
  10328. }
  10329. private:
  10330. ElementComparator& comparator;
  10331. ComparatorAdapter (const ComparatorAdapter&);
  10332. ComparatorAdapter& operator= (const ComparatorAdapter&);
  10333. };
  10334. friend class SharedObject;
  10335. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  10336. SharedObjectPtr object;
  10337. ListenerList <Listener> listeners;
  10338. #if JUCE_MSVC && ! DOXYGEN
  10339. public: // (workaround for VC6)
  10340. #endif
  10341. explicit ValueTree (SharedObject*);
  10342. };
  10343. #endif // __JUCE_VALUETREE_JUCEHEADER__
  10344. /*** End of inlined file: juce_ValueTree.h ***/
  10345. #endif
  10346. #ifndef __JUCE_VARIANT_JUCEHEADER__
  10347. #endif
  10348. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  10349. #endif
  10350. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  10351. #endif
  10352. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  10353. /*** Start of inlined file: juce_FileLogger.h ***/
  10354. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  10355. #define __JUCE_FILELOGGER_JUCEHEADER__
  10356. /**
  10357. A simple implemenation of a Logger that writes to a file.
  10358. @see Logger
  10359. */
  10360. class JUCE_API FileLogger : public Logger
  10361. {
  10362. public:
  10363. /** Creates a FileLogger for a given file.
  10364. @param fileToWriteTo the file that to use - new messages will be appended
  10365. to the file. If the file doesn't exist, it will be created,
  10366. along with any parent directories that are needed.
  10367. @param welcomeMessage when opened, the logger will write a header to the log, along
  10368. with the current date and time, and this welcome message
  10369. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  10370. but is larger than this number of bytes, then the start of the
  10371. file will be truncated to keep the size down. This prevents a log
  10372. file getting ridiculously large over time. The file will be truncated
  10373. at a new-line boundary. If this value is less than zero, no size limit
  10374. will be imposed; if it's zero, the file will always be deleted. Note that
  10375. the size is only checked once when this object is created - any logging
  10376. that is done later will be appended without any checking
  10377. */
  10378. FileLogger (const File& fileToWriteTo,
  10379. const String& welcomeMessage,
  10380. const int maxInitialFileSizeBytes = 128 * 1024);
  10381. /** Destructor. */
  10382. ~FileLogger();
  10383. void logMessage (const String& message);
  10384. const File getLogFile() const { return logFile; }
  10385. /** Helper function to create a log file in the correct place for this platform.
  10386. On Windows this will return a logger with a path such as:
  10387. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  10388. On the Mac it'll create something like:
  10389. ~/Library/Logs/[logFileName]
  10390. The method might return 0 if the file can't be created for some reason.
  10391. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  10392. it's best to use the something like the name of your application here.
  10393. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  10394. call it "log.txt" because if it goes in a directory with logs
  10395. from other applications (as it will do on the Mac) then no-one
  10396. will know which one is yours!
  10397. @param welcomeMessage a message that will be written to the log when it's opened.
  10398. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  10399. */
  10400. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  10401. const String& logFileName,
  10402. const String& welcomeMessage,
  10403. const int maxInitialFileSizeBytes = 128 * 1024);
  10404. juce_UseDebuggingNewOperator
  10405. private:
  10406. File logFile;
  10407. CriticalSection logLock;
  10408. ScopedPointer <FileOutputStream> logStream;
  10409. void trimFileSize (int maxFileSizeBytes) const;
  10410. FileLogger (const FileLogger&);
  10411. FileLogger& operator= (const FileLogger&);
  10412. };
  10413. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  10414. /*** End of inlined file: juce_FileLogger.h ***/
  10415. #endif
  10416. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  10417. /*** Start of inlined file: juce_Initialisation.h ***/
  10418. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  10419. #define __JUCE_INITIALISATION_JUCEHEADER__
  10420. /** Initialises Juce's GUI classes.
  10421. If you're embedding Juce into an application that uses its own event-loop rather
  10422. than using the START_JUCE_APPLICATION macro, call this function before making any
  10423. Juce calls, to make sure things are initialised correctly.
  10424. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  10425. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  10426. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  10427. */
  10428. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  10429. /** Clears up any static data being used by Juce's GUI classes.
  10430. If you're embedding Juce into an application that uses its own event-loop rather
  10431. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  10432. code to clean up any juce objects that might be lying around.
  10433. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  10434. */
  10435. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  10436. /** Initialises the core parts of Juce.
  10437. If you're embedding Juce into either a command-line program, call this function
  10438. at the start of your main() function to make sure that Juce is initialised correctly.
  10439. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  10440. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  10441. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  10442. */
  10443. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI();
  10444. /** Clears up any static data being used by Juce's non-gui core classes.
  10445. If you're embedding Juce into either a command-line program, call this function
  10446. at the end of your main() function if you want to make sure any Juce objects are
  10447. cleaned up correctly.
  10448. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  10449. */
  10450. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI();
  10451. /** A utility object that helps you initialise and shutdown Juce correctly
  10452. using an RAII pattern.
  10453. When an instance of this class is created, it calls initialiseJuce_NonGUI(),
  10454. and when it's deleted, it calls shutdownJuce_NonGUI(), which lets you easily
  10455. make sure that these functions are matched correctly.
  10456. This class is particularly handy to use at the beginning of a console app's
  10457. main() function, because it'll take care of shutting down whenever you return
  10458. from the main() call.
  10459. @see ScopedJuceInitialiser_GUI
  10460. */
  10461. class ScopedJuceInitialiser_NonGUI
  10462. {
  10463. public:
  10464. /** The constructor simply calls initialiseJuce_NonGUI(). */
  10465. ScopedJuceInitialiser_NonGUI() { initialiseJuce_NonGUI(); }
  10466. /** The destructor simply calls shutdownJuce_NonGUI(). */
  10467. ~ScopedJuceInitialiser_NonGUI() { shutdownJuce_NonGUI(); }
  10468. };
  10469. /** A utility object that helps you initialise and shutdown Juce correctly
  10470. using an RAII pattern.
  10471. When an instance of this class is created, it calls initialiseJuce_GUI(),
  10472. and when it's deleted, it calls shutdownJuce_GUI(), which lets you easily
  10473. make sure that these functions are matched correctly.
  10474. This class is particularly handy to use at the beginning of a console app's
  10475. main() function, because it'll take care of shutting down whenever you return
  10476. from the main() call.
  10477. @see ScopedJuceInitialiser_NonGUI
  10478. */
  10479. class ScopedJuceInitialiser_GUI
  10480. {
  10481. public:
  10482. /** The constructor simply calls initialiseJuce_GUI(). */
  10483. ScopedJuceInitialiser_GUI() { initialiseJuce_GUI(); }
  10484. /** The destructor simply calls shutdownJuce_GUI(). */
  10485. ~ScopedJuceInitialiser_GUI() { shutdownJuce_GUI(); }
  10486. };
  10487. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  10488. /*** End of inlined file: juce_Initialisation.h ***/
  10489. #endif
  10490. #ifndef __JUCE_LOGGER_JUCEHEADER__
  10491. #endif
  10492. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  10493. #endif
  10494. #ifndef __JUCE_MEMORY_JUCEHEADER__
  10495. #endif
  10496. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10497. /*** Start of inlined file: juce_PerformanceCounter.h ***/
  10498. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10499. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10500. /** A timer for measuring performance of code and dumping the results to a file.
  10501. e.g. @code
  10502. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  10503. for (;;)
  10504. {
  10505. pc.start();
  10506. doSomethingFishy();
  10507. pc.stop();
  10508. }
  10509. @endcode
  10510. In this example, the time of each period between calling start/stop will be
  10511. measured and averaged over 50 runs, and the results printed to a file
  10512. every 50 times round the loop.
  10513. */
  10514. class JUCE_API PerformanceCounter
  10515. {
  10516. public:
  10517. /** Creates a PerformanceCounter object.
  10518. @param counterName the name used when printing out the statistics
  10519. @param runsPerPrintout the number of start/stop iterations before calling
  10520. printStatistics()
  10521. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  10522. the results are just written to the debugger output
  10523. */
  10524. PerformanceCounter (const String& counterName,
  10525. int runsPerPrintout = 100,
  10526. const File& loggingFile = File::nonexistent);
  10527. /** Destructor. */
  10528. ~PerformanceCounter();
  10529. /** Starts timing.
  10530. @see stop
  10531. */
  10532. void start();
  10533. /** Stops timing and prints out the results.
  10534. The number of iterations before doing a printout of the
  10535. results is set in the constructor.
  10536. @see start
  10537. */
  10538. void stop();
  10539. /** Dumps the current metrics to the debugger output and to a file.
  10540. As well as using Logger::outputDebugString to print the results,
  10541. this will write then to the file specified in the constructor (if
  10542. this was valid).
  10543. */
  10544. void printStatistics();
  10545. juce_UseDebuggingNewOperator
  10546. private:
  10547. String name;
  10548. int numRuns, runsPerPrint;
  10549. double totalTime;
  10550. int64 started;
  10551. File outputFile;
  10552. };
  10553. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10554. /*** End of inlined file: juce_PerformanceCounter.h ***/
  10555. #endif
  10556. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  10557. #endif
  10558. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10559. /*** Start of inlined file: juce_PlatformUtilities.h ***/
  10560. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10561. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10562. /**
  10563. A collection of miscellaneous platform-specific utilities.
  10564. */
  10565. class JUCE_API PlatformUtilities
  10566. {
  10567. public:
  10568. /** Plays the operating system's default alert 'beep' sound. */
  10569. static void beep();
  10570. /** Tries to launch the system's default reader for a given file or URL. */
  10571. static bool openDocument (const String& documentURL, const String& parameters);
  10572. /** Tries to launch the system's default email app to let the user create an email.
  10573. */
  10574. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  10575. const String& emailSubject,
  10576. const String& bodyText,
  10577. const StringArray& filesToAttach);
  10578. #if JUCE_MAC || JUCE_IPHONE || DOXYGEN
  10579. /** MAC ONLY - Turns a Core CF String into a juce one. */
  10580. static const String cfStringToJuceString (CFStringRef cfString);
  10581. /** MAC ONLY - Turns a juce string into a Core CF one. */
  10582. static CFStringRef juceStringToCFString (const String& s);
  10583. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  10584. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  10585. /** MAC ONLY - Turns an FSRef into a juce string path. */
  10586. static const String makePathFromFSRef (FSRef* file);
  10587. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  10588. their precomposed equivalents.
  10589. */
  10590. static const String convertToPrecomposedUnicode (const String& s);
  10591. /** MAC ONLY - Gets the type of a file from the file's resources. */
  10592. static OSType getTypeOfFile (const String& filename);
  10593. /** MAC ONLY - Returns true if this file is actually a bundle. */
  10594. static bool isBundle (const String& filename);
  10595. /** MAC ONLY - Adds an item to the dock */
  10596. static void addItemToDock (const File& file);
  10597. /** MAC ONLY - Returns the current OS version number.
  10598. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  10599. */
  10600. static int getOSXMinorVersionNumber();
  10601. #endif
  10602. #if JUCE_WINDOWS || DOXYGEN
  10603. // Some registry helper functions:
  10604. /** WIN32 ONLY - Returns a string from the registry.
  10605. The path is a string for the entire path of a value in the registry,
  10606. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  10607. */
  10608. static const String getRegistryValue (const String& regValuePath,
  10609. const String& defaultValue = String::empty);
  10610. /** WIN32 ONLY - Sets a registry value as a string.
  10611. This will take care of creating any groups needed to get to the given
  10612. registry value.
  10613. */
  10614. static void setRegistryValue (const String& regValuePath,
  10615. const String& value);
  10616. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  10617. static bool registryValueExists (const String& regValuePath);
  10618. /** WIN32 ONLY - Deletes a registry value. */
  10619. static void deleteRegistryValue (const String& regValuePath);
  10620. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  10621. static void deleteRegistryKey (const String& regKeyPath);
  10622. /** WIN32 ONLY - Creates a file association in the registry.
  10623. This lets you set the exe that should be launched by a given file extension.
  10624. @param fileExtension the file extension to associate, including the
  10625. initial dot, e.g. ".txt"
  10626. @param symbolicDescription a space-free short token to identify the file type
  10627. @param fullDescription a human-readable description of the file type
  10628. @param targetExecutable the executable that should be launched
  10629. @param iconResourceNumber the icon that gets displayed for the file type will be
  10630. found by looking up this resource number in the
  10631. executable. Pass 0 here to not use an icon
  10632. */
  10633. static void registerFileAssociation (const String& fileExtension,
  10634. const String& symbolicDescription,
  10635. const String& fullDescription,
  10636. const File& targetExecutable,
  10637. int iconResourceNumber);
  10638. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  10639. In a normal Juce application this will be set to the module handle
  10640. of the application executable.
  10641. If you're writing a DLL using Juce and plan to use any Juce messaging or
  10642. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  10643. to set the correct module handle in your DllMain() function, because
  10644. the win32 system relies on the correct instance handle when opening windows.
  10645. */
  10646. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  10647. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  10648. @see getCurrentModuleInstanceHandle()
  10649. */
  10650. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  10651. /** WIN32 ONLY - Gets the command-line params as a string.
  10652. This is needed to avoid unicode problems with the argc type params.
  10653. */
  10654. static const String JUCE_CALLTYPE getCurrentCommandLineParams();
  10655. #endif
  10656. /** Clears the floating point unit's flags.
  10657. Only has an effect under win32, currently.
  10658. */
  10659. static void fpuReset();
  10660. #if JUCE_LINUX || JUCE_WINDOWS
  10661. /** Loads a dynamically-linked library into the process's address space.
  10662. @param pathOrFilename the platform-dependent name and search path
  10663. @returns a handle which can be used by getProcedureEntryPoint(), or
  10664. zero if it fails.
  10665. @see freeDynamicLibrary, getProcedureEntryPoint
  10666. */
  10667. static void* loadDynamicLibrary (const String& pathOrFilename);
  10668. /** Frees a dynamically-linked library.
  10669. @param libraryHandle a handle created by loadDynamicLibrary
  10670. @see loadDynamicLibrary, getProcedureEntryPoint
  10671. */
  10672. static void freeDynamicLibrary (void* libraryHandle);
  10673. /** Finds a procedure call in a dynamically-linked library.
  10674. @param libraryHandle a library handle returned by loadDynamicLibrary
  10675. @param procedureName the name of the procedure call to try to load
  10676. @returns a pointer to the function if found, or 0 if it fails
  10677. @see loadDynamicLibrary
  10678. */
  10679. static void* getProcedureEntryPoint (void* libraryHandle,
  10680. const String& procedureName);
  10681. #endif
  10682. #if JUCE_LINUX || DOXYGEN
  10683. #endif
  10684. private:
  10685. PlatformUtilities();
  10686. PlatformUtilities (const PlatformUtilities&);
  10687. PlatformUtilities& operator= (const PlatformUtilities&);
  10688. };
  10689. #if JUCE_MAC || JUCE_IPHONE
  10690. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  10691. using RAII.
  10692. */
  10693. class ScopedAutoReleasePool
  10694. {
  10695. public:
  10696. ScopedAutoReleasePool();
  10697. ~ScopedAutoReleasePool();
  10698. private:
  10699. void* pool;
  10700. ScopedAutoReleasePool (const ScopedAutoReleasePool&);
  10701. ScopedAutoReleasePool& operator= (const ScopedAutoReleasePool&);
  10702. };
  10703. #endif
  10704. #if JUCE_LINUX
  10705. /** A handy class that uses XLockDisplay and XUnlockDisplay to lock the X server
  10706. using an RAII approach.
  10707. */
  10708. class ScopedXLock
  10709. {
  10710. public:
  10711. /** Creating a ScopedXLock object locks the X display.
  10712. This uses XLockDisplay() to grab the display that Juce is using.
  10713. */
  10714. ScopedXLock();
  10715. /** Deleting a ScopedXLock object unlocks the X display.
  10716. This calls XUnlockDisplay() to release the lock.
  10717. */
  10718. ~ScopedXLock();
  10719. };
  10720. #endif
  10721. #if JUCE_MAC
  10722. /**
  10723. A wrapper class for picking up events from an Apple IR remote control device.
  10724. To use it, just create a subclass of this class, implementing the buttonPressed()
  10725. callback, then call start() and stop() to start or stop receiving events.
  10726. */
  10727. class JUCE_API AppleRemoteDevice
  10728. {
  10729. public:
  10730. AppleRemoteDevice();
  10731. virtual ~AppleRemoteDevice();
  10732. /** The set of buttons that may be pressed.
  10733. @see buttonPressed
  10734. */
  10735. enum ButtonType
  10736. {
  10737. menuButton = 0, /**< The menu button (if it's held for a short time). */
  10738. playButton, /**< The play button. */
  10739. plusButton, /**< The plus or volume-up button. */
  10740. minusButton, /**< The minus or volume-down button. */
  10741. rightButton, /**< The right button (if it's held for a short time). */
  10742. leftButton, /**< The left button (if it's held for a short time). */
  10743. rightButton_Long, /**< The right button (if it's held for a long time). */
  10744. leftButton_Long, /**< The menu button (if it's held for a long time). */
  10745. menuButton_Long, /**< The menu button (if it's held for a long time). */
  10746. playButtonSleepMode,
  10747. switched
  10748. };
  10749. /** Override this method to receive the callback about a button press.
  10750. The callback will happen on the application's message thread.
  10751. Some buttons trigger matching up and down events, in which the isDown parameter
  10752. will be true and then false. Others only send a single event when the
  10753. button is pressed.
  10754. */
  10755. virtual void buttonPressed (const ButtonType buttonId, const bool isDown) = 0;
  10756. /** Starts the device running and responding to events.
  10757. Returns true if it managed to open the device.
  10758. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  10759. and will not be available to any other part of the system. If
  10760. false, it will be shared with other apps.
  10761. @see stop
  10762. */
  10763. bool start (const bool inExclusiveMode);
  10764. /** Stops the device running.
  10765. @see start
  10766. */
  10767. void stop();
  10768. /** Returns true if the device has been started successfully.
  10769. */
  10770. bool isActive() const;
  10771. /** Returns the ID number of the remote, if it has sent one.
  10772. */
  10773. int getRemoteId() const { return remoteId; }
  10774. juce_UseDebuggingNewOperator
  10775. /** @internal */
  10776. void handleCallbackInternal();
  10777. private:
  10778. void* device;
  10779. void* queue;
  10780. int remoteId;
  10781. bool open (const bool openInExclusiveMode);
  10782. AppleRemoteDevice (const AppleRemoteDevice&);
  10783. AppleRemoteDevice& operator= (const AppleRemoteDevice&);
  10784. };
  10785. #endif
  10786. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10787. /*** End of inlined file: juce_PlatformUtilities.h ***/
  10788. #endif
  10789. #ifndef __JUCE_RANDOM_JUCEHEADER__
  10790. /*** Start of inlined file: juce_Random.h ***/
  10791. #ifndef __JUCE_RANDOM_JUCEHEADER__
  10792. #define __JUCE_RANDOM_JUCEHEADER__
  10793. /**
  10794. A simple pseudo-random number generator.
  10795. */
  10796. class JUCE_API Random
  10797. {
  10798. public:
  10799. /** Creates a Random object based on a seed value.
  10800. For a given seed value, the subsequent numbers generated by this object
  10801. will be predictable, so a good idea is to set this value based
  10802. on the time, e.g.
  10803. new Random (Time::currentTimeMillis())
  10804. */
  10805. explicit Random (int64 seedValue) throw();
  10806. /** Destructor. */
  10807. ~Random() throw();
  10808. /** Returns the next random 32 bit integer.
  10809. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  10810. */
  10811. int nextInt() throw();
  10812. /** Returns the next random number, limited to a given range.
  10813. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  10814. */
  10815. int nextInt (int maxValue) throw();
  10816. /** Returns the next 64-bit random number.
  10817. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  10818. */
  10819. int64 nextInt64() throw();
  10820. /** Returns the next random floating-point number.
  10821. @returns a random value in the range 0 to 1.0
  10822. */
  10823. float nextFloat() throw();
  10824. /** Returns the next random floating-point number.
  10825. @returns a random value in the range 0 to 1.0
  10826. */
  10827. double nextDouble() throw();
  10828. /** Returns the next random boolean value.
  10829. */
  10830. bool nextBool() throw();
  10831. /** Returns a BigInteger containing a random number.
  10832. @returns a random value in the range 0 to (maximumValue - 1).
  10833. */
  10834. const BigInteger nextLargeNumber (const BigInteger& maximumValue);
  10835. /** Sets a range of bits in a BigInteger to random values. */
  10836. void fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits);
  10837. /** To avoid the overhead of having to create a new Random object whenever
  10838. you need a number, this is a shared application-wide object that
  10839. can be used.
  10840. It's not thread-safe though, so threads should use their own Random object.
  10841. */
  10842. static Random& getSystemRandom() throw();
  10843. /** Resets this Random object to a given seed value. */
  10844. void setSeed (int64 newSeed) throw();
  10845. /** Merges this object's seed with another value.
  10846. This sets the seed to be a value created by combining the current seed and this
  10847. new value.
  10848. */
  10849. void combineSeed (int64 seedValue) throw();
  10850. /** Reseeds this generator using a value generated from various semi-random system
  10851. properties like the current time, etc.
  10852. Because this function convolves the time with the last seed value, calling
  10853. it repeatedly will increase the randomness of the final result.
  10854. */
  10855. void setSeedRandomly();
  10856. juce_UseDebuggingNewOperator
  10857. private:
  10858. int64 seed;
  10859. };
  10860. #endif // __JUCE_RANDOM_JUCEHEADER__
  10861. /*** End of inlined file: juce_Random.h ***/
  10862. #endif
  10863. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  10864. #endif
  10865. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  10866. /*** Start of inlined file: juce_Singleton.h ***/
  10867. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  10868. #define __JUCE_SINGLETON_JUCEHEADER__
  10869. /**
  10870. Macro to declare member variables and methods for a singleton class.
  10871. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  10872. to the class's definition.
  10873. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  10874. implementation code.
  10875. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  10876. destructor, in case it is deleted by other means than deleteInstance()
  10877. Clients can then call the static method MyClass::getInstance() to get a pointer
  10878. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  10879. no instance currently exists.
  10880. e.g. @code
  10881. class MySingleton
  10882. {
  10883. public:
  10884. MySingleton()
  10885. {
  10886. }
  10887. ~MySingleton()
  10888. {
  10889. // this ensures that no dangling pointers are left when the
  10890. // singleton is deleted.
  10891. clearSingletonInstance();
  10892. }
  10893. juce_DeclareSingleton (MySingleton, false)
  10894. };
  10895. juce_ImplementSingleton (MySingleton)
  10896. // example of usage:
  10897. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  10898. ...
  10899. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  10900. @endcode
  10901. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  10902. than once during the process's lifetime - i.e. after you've created and deleted the
  10903. object, getInstance() will refuse to create another one. This can be useful to stop
  10904. objects being accidentally re-created during your app's shutdown code.
  10905. If you know that your object will only be created and deleted by a single thread, you
  10906. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  10907. of this one.
  10908. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  10909. */
  10910. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  10911. \
  10912. static classname* _singletonInstance; \
  10913. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  10914. \
  10915. static classname* getInstance() \
  10916. { \
  10917. if (_singletonInstance == 0) \
  10918. {\
  10919. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  10920. \
  10921. if (_singletonInstance == 0) \
  10922. { \
  10923. static bool alreadyInside = false; \
  10924. static bool createdOnceAlready = false; \
  10925. \
  10926. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  10927. jassert (! problem); \
  10928. if (! problem) \
  10929. { \
  10930. createdOnceAlready = true; \
  10931. alreadyInside = true; \
  10932. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  10933. alreadyInside = false; \
  10934. \
  10935. _singletonInstance = newObject; \
  10936. } \
  10937. } \
  10938. } \
  10939. \
  10940. return _singletonInstance; \
  10941. } \
  10942. \
  10943. static inline classname* getInstanceWithoutCreating() throw() \
  10944. { \
  10945. return _singletonInstance; \
  10946. } \
  10947. \
  10948. static void deleteInstance() \
  10949. { \
  10950. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  10951. if (_singletonInstance != 0) \
  10952. { \
  10953. classname* const old = _singletonInstance; \
  10954. _singletonInstance = 0; \
  10955. delete old; \
  10956. } \
  10957. } \
  10958. \
  10959. void clearSingletonInstance() throw() \
  10960. { \
  10961. if (_singletonInstance == this) \
  10962. _singletonInstance = 0; \
  10963. }
  10964. /** This is a counterpart to the juce_DeclareSingleton macro.
  10965. After adding the juce_DeclareSingleton to the class definition, this macro has
  10966. to be used in the cpp file.
  10967. */
  10968. #define juce_ImplementSingleton(classname) \
  10969. \
  10970. classname* classname::_singletonInstance = 0; \
  10971. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  10972. /**
  10973. Macro to declare member variables and methods for a singleton class.
  10974. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  10975. section to make access to it thread-safe. If you know that your object will
  10976. only ever be created or deleted by a single thread, then this is a
  10977. more efficient version to use.
  10978. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  10979. than once during the process's lifetime - i.e. after you've created and deleted the
  10980. object, getInstance() will refuse to create another one. This can be useful to stop
  10981. objects being accidentally re-created during your app's shutdown code.
  10982. See the documentation for juce_DeclareSingleton for more information about
  10983. how to use it, the only difference being that you have to use
  10984. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  10985. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  10986. */
  10987. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  10988. \
  10989. static classname* _singletonInstance; \
  10990. \
  10991. static classname* getInstance() \
  10992. { \
  10993. if (_singletonInstance == 0) \
  10994. { \
  10995. static bool alreadyInside = false; \
  10996. static bool createdOnceAlready = false; \
  10997. \
  10998. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  10999. jassert (! problem); \
  11000. if (! problem) \
  11001. { \
  11002. createdOnceAlready = true; \
  11003. alreadyInside = true; \
  11004. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  11005. alreadyInside = false; \
  11006. \
  11007. _singletonInstance = newObject; \
  11008. } \
  11009. } \
  11010. \
  11011. return _singletonInstance; \
  11012. } \
  11013. \
  11014. static inline classname* getInstanceWithoutCreating() throw() \
  11015. { \
  11016. return _singletonInstance; \
  11017. } \
  11018. \
  11019. static void deleteInstance() \
  11020. { \
  11021. if (_singletonInstance != 0) \
  11022. { \
  11023. classname* const old = _singletonInstance; \
  11024. _singletonInstance = 0; \
  11025. delete old; \
  11026. } \
  11027. } \
  11028. \
  11029. void clearSingletonInstance() throw() \
  11030. { \
  11031. if (_singletonInstance == this) \
  11032. _singletonInstance = 0; \
  11033. }
  11034. /**
  11035. Macro to declare member variables and methods for a singleton class.
  11036. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  11037. for recursion or repeated instantiation. It's intended for use as a lightweight
  11038. version of a singleton, where you're using it in very straightforward
  11039. circumstances and don't need the extra checking.
  11040. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  11041. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  11042. See the documentation for juce_DeclareSingleton for more information about
  11043. how to use it, the only difference being that you have to use
  11044. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  11045. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  11046. */
  11047. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  11048. \
  11049. static classname* _singletonInstance; \
  11050. \
  11051. static classname* getInstance() \
  11052. { \
  11053. if (_singletonInstance == 0) \
  11054. _singletonInstance = new classname(); \
  11055. \
  11056. return _singletonInstance; \
  11057. } \
  11058. \
  11059. static inline classname* getInstanceWithoutCreating() throw() \
  11060. { \
  11061. return _singletonInstance; \
  11062. } \
  11063. \
  11064. static void deleteInstance() \
  11065. { \
  11066. if (_singletonInstance != 0) \
  11067. { \
  11068. classname* const old = _singletonInstance; \
  11069. _singletonInstance = 0; \
  11070. delete old; \
  11071. } \
  11072. } \
  11073. \
  11074. void clearSingletonInstance() throw() \
  11075. { \
  11076. if (_singletonInstance == this) \
  11077. _singletonInstance = 0; \
  11078. }
  11079. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  11080. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  11081. to the class definition, this macro has to be used somewhere in the cpp file.
  11082. */
  11083. #define juce_ImplementSingleton_SingleThreaded(classname) \
  11084. \
  11085. classname* classname::_singletonInstance = 0;
  11086. #endif // __JUCE_SINGLETON_JUCEHEADER__
  11087. /*** End of inlined file: juce_Singleton.h ***/
  11088. #endif
  11089. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  11090. #endif
  11091. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  11092. /*** Start of inlined file: juce_SystemStats.h ***/
  11093. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  11094. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  11095. /**
  11096. Contains methods for finding out about the current hardware and OS configuration.
  11097. */
  11098. class JUCE_API SystemStats
  11099. {
  11100. public:
  11101. /** Returns the current version of JUCE,
  11102. (just in case you didn't already know at compile-time.)
  11103. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  11104. */
  11105. static const String getJUCEVersion();
  11106. /** The set of possible results of the getOperatingSystemType() method.
  11107. */
  11108. enum OperatingSystemType
  11109. {
  11110. UnknownOS = 0,
  11111. MacOSX = 0x1000,
  11112. Linux = 0x2000,
  11113. Win95 = 0x4001,
  11114. Win98 = 0x4002,
  11115. WinNT351 = 0x4103,
  11116. WinNT40 = 0x4104,
  11117. Win2000 = 0x4105,
  11118. WinXP = 0x4106,
  11119. WinVista = 0x4107,
  11120. Windows7 = 0x4108,
  11121. Windows = 0x4000, /**< To test whether any version of Windows is running,
  11122. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  11123. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  11124. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  11125. };
  11126. /** Returns the type of operating system we're running on.
  11127. @returns one of the values from the OperatingSystemType enum.
  11128. @see getOperatingSystemName
  11129. */
  11130. static OperatingSystemType getOperatingSystemType();
  11131. /** Returns the name of the type of operating system we're running on.
  11132. @returns a string describing the OS type.
  11133. @see getOperatingSystemType
  11134. */
  11135. static const String getOperatingSystemName();
  11136. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  11137. */
  11138. static bool isOperatingSystem64Bit();
  11139. /** Returns the current user's name, if available.
  11140. @see getFullUserName()
  11141. */
  11142. static const String getLogonName();
  11143. /** Returns the current user's full name, if available.
  11144. On some OSes, this may just return the same value as getLogonName().
  11145. @see getLogonName()
  11146. */
  11147. static const String getFullUserName();
  11148. // CPU and memory information..
  11149. /** Returns the approximate CPU speed.
  11150. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  11151. what year you're reading this...)
  11152. */
  11153. static int getCpuSpeedInMegaherz();
  11154. /** Returns a string to indicate the CPU vendor.
  11155. Might not be known on some systems.
  11156. */
  11157. static const String getCpuVendor();
  11158. /** Checks whether Intel MMX instructions are available. */
  11159. static bool hasMMX();
  11160. /** Checks whether Intel SSE instructions are available. */
  11161. static bool hasSSE();
  11162. /** Checks whether Intel SSE2 instructions are available. */
  11163. static bool hasSSE2();
  11164. /** Checks whether AMD 3DNOW instructions are available. */
  11165. static bool has3DNow();
  11166. /** Returns the number of CPUs.
  11167. */
  11168. static int getNumCpus();
  11169. /** Finds out how much RAM is in the machine.
  11170. @returns the approximate number of megabytes of memory, or zero if
  11171. something goes wrong when finding out.
  11172. */
  11173. static int getMemorySizeInMegabytes();
  11174. /** Returns the system page-size.
  11175. This is only used by programmers with beards.
  11176. */
  11177. static int getPageSize();
  11178. /** Returns a list of MAC addresses found on this machine.
  11179. @param addresses an array into which the MAC addresses should be copied
  11180. @param maxNum the number of elements in this array
  11181. @param littleEndian the endianness of the numbers to return. If this is true,
  11182. the least-significant byte of each number is the first byte
  11183. of the mac address. If false, the least significant byte is
  11184. the last number. Note that the default values of this parameter
  11185. are different on Mac/PC to avoid breaking old software that was
  11186. written before this parameter was added (when the two systems
  11187. defaulted to using different endiannesses). In newer
  11188. software you probably want to specify an explicit value
  11189. for this.
  11190. @returns the number of MAC addresses that were found
  11191. */
  11192. static int getMACAddresses (int64* addresses, int maxNum,
  11193. #if JUCE_MAC
  11194. bool littleEndian = true);
  11195. #else
  11196. bool littleEndian = false);
  11197. #endif
  11198. /** Returns a list of MAC addresses found on this machine.
  11199. @returns an array of strings containing the MAC addresses that were found
  11200. */
  11201. static const StringArray getMACAddressStrings();
  11202. // not-for-public-use platform-specific method gets called at startup to initialise things.
  11203. static void initialiseStats();
  11204. private:
  11205. SystemStats();
  11206. SystemStats (const SystemStats&);
  11207. SystemStats& operator= (const SystemStats&);
  11208. };
  11209. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  11210. /*** End of inlined file: juce_SystemStats.h ***/
  11211. #endif
  11212. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  11213. #endif
  11214. #ifndef __JUCE_TIME_JUCEHEADER__
  11215. #endif
  11216. #ifndef __JUCE_UUID_JUCEHEADER__
  11217. /*** Start of inlined file: juce_Uuid.h ***/
  11218. #ifndef __JUCE_UUID_JUCEHEADER__
  11219. #define __JUCE_UUID_JUCEHEADER__
  11220. /**
  11221. A universally unique 128-bit identifier.
  11222. This class generates very random unique numbers based on the system time
  11223. and MAC addresses if any are available. It's extremely unlikely that two identical
  11224. UUIDs would ever be created by chance.
  11225. The class includes methods for saving the ID as a string or as raw binary data.
  11226. */
  11227. class JUCE_API Uuid
  11228. {
  11229. public:
  11230. /** Creates a new unique ID. */
  11231. Uuid();
  11232. /** Destructor. */
  11233. ~Uuid() throw();
  11234. /** Creates a copy of another UUID. */
  11235. Uuid (const Uuid& other);
  11236. /** Copies another UUID. */
  11237. Uuid& operator= (const Uuid& other);
  11238. /** Returns true if the ID is zero. */
  11239. bool isNull() const throw();
  11240. /** Compares two UUIDs. */
  11241. bool operator== (const Uuid& other) const;
  11242. /** Compares two UUIDs. */
  11243. bool operator!= (const Uuid& other) const;
  11244. /** Returns a stringified version of this UUID.
  11245. A Uuid object can later be reconstructed from this string using operator= or
  11246. the constructor that takes a string parameter.
  11247. @returns a 32 character hex string.
  11248. */
  11249. const String toString() const;
  11250. /** Creates an ID from an encoded string version.
  11251. @see toString
  11252. */
  11253. Uuid (const String& uuidString);
  11254. /** Copies from a stringified UUID.
  11255. The string passed in should be one that was created with the toString() method.
  11256. */
  11257. Uuid& operator= (const String& uuidString);
  11258. /** Returns a pointer to the internal binary representation of the ID.
  11259. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  11260. the constructor or operator= method that takes an array of uint8s.
  11261. */
  11262. const uint8* getRawData() const throw() { return value.asBytes; }
  11263. /** Creates a UUID from a 16-byte array.
  11264. @see getRawData
  11265. */
  11266. Uuid (const uint8* const rawData);
  11267. /** Sets this UUID from 16-bytes of raw data. */
  11268. Uuid& operator= (const uint8* const rawData);
  11269. juce_UseDebuggingNewOperator
  11270. private:
  11271. union
  11272. {
  11273. uint8 asBytes [16];
  11274. int asInt[4];
  11275. int64 asInt64[2];
  11276. } value;
  11277. };
  11278. #endif // __JUCE_UUID_JUCEHEADER__
  11279. /*** End of inlined file: juce_Uuid.h ***/
  11280. #endif
  11281. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  11282. /*** Start of inlined file: juce_BlowFish.h ***/
  11283. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  11284. #define __JUCE_BLOWFISH_JUCEHEADER__
  11285. /**
  11286. BlowFish encryption class.
  11287. */
  11288. class JUCE_API BlowFish
  11289. {
  11290. public:
  11291. /** Creates an object that can encode/decode based on the specified key.
  11292. The key data can be up to 72 bytes long.
  11293. */
  11294. BlowFish (const void* keyData, int keyBytes);
  11295. /** Creates a copy of another blowfish object. */
  11296. BlowFish (const BlowFish& other);
  11297. /** Copies another blowfish object. */
  11298. BlowFish& operator= (const BlowFish& other);
  11299. /** Destructor. */
  11300. ~BlowFish();
  11301. /** Encrypts a pair of 32-bit integers. */
  11302. void encrypt (uint32& data1, uint32& data2) const throw();
  11303. /** Decrypts a pair of 32-bit integers. */
  11304. void decrypt (uint32& data1, uint32& data2) const throw();
  11305. juce_UseDebuggingNewOperator
  11306. private:
  11307. uint32 p[18];
  11308. HeapBlock <uint32> s[4];
  11309. uint32 F (uint32 x) const throw();
  11310. };
  11311. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  11312. /*** End of inlined file: juce_BlowFish.h ***/
  11313. #endif
  11314. #ifndef __JUCE_MD5_JUCEHEADER__
  11315. /*** Start of inlined file: juce_MD5.h ***/
  11316. #ifndef __JUCE_MD5_JUCEHEADER__
  11317. #define __JUCE_MD5_JUCEHEADER__
  11318. /**
  11319. MD5 checksum class.
  11320. Create one of these with a block of source data or a string, and it calculates the
  11321. MD5 checksum of that data.
  11322. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  11323. */
  11324. class JUCE_API MD5
  11325. {
  11326. public:
  11327. /** Creates a null MD5 object. */
  11328. MD5();
  11329. /** Creates a copy of another MD5. */
  11330. MD5 (const MD5& other);
  11331. /** Copies another MD5. */
  11332. MD5& operator= (const MD5& other);
  11333. /** Creates a checksum for a block of binary data. */
  11334. explicit MD5 (const MemoryBlock& data);
  11335. /** Creates a checksum for a block of binary data. */
  11336. MD5 (const void* data, const size_t numBytes);
  11337. /** Creates a checksum for a string.
  11338. Note that this operates on the string as a block of unicode characters, so the
  11339. result you get will differ from the value you'd get if the string was treated
  11340. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  11341. of this method with a checksum created by a different framework, which may have
  11342. used a different encoding.
  11343. */
  11344. explicit MD5 (const String& text);
  11345. /** Creates a checksum for the input from a stream.
  11346. This will read up to the given number of bytes from the stream, and produce the
  11347. checksum of that. If the number of bytes to read is negative, it'll read
  11348. until the stream is exhausted.
  11349. */
  11350. MD5 (InputStream& input, int64 numBytesToRead = -1);
  11351. /** Creates a checksum for a file. */
  11352. explicit MD5 (const File& file);
  11353. /** Destructor. */
  11354. ~MD5();
  11355. /** Returns the checksum as a 16-byte block of data. */
  11356. const MemoryBlock getRawChecksumData() const;
  11357. /** Returns the checksum as a 32-digit hex string. */
  11358. const String toHexString() const;
  11359. /** Compares this to another MD5. */
  11360. bool operator== (const MD5& other) const;
  11361. /** Compares this to another MD5. */
  11362. bool operator!= (const MD5& other) const;
  11363. juce_UseDebuggingNewOperator
  11364. private:
  11365. uint8 result [16];
  11366. struct ProcessContext
  11367. {
  11368. uint8 buffer [64];
  11369. uint32 state [4];
  11370. uint32 count [2];
  11371. ProcessContext();
  11372. void processBlock (const void* data, size_t dataSize);
  11373. void transform (const void* buffer);
  11374. void finish (void* const result);
  11375. };
  11376. void processStream (InputStream& input, int64 numBytesToRead);
  11377. };
  11378. #endif // __JUCE_MD5_JUCEHEADER__
  11379. /*** End of inlined file: juce_MD5.h ***/
  11380. #endif
  11381. #ifndef __JUCE_PRIMES_JUCEHEADER__
  11382. /*** Start of inlined file: juce_Primes.h ***/
  11383. #ifndef __JUCE_PRIMES_JUCEHEADER__
  11384. #define __JUCE_PRIMES_JUCEHEADER__
  11385. /**
  11386. Prime number creation class.
  11387. This class contains static methods for generating and testing prime numbers.
  11388. @see BigInteger
  11389. */
  11390. class JUCE_API Primes
  11391. {
  11392. public:
  11393. /** Creates a random prime number with a given bit-length.
  11394. The certainty parameter specifies how many iterations to use when testing
  11395. for primality. A safe value might be anything over about 20-30.
  11396. The randomSeeds parameter lets you optionally pass it a set of values with
  11397. which to seed the random number generation, improving the security of the
  11398. keys generated.
  11399. */
  11400. static const BigInteger createProbablePrime (int bitLength,
  11401. int certainty,
  11402. const int* randomSeeds = 0,
  11403. int numRandomSeeds = 0);
  11404. /** Tests a number to see if it's prime.
  11405. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  11406. whether the number is prime.
  11407. The certainty parameter specifies how many iterations to use when testing - a
  11408. safe value might be anything over about 20-30.
  11409. */
  11410. static bool isProbablyPrime (const BigInteger& number, int certainty);
  11411. private:
  11412. Primes();
  11413. Primes (const Primes&);
  11414. Primes& operator= (const Primes&);
  11415. };
  11416. #endif // __JUCE_PRIMES_JUCEHEADER__
  11417. /*** End of inlined file: juce_Primes.h ***/
  11418. #endif
  11419. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  11420. /*** Start of inlined file: juce_RSAKey.h ***/
  11421. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  11422. #define __JUCE_RSAKEY_JUCEHEADER__
  11423. /**
  11424. RSA public/private key-pair encryption class.
  11425. An object of this type makes up one half of a public/private RSA key pair. Use the
  11426. createKeyPair() method to create a matching pair for encoding/decoding.
  11427. */
  11428. class JUCE_API RSAKey
  11429. {
  11430. public:
  11431. /** Creates a null key object.
  11432. Initialise a pair of objects for use with the createKeyPair() method.
  11433. */
  11434. RSAKey();
  11435. /** Loads a key from an encoded string representation.
  11436. This reloads a key from a string created by the toString() method.
  11437. */
  11438. explicit RSAKey (const String& stringRepresentation);
  11439. /** Destructor. */
  11440. ~RSAKey();
  11441. bool operator== (const RSAKey& other) const throw();
  11442. bool operator!= (const RSAKey& other) const throw();
  11443. /** Turns the key into a string representation.
  11444. This can be reloaded using the constructor that takes a string.
  11445. */
  11446. const String toString() const;
  11447. /** Encodes or decodes a value.
  11448. Call this on the public key object to encode some data, then use the matching
  11449. private key object to decode it.
  11450. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  11451. initialised correctly.
  11452. NOTE: This method dumbly applies this key to this data. If you encode some data
  11453. and then try to decode it with a key that doesn't match, this method will still
  11454. happily do its job and return true, but the result won't be what you were expecting.
  11455. It's your responsibility to check that the result is what you wanted.
  11456. */
  11457. bool applyToValue (BigInteger& value) const;
  11458. /** Creates a public/private key-pair.
  11459. Each key will perform one-way encryption that can only be reversed by
  11460. using the other key.
  11461. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  11462. sizes are more secure, but this method will take longer to execute.
  11463. The randomSeeds parameter lets you optionally pass it a set of values with
  11464. which to seed the random number generation, improving the security of the
  11465. keys generated.
  11466. */
  11467. static void createKeyPair (RSAKey& publicKey,
  11468. RSAKey& privateKey,
  11469. int numBits,
  11470. const int* randomSeeds = 0,
  11471. int numRandomSeeds = 0);
  11472. juce_UseDebuggingNewOperator
  11473. protected:
  11474. BigInteger part1, part2;
  11475. };
  11476. #endif // __JUCE_RSAKEY_JUCEHEADER__
  11477. /*** End of inlined file: juce_RSAKey.h ***/
  11478. #endif
  11479. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11480. /*** Start of inlined file: juce_DirectoryIterator.h ***/
  11481. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11482. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11483. /**
  11484. Searches through a the files in a directory, returning each file that is found.
  11485. A DirectoryIterator will search through a directory and its subdirectories using
  11486. a wildcard filepattern match.
  11487. If you may be finding a large number of files, this is better than
  11488. using File::findChildFiles() because it doesn't block while it finds them
  11489. all, and this is more memory-efficient.
  11490. It can also guess how far it's got using a wildly inaccurate algorithm.
  11491. */
  11492. class JUCE_API DirectoryIterator
  11493. {
  11494. public:
  11495. /** Creates a DirectoryIterator for a given directory.
  11496. After creating one of these, call its next() method to get the
  11497. first file - e.g. @code
  11498. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  11499. while (iter.next())
  11500. {
  11501. File theFileItFound (iter.getFile());
  11502. ... etc
  11503. }
  11504. @endcode
  11505. @param directory the directory to search in
  11506. @param isRecursive whether all the subdirectories should also be searched
  11507. @param wildCard the file pattern to match
  11508. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  11509. whether to look for files, directories, or both.
  11510. */
  11511. DirectoryIterator (const File& directory,
  11512. bool isRecursive,
  11513. const String& wildCard = "*",
  11514. int whatToLookFor = File::findFiles);
  11515. /** Destructor. */
  11516. ~DirectoryIterator();
  11517. /** Moves the iterator along to the next file.
  11518. @returns true if a file was found (you can then use getFile() to see what it was) - or
  11519. false if there are no more matching files.
  11520. */
  11521. bool next();
  11522. /** Moves the iterator along to the next file, and returns various properties of that file.
  11523. If you need to find out details about the file, it's more efficient to call this method than
  11524. to call the normal next() method and then find out the details afterwards.
  11525. All the parameters are optional, so pass null pointers for any items that you're not
  11526. interested in.
  11527. @returns true if a file was found (you can then use getFile() to see what it was) - or
  11528. false if there are no more matching files. If it returns false, then none of the
  11529. parameters will be filled-in.
  11530. */
  11531. bool next (bool* isDirectory, bool* isHidden, int64* fileSize,
  11532. Time* modTime, Time* creationTime, bool* isReadOnly);
  11533. /** Returns the file that the iterator is currently pointing at.
  11534. The result of this call is only valid after a call to next() has returned true.
  11535. */
  11536. const File getFile() const;
  11537. /** Returns a guess of how far through the search the iterator has got.
  11538. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  11539. very accurate.
  11540. */
  11541. float getEstimatedProgress() const;
  11542. juce_UseDebuggingNewOperator
  11543. private:
  11544. friend class File;
  11545. class NativeIterator
  11546. {
  11547. public:
  11548. NativeIterator (const File& directory, const String& wildCard);
  11549. ~NativeIterator();
  11550. bool next (String& filenameFound,
  11551. bool* isDirectory, bool* isHidden, int64* fileSize,
  11552. Time* modTime, Time* creationTime, bool* isReadOnly);
  11553. class Pimpl;
  11554. juce_UseDebuggingNewOperator
  11555. private:
  11556. friend class DirectoryIterator;
  11557. friend class ScopedPointer<Pimpl>;
  11558. ScopedPointer<Pimpl> pimpl;
  11559. NativeIterator (const NativeIterator&);
  11560. NativeIterator& operator= (const NativeIterator&);
  11561. };
  11562. friend class ScopedPointer<NativeIterator::Pimpl>;
  11563. NativeIterator fileFinder;
  11564. String wildCard, path;
  11565. int index;
  11566. mutable int totalNumFiles;
  11567. const int whatToLookFor;
  11568. const bool isRecursive;
  11569. ScopedPointer <DirectoryIterator> subIterator;
  11570. File currentFile;
  11571. DirectoryIterator (const DirectoryIterator&);
  11572. DirectoryIterator& operator= (const DirectoryIterator&);
  11573. };
  11574. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11575. /*** End of inlined file: juce_DirectoryIterator.h ***/
  11576. #endif
  11577. #ifndef __JUCE_FILE_JUCEHEADER__
  11578. #endif
  11579. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11580. /*** Start of inlined file: juce_FileInputStream.h ***/
  11581. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11582. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11583. /**
  11584. An input stream that reads from a local file.
  11585. @see InputStream, FileOutputStream, File::createInputStream
  11586. */
  11587. class JUCE_API FileInputStream : public InputStream
  11588. {
  11589. public:
  11590. /** Creates a FileInputStream.
  11591. @param fileToRead the file to read from - if the file can't be accessed for some
  11592. reason, then the stream will just contain no data
  11593. */
  11594. explicit FileInputStream (const File& fileToRead);
  11595. /** Destructor. */
  11596. ~FileInputStream();
  11597. const File& getFile() const throw() { return file; }
  11598. int64 getTotalLength();
  11599. int read (void* destBuffer, int maxBytesToRead);
  11600. bool isExhausted();
  11601. int64 getPosition();
  11602. bool setPosition (int64 pos);
  11603. juce_UseDebuggingNewOperator
  11604. private:
  11605. File file;
  11606. void* fileHandle;
  11607. int64 currentPosition, totalSize;
  11608. bool needToSeek;
  11609. FileInputStream (const FileInputStream&);
  11610. FileInputStream& operator= (const FileInputStream&);
  11611. };
  11612. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11613. /*** End of inlined file: juce_FileInputStream.h ***/
  11614. #endif
  11615. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11616. /*** Start of inlined file: juce_FileOutputStream.h ***/
  11617. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11618. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11619. /**
  11620. An output stream that writes into a local file.
  11621. @see OutputStream, FileInputStream, File::createOutputStream
  11622. */
  11623. class JUCE_API FileOutputStream : public OutputStream
  11624. {
  11625. public:
  11626. /** Creates a FileOutputStream.
  11627. If the file doesn't exist, it will first be created. If the file can't be
  11628. created or opened, the failedToOpen() method will return
  11629. true.
  11630. If the file already exists when opened, the stream's write-postion will
  11631. be set to the end of the file. To overwrite an existing file,
  11632. use File::deleteFile() before opening the stream, or use setPosition(0)
  11633. after it's opened (although this won't truncate the file).
  11634. It's better to use File::createOutputStream() to create one of these, rather
  11635. than using the class directly.
  11636. @see TemporaryFile
  11637. */
  11638. FileOutputStream (const File& fileToWriteTo,
  11639. int bufferSizeToUse = 16384);
  11640. /** Destructor. */
  11641. ~FileOutputStream();
  11642. /** Returns the file that this stream is writing to.
  11643. */
  11644. const File& getFile() const { return file; }
  11645. /** Returns true if the stream couldn't be opened for some reason.
  11646. */
  11647. bool failedToOpen() const { return fileHandle == 0; }
  11648. void flush();
  11649. int64 getPosition();
  11650. bool setPosition (int64 pos);
  11651. bool write (const void* data, int numBytes);
  11652. juce_UseDebuggingNewOperator
  11653. private:
  11654. File file;
  11655. void* fileHandle;
  11656. int64 currentPosition;
  11657. int bufferSize, bytesInBuffer;
  11658. HeapBlock <char> buffer;
  11659. void flushInternal();
  11660. int64 getPositionInternal() const;
  11661. FileOutputStream (const FileOutputStream&);
  11662. FileOutputStream& operator= (const FileOutputStream&);
  11663. };
  11664. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11665. /*** End of inlined file: juce_FileOutputStream.h ***/
  11666. #endif
  11667. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  11668. /*** Start of inlined file: juce_FileSearchPath.h ***/
  11669. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  11670. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  11671. /**
  11672. Encapsulates a set of folders that make up a search path.
  11673. @see File
  11674. */
  11675. class JUCE_API FileSearchPath
  11676. {
  11677. public:
  11678. /** Creates an empty search path. */
  11679. FileSearchPath();
  11680. /** Creates a search path from a string of pathnames.
  11681. The path can be semicolon- or comma-separated, e.g.
  11682. "/foo/bar;/foo/moose;/fish/moose"
  11683. The separate folders are tokenised and added to the search path.
  11684. */
  11685. FileSearchPath (const String& path);
  11686. /** Creates a copy of another search path. */
  11687. FileSearchPath (const FileSearchPath& other);
  11688. /** Destructor. */
  11689. ~FileSearchPath();
  11690. /** Uses a string containing a list of pathnames to re-initialise this list.
  11691. This search path is cleared and the semicolon- or comma-separated folders
  11692. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  11693. */
  11694. FileSearchPath& operator= (const String& path);
  11695. /** Returns the number of folders in this search path.
  11696. @see operator[]
  11697. */
  11698. int getNumPaths() const;
  11699. /** Returns one of the folders in this search path.
  11700. The file returned isn't guaranteed to actually be a valid directory.
  11701. @see getNumPaths
  11702. */
  11703. const File operator[] (int index) const;
  11704. /** Returns the search path as a semicolon-separated list of directories. */
  11705. const String toString() const;
  11706. /** Adds a new directory to the search path.
  11707. The new directory is added to the end of the list if the insertIndex parameter is
  11708. less than zero, otherwise it is inserted at the given index.
  11709. */
  11710. void add (const File& directoryToAdd,
  11711. int insertIndex = -1);
  11712. /** Adds a new directory to the search path if it's not already in there. */
  11713. void addIfNotAlreadyThere (const File& directoryToAdd);
  11714. /** Removes a directory from the search path. */
  11715. void remove (int indexToRemove);
  11716. /** Merges another search path into this one.
  11717. This will remove any duplicate directories.
  11718. */
  11719. void addPath (const FileSearchPath& other);
  11720. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  11721. If the search is intended to be recursive, there's no point having nested folders in the search
  11722. path, because they'll just get searched twice and you'll get duplicate results.
  11723. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  11724. */
  11725. void removeRedundantPaths();
  11726. /** Removes any directories that don't actually exist. */
  11727. void removeNonExistentPaths();
  11728. /** Searches the path for a wildcard.
  11729. This will search all the directories in the search path in order, adding any
  11730. matching files to the results array.
  11731. @param results an array to append the results to
  11732. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  11733. return files, directories, or both.
  11734. @param searchRecursively whether to recursively search the subdirectories too
  11735. @param wildCardPattern a pattern to match against the filenames
  11736. @returns the number of files added to the array
  11737. @see File::findChildFiles
  11738. */
  11739. int findChildFiles (Array<File>& results,
  11740. int whatToLookFor,
  11741. bool searchRecursively,
  11742. const String& wildCardPattern = "*") const;
  11743. /** Finds out whether a file is inside one of the path's directories.
  11744. This will return true if the specified file is a child of one of the
  11745. directories specified by this path. Note that this doesn't actually do any
  11746. searching or check that the files exist - it just looks at the pathnames
  11747. to work out whether the file would be inside a directory.
  11748. @param fileToCheck the file to look for
  11749. @param checkRecursively if true, then this will return true if the file is inside a
  11750. subfolder of one of the path's directories (at any depth). If false
  11751. it will only return true if the file is actually a direct child
  11752. of one of the directories.
  11753. @see File::isAChildOf
  11754. */
  11755. bool isFileInPath (const File& fileToCheck,
  11756. bool checkRecursively) const;
  11757. juce_UseDebuggingNewOperator
  11758. private:
  11759. StringArray directories;
  11760. void init (const String& path);
  11761. };
  11762. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  11763. /*** End of inlined file: juce_FileSearchPath.h ***/
  11764. #endif
  11765. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  11766. /*** Start of inlined file: juce_NamedPipe.h ***/
  11767. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  11768. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  11769. /**
  11770. A cross-process pipe that can have data written to and read from it.
  11771. Two or more processes can use these for inter-process communication.
  11772. @see InterprocessConnection
  11773. */
  11774. class JUCE_API NamedPipe
  11775. {
  11776. public:
  11777. /** Creates a NamedPipe. */
  11778. NamedPipe();
  11779. /** Destructor. */
  11780. ~NamedPipe();
  11781. /** Tries to open a pipe that already exists.
  11782. Returns true if it succeeds.
  11783. */
  11784. bool openExisting (const String& pipeName);
  11785. /** Tries to create a new pipe.
  11786. Returns true if it succeeds.
  11787. */
  11788. bool createNewPipe (const String& pipeName);
  11789. /** Closes the pipe, if it's open. */
  11790. void close();
  11791. /** True if the pipe is currently open. */
  11792. bool isOpen() const;
  11793. /** Returns the last name that was used to try to open this pipe. */
  11794. const String getName() const;
  11795. /** Reads data from the pipe.
  11796. This will block until another thread has written enough data into the pipe to fill
  11797. the number of bytes specified, or until another thread calls the cancelPendingReads()
  11798. method.
  11799. If the operation fails, it returns -1, otherwise, it will return the number of
  11800. bytes read.
  11801. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  11802. this is a maximum timeout for reading from the pipe.
  11803. */
  11804. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  11805. /** Writes some data to the pipe.
  11806. If the operation fails, it returns -1, otherwise, it will return the number of
  11807. bytes written.
  11808. */
  11809. int write (const void* sourceBuffer, int numBytesToWrite,
  11810. int timeOutMilliseconds = 2000);
  11811. /** If any threads are currently blocked on a read operation, this tells them to abort.
  11812. */
  11813. void cancelPendingReads();
  11814. juce_UseDebuggingNewOperator
  11815. private:
  11816. void* internal;
  11817. String currentPipeName;
  11818. CriticalSection lock;
  11819. NamedPipe (const NamedPipe&);
  11820. NamedPipe& operator= (const NamedPipe&);
  11821. bool openInternal (const String& pipeName, const bool createPipe);
  11822. };
  11823. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  11824. /*** End of inlined file: juce_NamedPipe.h ***/
  11825. #endif
  11826. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  11827. /*** Start of inlined file: juce_TemporaryFile.h ***/
  11828. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  11829. #define __JUCE_TEMPORARYFILE_JUCEHEADER__
  11830. /**
  11831. Manages a temporary file, which will be deleted when this object is deleted.
  11832. This object is intended to be used as a stack based object, using its scope
  11833. to make sure the temporary file isn't left lying around.
  11834. For example:
  11835. @code
  11836. {
  11837. File myTargetFile ("~/myfile.txt");
  11838. // this will choose a file called something like "~/myfile_temp239348.txt"
  11839. // which definitely doesn't exist at the time the constructor is called.
  11840. TemporaryFile temp (myTargetFile);
  11841. // create a stream to the temporary file, and write some data to it...
  11842. ScopedPointer <FileOutputStream> out (temp.getFile().createOutputStream());
  11843. if (out != 0)
  11844. {
  11845. out->write ( ...etc )
  11846. out->flush();
  11847. out = 0; // (deletes the stream)
  11848. // ..now we've finished writing, this will rename the temp file to
  11849. // make it replace the target file we specified above.
  11850. bool succeeded = temp.overwriteTargetFileWithTemporary();
  11851. }
  11852. // ..and even if something went wrong and our overwrite failed,
  11853. // as the TemporaryFile object goes out of scope here, it'll make sure
  11854. // that the temp file gets deleted.
  11855. }
  11856. @endcode
  11857. @see File, FileOutputStream
  11858. */
  11859. class JUCE_API TemporaryFile
  11860. {
  11861. public:
  11862. enum OptionFlags
  11863. {
  11864. useHiddenFile = 1, /**< Indicates that the temporary file should be hidden -
  11865. i.e. its name should start with a dot. */
  11866. putNumbersInBrackets = 2 /**< Indicates that when numbers are appended to make sure
  11867. the file is unique, they should go in brackets rather
  11868. than just being appended (see File::getNonexistentSibling() )*/
  11869. };
  11870. /** Creates a randomly-named temporary file in the default temp directory.
  11871. @param suffix a file suffix to use for the file
  11872. @param optionFlags a combination of the values listed in the OptionFlags enum
  11873. The file will not be created until you write to it. And remember that when
  11874. this object is deleted, the file will also be deleted!
  11875. */
  11876. TemporaryFile (const String& suffix = String::empty,
  11877. int optionFlags = 0);
  11878. /** Creates a temporary file in the same directory as a specified file.
  11879. This is useful if you have a file that you want to overwrite, but don't
  11880. want to harm the original file if the write operation fails. You can
  11881. use this to create a temporary file next to the target file, then
  11882. write to the temporary file, and finally use overwriteTargetFileWithTemporary()
  11883. to replace the target file with the one you've just written.
  11884. This class won't create any files until you actually write to them. And remember
  11885. that when this object is deleted, the temporary file will also be deleted!
  11886. @param targetFile the file that you intend to overwrite - the temporary
  11887. file will be created in the same directory as this
  11888. @param optionFlags a combination of the values listed in the OptionFlags enum
  11889. */
  11890. TemporaryFile (const File& targetFile,
  11891. int optionFlags = 0);
  11892. /** Destructor.
  11893. When this object is deleted it will make sure that its temporary file is
  11894. also deleted! If the operation fails, it'll throw an assertion in debug
  11895. mode.
  11896. */
  11897. ~TemporaryFile();
  11898. /** Returns the temporary file. */
  11899. const File getFile() const { return temporaryFile; }
  11900. /** Returns the target file that was specified in the constructor. */
  11901. const File getTargetFile() const { return targetFile; }
  11902. /** Tries to move the temporary file to overwrite the target file that was
  11903. specified in the constructor.
  11904. If you used the constructor that specified a target file, this will attempt
  11905. to replace that file with the temporary one.
  11906. Before calling this, make sure:
  11907. - that you've actually written to the temporary file
  11908. - that you've closed any open streams that you were using to write to it
  11909. - and that you don't have any streams open to the target file, which would
  11910. prevent it being overwritten
  11911. If the file move succeeds, this returns false, and the temporary file will
  11912. have disappeared. If it fails, the temporary file will probably still exist,
  11913. but will be deleted when this object is destroyed.
  11914. */
  11915. bool overwriteTargetFileWithTemporary() const;
  11916. juce_UseDebuggingNewOperator
  11917. private:
  11918. File temporaryFile, targetFile;
  11919. void createTempFile (const File& parentDirectory, String name, const String& suffix, int optionFlags);
  11920. TemporaryFile (const TemporaryFile&);
  11921. TemporaryFile& operator= (const TemporaryFile&);
  11922. };
  11923. #endif // __JUCE_TEMPORARYFILE_JUCEHEADER__
  11924. /*** End of inlined file: juce_TemporaryFile.h ***/
  11925. #endif
  11926. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  11927. /*** Start of inlined file: juce_ZipFile.h ***/
  11928. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  11929. #define __JUCE_ZIPFILE_JUCEHEADER__
  11930. /*** Start of inlined file: juce_InputSource.h ***/
  11931. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  11932. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  11933. /**
  11934. A lightweight object that can create a stream to read some kind of resource.
  11935. This may be used to refer to a file, or some other kind of source, allowing a
  11936. caller to create an input stream that can read from it when required.
  11937. @see FileInputSource
  11938. */
  11939. class JUCE_API InputSource
  11940. {
  11941. public:
  11942. InputSource() throw() {}
  11943. /** Destructor. */
  11944. virtual ~InputSource() {}
  11945. /** Returns a new InputStream to read this item.
  11946. @returns an inputstream that the caller will delete, or 0 if
  11947. the filename isn't found.
  11948. */
  11949. virtual InputStream* createInputStream() = 0;
  11950. /** Returns a new InputStream to read an item, relative.
  11951. @param relatedItemPath the relative pathname of the resource that is required
  11952. @returns an inputstream that the caller will delete, or 0 if
  11953. the item isn't found.
  11954. */
  11955. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  11956. /** Returns a hash code that uniquely represents this item.
  11957. */
  11958. virtual int64 hashCode() const = 0;
  11959. juce_UseDebuggingNewOperator
  11960. };
  11961. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  11962. /*** End of inlined file: juce_InputSource.h ***/
  11963. /**
  11964. Decodes a ZIP file from a stream.
  11965. This can enumerate the items in a ZIP file and can create suitable stream objects
  11966. to read each one.
  11967. */
  11968. class JUCE_API ZipFile
  11969. {
  11970. public:
  11971. /** Creates a ZipFile for a given stream.
  11972. @param inputStream the stream to read from
  11973. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  11974. will be deleted when this ZipFile object is deleted
  11975. */
  11976. ZipFile (InputStream* inputStream,
  11977. bool deleteStreamWhenDestroyed) throw();
  11978. /** Creates a ZipFile based for a file. */
  11979. ZipFile (const File& file);
  11980. /** Creates a ZipFile for an input source.
  11981. The inputSource object will be owned by the zip file, which will delete
  11982. it later when not needed.
  11983. */
  11984. ZipFile (InputSource* inputSource);
  11985. /** Destructor. */
  11986. ~ZipFile() throw();
  11987. /**
  11988. Contains information about one of the entries in a ZipFile.
  11989. @see ZipFile::getEntry
  11990. */
  11991. struct ZipEntry
  11992. {
  11993. /** The name of the file, which may also include a partial pathname. */
  11994. String filename;
  11995. /** The file's original size. */
  11996. unsigned int uncompressedSize;
  11997. /** The last time the file was modified. */
  11998. Time fileTime;
  11999. };
  12000. /** Returns the number of items in the zip file. */
  12001. int getNumEntries() const throw();
  12002. /** Returns a structure that describes one of the entries in the zip file.
  12003. This may return zero if the index is out of range.
  12004. @see ZipFile::ZipEntry
  12005. */
  12006. const ZipEntry* getEntry (int index) const throw();
  12007. /** Returns the index of the first entry with a given filename.
  12008. This uses a case-sensitive comparison to look for a filename in the
  12009. list of entries. It might return -1 if no match is found.
  12010. @see ZipFile::ZipEntry
  12011. */
  12012. int getIndexOfFileName (const String& fileName) const throw();
  12013. /** Returns a structure that describes one of the entries in the zip file.
  12014. This uses a case-sensitive comparison to look for a filename in the
  12015. list of entries. It might return 0 if no match is found.
  12016. @see ZipFile::ZipEntry
  12017. */
  12018. const ZipEntry* getEntry (const String& fileName) const throw();
  12019. /** Sorts the list of entries, based on the filename.
  12020. */
  12021. void sortEntriesByFilename();
  12022. /** Creates a stream that can read from one of the zip file's entries.
  12023. The stream that is returned must be deleted by the caller (and
  12024. zero might be returned if a stream can't be opened for some reason).
  12025. The stream must not be used after the ZipFile object that created
  12026. has been deleted.
  12027. */
  12028. InputStream* createStreamForEntry (int index);
  12029. /** Uncompresses all of the files in the zip file.
  12030. This will expand all the entires into a target directory. The relative
  12031. paths of the entries are used.
  12032. @param targetDirectory the root folder to uncompress to
  12033. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  12034. */
  12035. void uncompressTo (const File& targetDirectory,
  12036. bool shouldOverwriteFiles = true);
  12037. juce_UseDebuggingNewOperator
  12038. private:
  12039. class ZipInputStream;
  12040. class ZipFilenameComparator;
  12041. class ZipEntryInfo;
  12042. friend class ZipInputStream;
  12043. friend class ZipFilenameComparator;
  12044. friend class ZipEntryInfo;
  12045. OwnedArray <ZipEntryInfo> entries;
  12046. CriticalSection lock;
  12047. InputStream* inputStream;
  12048. ScopedPointer <InputStream> streamToDelete;
  12049. ScopedPointer <InputSource> inputSource;
  12050. #if JUCE_DEBUG
  12051. int numOpenStreams;
  12052. #endif
  12053. void init();
  12054. int findEndOfZipEntryTable (InputStream* in, int& numEntries);
  12055. static int compareElements (const ZipEntryInfo* first, const ZipEntryInfo* second);
  12056. ZipFile (const ZipFile&);
  12057. ZipFile& operator= (const ZipFile&);
  12058. };
  12059. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  12060. /*** End of inlined file: juce_ZipFile.h ***/
  12061. #endif
  12062. #ifndef __JUCE_SOCKET_JUCEHEADER__
  12063. /*** Start of inlined file: juce_Socket.h ***/
  12064. #ifndef __JUCE_SOCKET_JUCEHEADER__
  12065. #define __JUCE_SOCKET_JUCEHEADER__
  12066. /**
  12067. A wrapper for a streaming (TCP) socket.
  12068. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  12069. sockets, you could also try the InterprocessConnection class.
  12070. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  12071. */
  12072. class JUCE_API StreamingSocket
  12073. {
  12074. public:
  12075. /** Creates an uninitialised socket.
  12076. To connect it, use the connect() method, after which you can read() or write()
  12077. to it.
  12078. To wait for other sockets to connect to this one, the createListener() method
  12079. enters "listener" mode, and can be used to spawn new sockets for each connection
  12080. that comes along.
  12081. */
  12082. StreamingSocket();
  12083. /** Destructor. */
  12084. ~StreamingSocket();
  12085. /** Binds the socket to the specified local port.
  12086. @returns true on success; false may indicate that another socket is already bound
  12087. on the same port
  12088. */
  12089. bool bindToPort (int localPortNumber);
  12090. /** Tries to connect the socket to hostname:port.
  12091. If timeOutMillisecs is 0, then this method will block until the operating system
  12092. rejects the connection (which could take a long time).
  12093. @returns true if it succeeds.
  12094. @see isConnected
  12095. */
  12096. bool connect (const String& remoteHostname,
  12097. int remotePortNumber,
  12098. int timeOutMillisecs = 3000);
  12099. /** True if the socket is currently connected. */
  12100. bool isConnected() const throw() { return connected; }
  12101. /** Closes the connection. */
  12102. void close();
  12103. /** Returns the name of the currently connected host. */
  12104. const String& getHostName() const throw() { return hostName; }
  12105. /** Returns the port number that's currently open. */
  12106. int getPort() const throw() { return portNumber; }
  12107. /** True if the socket is connected to this machine rather than over the network. */
  12108. bool isLocal() const throw();
  12109. /** Waits until the socket is ready for reading or writing.
  12110. If readyForReading is true, it will wait until the socket is ready for
  12111. reading; if false, it will wait until it's ready for writing.
  12112. If the timeout is < 0, it will wait forever, or else will give up after
  12113. the specified time.
  12114. If the socket is ready on return, this returns 1. If it times-out before
  12115. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  12116. */
  12117. int waitUntilReady (bool readyForReading,
  12118. int timeoutMsecs) const;
  12119. /** Reads bytes from the socket.
  12120. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  12121. maxBytesToRead bytes have been read, (or until an error occurs). If this
  12122. flag is false, the method will return as much data as is currently available
  12123. without blocking.
  12124. @returns the number of bytes read, or -1 if there was an error.
  12125. @see waitUntilReady
  12126. */
  12127. int read (void* destBuffer, int maxBytesToRead,
  12128. bool blockUntilSpecifiedAmountHasArrived);
  12129. /** Writes bytes to the socket from a buffer.
  12130. Note that this method will block unless you have checked the socket is ready
  12131. for writing before calling it (see the waitUntilReady() method).
  12132. @returns the number of bytes written, or -1 if there was an error.
  12133. */
  12134. int write (const void* sourceBuffer, int numBytesToWrite);
  12135. /** Puts this socket into "listener" mode.
  12136. When in this mode, your thread can call waitForNextConnection() repeatedly,
  12137. which will spawn new sockets for each new connection, so that these can
  12138. be handled in parallel by other threads.
  12139. @param portNumber the port number to listen on
  12140. @param localHostName the interface address to listen on - pass an empty
  12141. string to listen on all addresses
  12142. @returns true if it manages to open the socket successfully.
  12143. @see waitForNextConnection
  12144. */
  12145. bool createListener (int portNumber, const String& localHostName = String::empty);
  12146. /** When in "listener" mode, this waits for a connection and spawns it as a new
  12147. socket.
  12148. The object that gets returned will be owned by the caller.
  12149. This method can only be called after using createListener().
  12150. @see createListener
  12151. */
  12152. StreamingSocket* waitForNextConnection() const;
  12153. juce_UseDebuggingNewOperator
  12154. private:
  12155. String hostName;
  12156. int volatile portNumber, handle;
  12157. bool connected, isListener;
  12158. StreamingSocket (const String& hostname, int portNumber, int handle);
  12159. StreamingSocket (const StreamingSocket&);
  12160. StreamingSocket& operator= (const StreamingSocket&);
  12161. };
  12162. /**
  12163. A wrapper for a datagram (UDP) socket.
  12164. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  12165. sockets, you could also try the InterprocessConnection class.
  12166. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  12167. */
  12168. class JUCE_API DatagramSocket
  12169. {
  12170. public:
  12171. /**
  12172. Creates an (uninitialised) datagram socket.
  12173. The localPortNumber is the port on which to bind this socket. If this value is 0,
  12174. the port number is assigned by the operating system.
  12175. To use the socket for sending, call the connect() method. This will not immediately
  12176. make a connection, but will save the destination you've provided. After this, you can
  12177. call read() or write().
  12178. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  12179. (may require extra privileges on linux)
  12180. To wait for other sockets to connect to this one, call waitForNextConnection().
  12181. */
  12182. DatagramSocket (int localPortNumber,
  12183. bool enableBroadcasting = false);
  12184. /** Destructor. */
  12185. ~DatagramSocket();
  12186. /** Binds the socket to the specified local port.
  12187. @returns true on success; false may indicate that another socket is already bound
  12188. on the same port
  12189. */
  12190. bool bindToPort (int localPortNumber);
  12191. /** Tries to connect the socket to hostname:port.
  12192. If timeOutMillisecs is 0, then this method will block until the operating system
  12193. rejects the connection (which could take a long time).
  12194. @returns true if it succeeds.
  12195. @see isConnected
  12196. */
  12197. bool connect (const String& remoteHostname,
  12198. int remotePortNumber,
  12199. int timeOutMillisecs = 3000);
  12200. /** True if the socket is currently connected. */
  12201. bool isConnected() const throw() { return connected; }
  12202. /** Closes the connection. */
  12203. void close();
  12204. /** Returns the name of the currently connected host. */
  12205. const String& getHostName() const throw() { return hostName; }
  12206. /** Returns the port number that's currently open. */
  12207. int getPort() const throw() { return portNumber; }
  12208. /** True if the socket is connected to this machine rather than over the network. */
  12209. bool isLocal() const throw();
  12210. /** Waits until the socket is ready for reading or writing.
  12211. If readyForReading is true, it will wait until the socket is ready for
  12212. reading; if false, it will wait until it's ready for writing.
  12213. If the timeout is < 0, it will wait forever, or else will give up after
  12214. the specified time.
  12215. If the socket is ready on return, this returns 1. If it times-out before
  12216. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  12217. */
  12218. int waitUntilReady (bool readyForReading,
  12219. int timeoutMsecs) const;
  12220. /** Reads bytes from the socket.
  12221. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  12222. maxBytesToRead bytes have been read, (or until an error occurs). If this
  12223. flag is false, the method will return as much data as is currently available
  12224. without blocking.
  12225. @returns the number of bytes read, or -1 if there was an error.
  12226. @see waitUntilReady
  12227. */
  12228. int read (void* destBuffer, int maxBytesToRead,
  12229. bool blockUntilSpecifiedAmountHasArrived);
  12230. /** Writes bytes to the socket from a buffer.
  12231. Note that this method will block unless you have checked the socket is ready
  12232. for writing before calling it (see the waitUntilReady() method).
  12233. @returns the number of bytes written, or -1 if there was an error.
  12234. */
  12235. int write (const void* sourceBuffer, int numBytesToWrite);
  12236. /** This waits for incoming data to be sent, and returns a socket that can be used
  12237. to read it.
  12238. The object that gets returned is owned by the caller, and can't be used for
  12239. sending, but can be used to read the data.
  12240. */
  12241. DatagramSocket* waitForNextConnection() const;
  12242. juce_UseDebuggingNewOperator
  12243. private:
  12244. String hostName;
  12245. int volatile portNumber, handle;
  12246. bool connected, allowBroadcast;
  12247. void* serverAddress;
  12248. DatagramSocket (const String& hostname, int portNumber, int handle, int localPortNumber);
  12249. DatagramSocket (const DatagramSocket&);
  12250. DatagramSocket& operator= (const DatagramSocket&);
  12251. };
  12252. #endif // __JUCE_SOCKET_JUCEHEADER__
  12253. /*** End of inlined file: juce_Socket.h ***/
  12254. #endif
  12255. #ifndef __JUCE_URL_JUCEHEADER__
  12256. /*** Start of inlined file: juce_URL.h ***/
  12257. #ifndef __JUCE_URL_JUCEHEADER__
  12258. #define __JUCE_URL_JUCEHEADER__
  12259. /**
  12260. Represents a URL and has a bunch of useful functions to manipulate it.
  12261. This class can be used to launch URLs in browsers, and also to create
  12262. InputStreams that can read from remote http or ftp sources.
  12263. */
  12264. class JUCE_API URL
  12265. {
  12266. public:
  12267. /** Creates an empty URL. */
  12268. URL();
  12269. /** Creates a URL from a string. */
  12270. URL (const String& url);
  12271. /** Creates a copy of another URL. */
  12272. URL (const URL& other);
  12273. /** Destructor. */
  12274. ~URL();
  12275. /** Copies this URL from another one. */
  12276. URL& operator= (const URL& other);
  12277. /** Returns a string version of the URL.
  12278. If includeGetParameters is true and any parameters have been set with the
  12279. withParameter() method, then the string will have these appended on the
  12280. end and url-encoded.
  12281. */
  12282. const String toString (bool includeGetParameters) const;
  12283. /** True if it seems to be valid. */
  12284. bool isWellFormed() const;
  12285. /** Returns just the domain part of the URL.
  12286. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  12287. */
  12288. const String getDomain() const;
  12289. /** Returns the path part of the URL.
  12290. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  12291. */
  12292. const String getSubPath() const;
  12293. /** Returns the scheme of the URL.
  12294. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  12295. include the colon).
  12296. */
  12297. const String getScheme() const;
  12298. /** Returns a new version of this URL that uses a different sub-path.
  12299. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  12300. "bar", it'll return "http://www.xyz.com/bar?x=1".
  12301. */
  12302. const URL withNewSubPath (const String& newPath) const;
  12303. /** Returns a copy of this URL, with a GET or POST parameter added to the end.
  12304. Any control characters in the value will be encoded.
  12305. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  12306. would produce a new url whose toString(true) method would return
  12307. "www.fish.com?amount=some+fish".
  12308. */
  12309. const URL withParameter (const String& parameterName,
  12310. const String& parameterValue) const;
  12311. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  12312. When performing a POST where one of your parameters is a binary file, this
  12313. lets you specify the file.
  12314. Note that the filename is stored, but the file itself won't actually be read
  12315. until this URL is later used to create a network input stream.
  12316. */
  12317. const URL withFileToUpload (const String& parameterName,
  12318. const File& fileToUpload,
  12319. const String& mimeType) const;
  12320. /** Returns a set of all the parameters encoded into the url.
  12321. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  12322. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  12323. The values returned will have been cleaned up to remove any escape characters.
  12324. @see getNamedParameter, withParameter
  12325. */
  12326. const StringPairArray& getParameters() const;
  12327. /** Returns the set of files that should be uploaded as part of a POST operation.
  12328. This is the set of files that were added to the URL with the withFileToUpload()
  12329. method.
  12330. */
  12331. const StringPairArray& getFilesToUpload() const;
  12332. /** Returns the set of mime types associated with each of the upload files.
  12333. */
  12334. const StringPairArray& getMimeTypesOfUploadFiles() const;
  12335. /** Returns a copy of this URL, with a block of data to send as the POST data.
  12336. If you're setting the POST data, be careful not to have any parameters set
  12337. as well, otherwise it'll all get thrown in together, and might not have the
  12338. desired effect.
  12339. If the URL already contains some POST data, this will replace it, rather
  12340. than being appended to it.
  12341. This data will only be used if you specify a post operation when you call
  12342. createInputStream().
  12343. */
  12344. const URL withPOSTData (const String& postData) const;
  12345. /** Returns the data that was set using withPOSTData().
  12346. */
  12347. const String getPostData() const { return postData; }
  12348. /** Tries to launch the system's default browser to open the URL.
  12349. Returns true if this seems to have worked.
  12350. */
  12351. bool launchInDefaultBrowser() const;
  12352. /** Takes a guess as to whether a string might be a valid website address.
  12353. This isn't foolproof!
  12354. */
  12355. static bool isProbablyAWebsiteURL (const String& possibleURL);
  12356. /** Takes a guess as to whether a string might be a valid email address.
  12357. This isn't foolproof!
  12358. */
  12359. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  12360. /** This callback function can be used by the createInputStream() method.
  12361. It allows your app to receive progress updates during a lengthy POST operation. If you
  12362. want to continue the operation, this should return true, or false to abort.
  12363. */
  12364. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  12365. /** Attempts to open a stream that can read from this URL.
  12366. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  12367. the paramters, otherwise it'll encode them into the
  12368. URL and do a 'GET'.
  12369. @param progressCallback if this is non-zero, it lets you supply a callback function
  12370. to keep track of the operation's progress. This can be useful
  12371. for lengthy POST operations, so that you can provide user feedback.
  12372. @param progressCallbackContext if a callback is specified, this value will be passed to
  12373. the function
  12374. @param extraHeaders if not empty, this string is appended onto the headers that
  12375. are used for the request. It must therefore be a valid set of HTML
  12376. header directives, separated by newlines.
  12377. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  12378. a negative number, it will be infinite. Otherwise it specifies a
  12379. time in milliseconds.
  12380. @param responseHeaders if this is non-zero, all the (key, value) pairs received as headers
  12381. in the response will be stored in this array
  12382. @returns an input stream that the caller must delete, or a null pointer if there was an
  12383. error trying to open it.
  12384. */
  12385. InputStream* createInputStream (bool usePostCommand,
  12386. OpenStreamProgressCallback* progressCallback = 0,
  12387. void* progressCallbackContext = 0,
  12388. const String& extraHeaders = String::empty,
  12389. int connectionTimeOutMs = 0,
  12390. StringPairArray* responseHeaders = 0) const;
  12391. /** Tries to download the entire contents of this URL into a binary data block.
  12392. If it succeeds, this will return true and append the data it read onto the end
  12393. of the memory block.
  12394. @param destData the memory block to append the new data to
  12395. @param usePostCommand whether to use a POST command to get the data (uses
  12396. a GET command if this is false)
  12397. @see readEntireTextStream, readEntireXmlStream
  12398. */
  12399. bool readEntireBinaryStream (MemoryBlock& destData,
  12400. bool usePostCommand = false) const;
  12401. /** Tries to download the entire contents of this URL as a string.
  12402. If it fails, this will return an empty string, otherwise it will return the
  12403. contents of the downloaded file. If you need to distinguish between a read
  12404. operation that fails and one that returns an empty string, you'll need to use
  12405. a different method, such as readEntireBinaryStream().
  12406. @param usePostCommand whether to use a POST command to get the data (uses
  12407. a GET command if this is false)
  12408. @see readEntireBinaryStream, readEntireXmlStream
  12409. */
  12410. const String readEntireTextStream (bool usePostCommand = false) const;
  12411. /** Tries to download the entire contents of this URL and parse it as XML.
  12412. If it fails, or if the text that it reads can't be parsed as XML, this will
  12413. return 0.
  12414. When it returns a valid XmlElement object, the caller is responsibile for deleting
  12415. this object when no longer needed.
  12416. @param usePostCommand whether to use a POST command to get the data (uses
  12417. a GET command if this is false)
  12418. @see readEntireBinaryStream, readEntireTextStream
  12419. */
  12420. XmlElement* readEntireXmlStream (bool usePostCommand = false) const;
  12421. /** Adds escape sequences to a string to encode any characters that aren't
  12422. legal in a URL.
  12423. E.g. any spaces will be replaced with "%20".
  12424. This is the opposite of removeEscapeChars().
  12425. If isParameter is true, it means that the string is going to be used
  12426. as a parameter, so it also encodes '$' and ',' (which would otherwise
  12427. be legal in a URL.
  12428. @see removeEscapeChars
  12429. */
  12430. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  12431. bool isParameter);
  12432. /** Replaces any escape character sequences in a string with their original
  12433. character codes.
  12434. E.g. any instances of "%20" will be replaced by a space.
  12435. This is the opposite of addEscapeChars().
  12436. @see addEscapeChars
  12437. */
  12438. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  12439. juce_UseDebuggingNewOperator
  12440. private:
  12441. String url, postData;
  12442. StringPairArray parameters, filesToUpload, mimeTypes;
  12443. };
  12444. #endif // __JUCE_URL_JUCEHEADER__
  12445. /*** End of inlined file: juce_URL.h ***/
  12446. #endif
  12447. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12448. /*** Start of inlined file: juce_BufferedInputStream.h ***/
  12449. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12450. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12451. /** Wraps another input stream, and reads from it using an intermediate buffer
  12452. If you're using an input stream such as a file input stream, and making lots of
  12453. small read accesses to it, it's probably sensible to wrap it in one of these,
  12454. so that the source stream gets accessed in larger chunk sizes, meaning less
  12455. work for the underlying stream.
  12456. */
  12457. class JUCE_API BufferedInputStream : public InputStream
  12458. {
  12459. public:
  12460. /** Creates a BufferedInputStream from an input source.
  12461. @param sourceStream the source stream to read from
  12462. @param bufferSize the size of reservoir to use to buffer the source
  12463. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  12464. deleted by this object when it is itself deleted.
  12465. */
  12466. BufferedInputStream (InputStream* sourceStream,
  12467. int bufferSize,
  12468. bool deleteSourceWhenDestroyed);
  12469. /** Destructor.
  12470. This may also delete the source stream, if that option was chosen when the
  12471. buffered stream was created.
  12472. */
  12473. ~BufferedInputStream();
  12474. int64 getTotalLength();
  12475. int64 getPosition();
  12476. bool setPosition (int64 newPosition);
  12477. int read (void* destBuffer, int maxBytesToRead);
  12478. const String readString();
  12479. bool isExhausted();
  12480. juce_UseDebuggingNewOperator
  12481. private:
  12482. InputStream* const source;
  12483. ScopedPointer <InputStream> sourceToDelete;
  12484. int bufferSize;
  12485. int64 position, lastReadPos, bufferStart, bufferOverlap;
  12486. HeapBlock <char> buffer;
  12487. void ensureBuffered();
  12488. BufferedInputStream (const BufferedInputStream&);
  12489. BufferedInputStream& operator= (const BufferedInputStream&);
  12490. };
  12491. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12492. /*** End of inlined file: juce_BufferedInputStream.h ***/
  12493. #endif
  12494. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12495. /*** Start of inlined file: juce_FileInputSource.h ***/
  12496. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12497. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12498. /**
  12499. A type of InputSource that represents a normal file.
  12500. @see InputSource
  12501. */
  12502. class JUCE_API FileInputSource : public InputSource
  12503. {
  12504. public:
  12505. FileInputSource (const File& file);
  12506. ~FileInputSource();
  12507. InputStream* createInputStream();
  12508. InputStream* createInputStreamFor (const String& relatedItemPath);
  12509. int64 hashCode() const;
  12510. juce_UseDebuggingNewOperator
  12511. private:
  12512. const File file;
  12513. FileInputSource (const FileInputSource&);
  12514. FileInputSource& operator= (const FileInputSource&);
  12515. };
  12516. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12517. /*** End of inlined file: juce_FileInputSource.h ***/
  12518. #endif
  12519. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12520. /*** Start of inlined file: juce_GZIPCompressorOutputStream.h ***/
  12521. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12522. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12523. class GZIPCompressorHelper;
  12524. /**
  12525. A stream which uses zlib to compress the data written into it.
  12526. @see GZIPDecompressorInputStream
  12527. */
  12528. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  12529. {
  12530. public:
  12531. /** Creates a compression stream.
  12532. @param destStream the stream into which the compressed data should
  12533. be written
  12534. @param compressionLevel how much to compress the data, between 1 and 9, where
  12535. 1 is the fastest/lowest compression, and 9 is the
  12536. slowest/highest compression. Any value outside this range
  12537. indicates that a default compression level should be used.
  12538. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  12539. this stream is destroyed
  12540. @param noWrap this is used internally by the ZipFile class
  12541. and should be ignored by user applications
  12542. */
  12543. GZIPCompressorOutputStream (OutputStream* destStream,
  12544. int compressionLevel = 0,
  12545. bool deleteDestStreamWhenDestroyed = false,
  12546. bool noWrap = false);
  12547. /** Destructor. */
  12548. ~GZIPCompressorOutputStream();
  12549. void flush();
  12550. int64 getPosition();
  12551. bool setPosition (int64 newPosition);
  12552. bool write (const void* destBuffer, int howMany);
  12553. juce_UseDebuggingNewOperator
  12554. private:
  12555. OutputStream* const destStream;
  12556. ScopedPointer <OutputStream> streamToDelete;
  12557. HeapBlock <uint8> buffer;
  12558. ScopedPointer <GZIPCompressorHelper> helper;
  12559. bool doNextBlock();
  12560. GZIPCompressorOutputStream (const GZIPCompressorOutputStream&);
  12561. GZIPCompressorOutputStream& operator= (const GZIPCompressorOutputStream&);
  12562. };
  12563. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12564. /*** End of inlined file: juce_GZIPCompressorOutputStream.h ***/
  12565. #endif
  12566. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12567. /*** Start of inlined file: juce_GZIPDecompressorInputStream.h ***/
  12568. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12569. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12570. class GZIPDecompressHelper;
  12571. /**
  12572. This stream will decompress a source-stream using zlib.
  12573. Tip: if you're reading lots of small items from one of these streams, you
  12574. can increase the performance enormously by passing it through a
  12575. BufferedInputStream, so that it has to read larger blocks less often.
  12576. @see GZIPCompressorOutputStream
  12577. */
  12578. class JUCE_API GZIPDecompressorInputStream : public InputStream
  12579. {
  12580. public:
  12581. /** Creates a decompressor stream.
  12582. @param sourceStream the stream to read from
  12583. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  12584. when this object is destroyed
  12585. @param noWrap this is used internally by the ZipFile class
  12586. and should be ignored by user applications
  12587. @param uncompressedStreamLength if the creator knows the length that the
  12588. uncompressed stream will be, then it can supply this
  12589. value, which will be returned by getTotalLength()
  12590. */
  12591. GZIPDecompressorInputStream (InputStream* sourceStream,
  12592. bool deleteSourceWhenDestroyed,
  12593. bool noWrap = false,
  12594. int64 uncompressedStreamLength = -1);
  12595. /** Destructor. */
  12596. ~GZIPDecompressorInputStream();
  12597. int64 getPosition();
  12598. bool setPosition (int64 pos);
  12599. int64 getTotalLength();
  12600. bool isExhausted();
  12601. int read (void* destBuffer, int maxBytesToRead);
  12602. juce_UseDebuggingNewOperator
  12603. private:
  12604. InputStream* const sourceStream;
  12605. ScopedPointer <InputStream> streamToDelete;
  12606. const int64 uncompressedStreamLength;
  12607. const bool noWrap;
  12608. bool isEof;
  12609. int activeBufferSize;
  12610. int64 originalSourcePos, currentPos;
  12611. HeapBlock <uint8> buffer;
  12612. ScopedPointer <GZIPDecompressHelper> helper;
  12613. GZIPDecompressorInputStream (const GZIPDecompressorInputStream&);
  12614. GZIPDecompressorInputStream& operator= (const GZIPDecompressorInputStream&);
  12615. };
  12616. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12617. /*** End of inlined file: juce_GZIPDecompressorInputStream.h ***/
  12618. #endif
  12619. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  12620. #endif
  12621. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  12622. #endif
  12623. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12624. /*** Start of inlined file: juce_MemoryInputStream.h ***/
  12625. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12626. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12627. /**
  12628. Allows a block of data and to be accessed as a stream.
  12629. This can either be used to refer to a shared block of memory, or can make its
  12630. own internal copy of the data when the MemoryInputStream is created.
  12631. */
  12632. class JUCE_API MemoryInputStream : public InputStream
  12633. {
  12634. public:
  12635. /** Creates a MemoryInputStream.
  12636. @param sourceData the block of data to use as the stream's source
  12637. @param sourceDataSize the number of bytes in the source data block
  12638. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  12639. the source data, so this data shouldn't be changed
  12640. for the lifetime of the stream; if this parameter is
  12641. true, the stream will make its own copy of the
  12642. data and use that.
  12643. */
  12644. MemoryInputStream (const void* sourceData,
  12645. size_t sourceDataSize,
  12646. bool keepInternalCopyOfData);
  12647. /** Creates a MemoryInputStream.
  12648. @param data a block of data to use as the stream's source
  12649. @param keepInternalCopyOfData if false, the stream will just keep a reference to
  12650. the source data, so this data shouldn't be changed
  12651. for the lifetime of the stream; if this parameter is
  12652. true, the stream will make its own copy of the
  12653. data and use that.
  12654. */
  12655. MemoryInputStream (const MemoryBlock& data,
  12656. bool keepInternalCopyOfData);
  12657. /** Destructor. */
  12658. ~MemoryInputStream();
  12659. int64 getPosition();
  12660. bool setPosition (int64 pos);
  12661. int64 getTotalLength();
  12662. bool isExhausted();
  12663. int read (void* destBuffer, int maxBytesToRead);
  12664. juce_UseDebuggingNewOperator
  12665. private:
  12666. const char* data;
  12667. size_t dataSize, position;
  12668. MemoryBlock internalCopy;
  12669. MemoryInputStream (const MemoryInputStream&);
  12670. MemoryInputStream& operator= (const MemoryInputStream&);
  12671. };
  12672. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12673. /*** End of inlined file: juce_MemoryInputStream.h ***/
  12674. #endif
  12675. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12676. /*** Start of inlined file: juce_MemoryOutputStream.h ***/
  12677. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12678. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12679. /** Writes data to an internal memory buffer, which grows as required.
  12680. The data that was written into the stream can then be accessed later as
  12681. a contiguous block of memory.
  12682. */
  12683. class JUCE_API MemoryOutputStream : public OutputStream
  12684. {
  12685. public:
  12686. /** Creates a memory stream ready for writing into.
  12687. @param initialSize the intial amount of space to allocate for writing into
  12688. @param granularity the increments by which the internal storage will be increased
  12689. @param memoryBlockToWriteTo if this is non-zero, then this block will be used as the
  12690. place that the data gets stored. If it's zero, the stream
  12691. will allocate its own storage internally, which you can
  12692. access using getData() and getDataSize()
  12693. */
  12694. MemoryOutputStream (size_t initialSize = 256,
  12695. size_t granularity = 256,
  12696. MemoryBlock* memoryBlockToWriteTo = 0);
  12697. /** Destructor.
  12698. This will free any data that was written to it.
  12699. */
  12700. ~MemoryOutputStream();
  12701. /** Returns a pointer to the data that has been written to the stream.
  12702. @see getDataSize
  12703. */
  12704. const char* getData() const throw();
  12705. /** Returns the number of bytes of data that have been written to the stream.
  12706. @see getData
  12707. */
  12708. size_t getDataSize() const throw() { return size; }
  12709. /** Resets the stream, clearing any data that has been written to it so far. */
  12710. void reset() throw();
  12711. /** Returns a String created from the (UTF8) data that has been written to the stream. */
  12712. const String toUTF8() const;
  12713. void flush();
  12714. bool write (const void* buffer, int howMany);
  12715. int64 getPosition() { return position; }
  12716. bool setPosition (int64 newPosition);
  12717. juce_UseDebuggingNewOperator
  12718. private:
  12719. MemoryBlock* data;
  12720. ScopedPointer <MemoryBlock> dataToDelete;
  12721. size_t position, size, blockSize;
  12722. MemoryOutputStream (const MemoryOutputStream&);
  12723. MemoryOutputStream& operator= (const MemoryOutputStream&);
  12724. };
  12725. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12726. /*** End of inlined file: juce_MemoryOutputStream.h ***/
  12727. #endif
  12728. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  12729. #endif
  12730. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12731. /*** Start of inlined file: juce_SubregionStream.h ***/
  12732. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12733. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12734. /** Wraps another input stream, and reads from a specific part of it.
  12735. This lets you take a subsection of a stream and present it as an entire
  12736. stream in its own right.
  12737. */
  12738. class JUCE_API SubregionStream : public InputStream
  12739. {
  12740. public:
  12741. /** Creates a SubregionStream from an input source.
  12742. @param sourceStream the source stream to read from
  12743. @param startPositionInSourceStream this is the position in the source stream that
  12744. corresponds to position 0 in this stream
  12745. @param lengthOfSourceStream this specifies the maximum number of bytes
  12746. from the source stream that will be passed through
  12747. by this stream. When the position of this stream
  12748. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  12749. If the length passed in here is greater than the length
  12750. of the source stream (as returned by getTotalLength()),
  12751. then the smaller value will be used.
  12752. Passing a negative value for this parameter means it
  12753. will keep reading until the source's end-of-stream.
  12754. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  12755. deleted by this object when it is itself deleted.
  12756. */
  12757. SubregionStream (InputStream* sourceStream,
  12758. int64 startPositionInSourceStream,
  12759. int64 lengthOfSourceStream,
  12760. bool deleteSourceWhenDestroyed);
  12761. /** Destructor.
  12762. This may also delete the source stream, if that option was chosen when the
  12763. buffered stream was created.
  12764. */
  12765. ~SubregionStream();
  12766. int64 getTotalLength();
  12767. int64 getPosition();
  12768. bool setPosition (int64 newPosition);
  12769. int read (void* destBuffer, int maxBytesToRead);
  12770. bool isExhausted();
  12771. juce_UseDebuggingNewOperator
  12772. private:
  12773. InputStream* const source;
  12774. ScopedPointer <InputStream> sourceToDelete;
  12775. const int64 startPositionInSourceStream, lengthOfSourceStream;
  12776. SubregionStream (const SubregionStream&);
  12777. SubregionStream& operator= (const SubregionStream&);
  12778. };
  12779. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12780. /*** End of inlined file: juce_SubregionStream.h ***/
  12781. #endif
  12782. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  12783. #endif
  12784. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12785. /*** Start of inlined file: juce_LocalisedStrings.h ***/
  12786. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12787. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12788. /** Used in the same way as the T(text) macro, this will attempt to translate a
  12789. string into a localised version using the LocalisedStrings class.
  12790. @see LocalisedStrings
  12791. */
  12792. #define TRANS(stringLiteral) \
  12793. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  12794. /**
  12795. Used to convert strings to localised foreign-language versions.
  12796. This is basically a look-up table of strings and their translated equivalents.
  12797. It can be loaded from a text file, so that you can supply a set of localised
  12798. versions of strings that you use in your app.
  12799. To use it in your code, simply call the translate() method on each string that
  12800. might have foreign versions, and if none is found, the method will just return
  12801. the original string.
  12802. The translation file should start with some lines specifying a description of
  12803. the language it contains, and also a list of ISO country codes where it might
  12804. be appropriate to use the file. After that, each line of the file should contain
  12805. a pair of quoted strings with an '=' sign.
  12806. E.g. for a french translation, the file might be:
  12807. @code
  12808. language: French
  12809. countries: fr be mc ch lu
  12810. "hello" = "bonjour"
  12811. "goodbye" = "au revoir"
  12812. @endcode
  12813. If the strings need to contain a quote character, they can use '\"' instead, and
  12814. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  12815. (you can use this to add comments).
  12816. Note that this is a singleton class, so don't create or destroy the object directly.
  12817. There's also a TRANS(text) macro defined to make it easy to use the this.
  12818. E.g. @code
  12819. printSomething (TRANS("hello"));
  12820. @endcode
  12821. This macro is used in the Juce classes themselves, so your application has a chance to
  12822. intercept and translate any internal Juce text strings that might be shown. (You can easily
  12823. get a list of all the messages by searching for the TRANS() macro in the Juce source
  12824. code).
  12825. */
  12826. class JUCE_API LocalisedStrings
  12827. {
  12828. public:
  12829. /** Creates a set of translations from the text of a translation file.
  12830. When you create one of these, you can call setCurrentMappings() to make it
  12831. the set of mappings that the system's using.
  12832. */
  12833. LocalisedStrings (const String& fileContents);
  12834. /** Creates a set of translations from a file.
  12835. When you create one of these, you can call setCurrentMappings() to make it
  12836. the set of mappings that the system's using.
  12837. */
  12838. LocalisedStrings (const File& fileToLoad);
  12839. /** Destructor. */
  12840. ~LocalisedStrings();
  12841. /** Selects the current set of mappings to be used by the system.
  12842. The object you pass in will be automatically deleted when no longer needed, so
  12843. don't keep a pointer to it. You can also pass in zero to remove the current
  12844. mappings.
  12845. See also the TRANS() macro, which uses the current set to do its translation.
  12846. @see translateWithCurrentMappings
  12847. */
  12848. static void setCurrentMappings (LocalisedStrings* newTranslations);
  12849. /** Returns the currently selected set of mappings.
  12850. This is the object that was last passed to setCurrentMappings(). It may
  12851. be 0 if none has been created.
  12852. */
  12853. static LocalisedStrings* getCurrentMappings();
  12854. /** Tries to translate a string using the currently selected set of mappings.
  12855. If no mapping has been set, or if the mapping doesn't contain a translation
  12856. for the string, this will just return the original string.
  12857. See also the TRANS() macro, which uses this method to do its translation.
  12858. @see setCurrentMappings, getCurrentMappings
  12859. */
  12860. static const String translateWithCurrentMappings (const String& text);
  12861. /** Tries to translate a string using the currently selected set of mappings.
  12862. If no mapping has been set, or if the mapping doesn't contain a translation
  12863. for the string, this will just return the original string.
  12864. See also the TRANS() macro, which uses this method to do its translation.
  12865. @see setCurrentMappings, getCurrentMappings
  12866. */
  12867. static const String translateWithCurrentMappings (const char* text);
  12868. /** Attempts to look up a string and return its localised version.
  12869. If the string isn't found in the list, the original string will be returned.
  12870. */
  12871. const String translate (const String& text) const;
  12872. /** Returns the name of the language specified in the translation file.
  12873. This is specified in the file using a line starting with "language:", e.g.
  12874. @code
  12875. language: german
  12876. @endcode
  12877. */
  12878. const String getLanguageName() const { return languageName; }
  12879. /** Returns the list of suitable country codes listed in the translation file.
  12880. These is specified in the file using a line starting with "countries:", e.g.
  12881. @code
  12882. countries: fr be mc ch lu
  12883. @endcode
  12884. The country codes are supposed to be 2-character ISO complient codes.
  12885. */
  12886. const StringArray getCountryCodes() const { return countryCodes; }
  12887. /** Indicates whether to use a case-insensitive search when looking up a string.
  12888. This defaults to true.
  12889. */
  12890. void setIgnoresCase (const bool shouldIgnoreCase);
  12891. juce_UseDebuggingNewOperator
  12892. private:
  12893. String languageName;
  12894. StringArray countryCodes;
  12895. StringPairArray translations;
  12896. void loadFromText (const String& fileContents);
  12897. };
  12898. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12899. /*** End of inlined file: juce_LocalisedStrings.h ***/
  12900. #endif
  12901. #ifndef __JUCE_STRING_JUCEHEADER__
  12902. #endif
  12903. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  12904. #endif
  12905. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  12906. #endif
  12907. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  12908. #endif
  12909. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  12910. /*** Start of inlined file: juce_XmlDocument.h ***/
  12911. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  12912. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  12913. /**
  12914. Parses a text-based XML document and creates an XmlElement object from it.
  12915. The parser will parse DTDs to load external entities but won't
  12916. check the document for validity against the DTD.
  12917. e.g.
  12918. @code
  12919. XmlDocument myDocument (File ("myfile.xml"));
  12920. XmlElement* mainElement = myDocument.getDocumentElement();
  12921. if (mainElement == 0)
  12922. {
  12923. String error = myDocument.getLastParseError();
  12924. }
  12925. else
  12926. {
  12927. ..use the element
  12928. }
  12929. @endcode
  12930. @see XmlElement
  12931. */
  12932. class JUCE_API XmlDocument
  12933. {
  12934. public:
  12935. /** Creates an XmlDocument from the xml text.
  12936. The text doesn't actually get parsed until the getDocumentElement() method is
  12937. called.
  12938. */
  12939. XmlDocument (const String& documentText);
  12940. /** Creates an XmlDocument from a file.
  12941. The text doesn't actually get parsed until the getDocumentElement() method is
  12942. called.
  12943. */
  12944. XmlDocument (const File& file);
  12945. /** Destructor. */
  12946. ~XmlDocument();
  12947. /** Creates an XmlElement object to represent the main document node.
  12948. This method will do the actual parsing of the text, and if there's a
  12949. parse error, it may returns 0 (and you can find out the error using
  12950. the getLastParseError() method).
  12951. @param onlyReadOuterDocumentElement if true, the parser will only read the
  12952. first section of the file, and will only
  12953. return the outer document element - this
  12954. allows quick checking of large files to
  12955. see if they contain the correct type of
  12956. tag, without having to parse the entire file
  12957. @returns a new XmlElement which the caller will need to delete, or null if
  12958. there was an error.
  12959. @see getLastParseError
  12960. */
  12961. XmlElement* getDocumentElement (const bool onlyReadOuterDocumentElement = false);
  12962. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  12963. @returns the error, or an empty string if there was no error.
  12964. */
  12965. const String& getLastParseError() const throw();
  12966. /** Sets an input source object to use for parsing documents that reference external entities.
  12967. If the document has been created from a file, this probably won't be needed, but
  12968. if you're parsing some text and there might be a DTD that references external
  12969. files, you may need to create a custom input source that can retrieve the
  12970. other files it needs.
  12971. The object that is passed-in will be deleted automatically when no longer needed.
  12972. @see InputSource
  12973. */
  12974. void setInputSource (InputSource* const newSource) throw();
  12975. /** Sets a flag to change the treatment of empty text elements.
  12976. If this is true (the default state), then any text elements that contain only
  12977. whitespace characters will be ingored during parsing. If you need to catch
  12978. whitespace-only text, then you should set this to false before calling the
  12979. getDocumentElement() method.
  12980. */
  12981. void setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw();
  12982. juce_UseDebuggingNewOperator
  12983. private:
  12984. String originalText;
  12985. const juce_wchar* input;
  12986. bool outOfData, errorOccurred;
  12987. bool identifierLookupTable [128];
  12988. String lastError, dtdText;
  12989. StringArray tokenisedDTD;
  12990. bool needToLoadDTD, ignoreEmptyTextElements;
  12991. ScopedPointer <InputSource> inputSource;
  12992. void setLastError (const String& desc, const bool carryOn);
  12993. void skipHeader();
  12994. void skipNextWhiteSpace();
  12995. juce_wchar readNextChar() throw();
  12996. XmlElement* readNextElement (const bool alsoParseSubElements);
  12997. void readChildElements (XmlElement* parent);
  12998. int findNextTokenLength() throw();
  12999. void readQuotedString (String& result);
  13000. void readEntity (String& result);
  13001. static bool isXmlIdentifierCharSlow (juce_wchar c) throw();
  13002. bool isXmlIdentifierChar (juce_wchar c) const throw();
  13003. const String getFileContents (const String& filename) const;
  13004. const String expandEntity (const String& entity);
  13005. const String expandExternalEntity (const String& entity);
  13006. const String getParameterEntity (const String& entity);
  13007. XmlDocument (const XmlDocument&);
  13008. XmlDocument& operator= (const XmlDocument&);
  13009. };
  13010. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  13011. /*** End of inlined file: juce_XmlDocument.h ***/
  13012. #endif
  13013. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  13014. #endif
  13015. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  13016. #endif
  13017. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13018. /*** Start of inlined file: juce_InterProcessLock.h ***/
  13019. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13020. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13021. /**
  13022. Acts as a critical section which processes can use to block each other.
  13023. @see CriticalSection
  13024. */
  13025. class JUCE_API InterProcessLock
  13026. {
  13027. public:
  13028. /** Creates a lock object.
  13029. @param name a name that processes will use to identify this lock object
  13030. */
  13031. explicit InterProcessLock (const String& name);
  13032. /** Destructor.
  13033. This will also release the lock if it's currently held by this process.
  13034. */
  13035. ~InterProcessLock();
  13036. /** Attempts to lock the critical section.
  13037. @param timeOutMillisecs how many milliseconds to wait if the lock
  13038. is already held by another process - a value of
  13039. 0 will return immediately, negative values will wait
  13040. forever
  13041. @returns true if the lock could be gained within the timeout period, or
  13042. false if the timeout expired.
  13043. */
  13044. bool enter (int timeOutMillisecs = -1);
  13045. /** Releases the lock if it's currently held by this process.
  13046. */
  13047. void exit();
  13048. /**
  13049. Automatically locks and unlocks an InterProcessLock object.
  13050. This works like a ScopedLock, but using an InterprocessLock rather than
  13051. a CriticalSection.
  13052. @see ScopedLock
  13053. */
  13054. class ScopedLockType
  13055. {
  13056. public:
  13057. /** Creates a scoped lock.
  13058. As soon as it is created, this will lock the InterProcessLock, and
  13059. when the ScopedLockType object is deleted, the InterProcessLock will
  13060. be unlocked.
  13061. Note that since an InterprocessLock can fail due to errors, you should check
  13062. isLocked() to make sure that the lock was successful before using it.
  13063. Make sure this object is created and deleted by the same thread,
  13064. otherwise there are no guarantees what will happen! Best just to use it
  13065. as a local stack object, rather than creating one with the new() operator.
  13066. */
  13067. explicit ScopedLockType (InterProcessLock& lock) : lock_ (lock) { lockWasSuccessful = lock.enter(); }
  13068. /** Destructor.
  13069. The InterProcessLock will be unlocked when the destructor is called.
  13070. Make sure this object is created and deleted by the same thread,
  13071. otherwise there are no guarantees what will happen!
  13072. */
  13073. inline ~ScopedLockType() { lock_.exit(); }
  13074. /** Returns true if the InterProcessLock was successfully locked. */
  13075. bool isLocked() const throw() { return lockWasSuccessful; }
  13076. private:
  13077. InterProcessLock& lock_;
  13078. bool lockWasSuccessful;
  13079. ScopedLockType (const ScopedLockType&);
  13080. ScopedLockType& operator= (const ScopedLockType&);
  13081. };
  13082. juce_UseDebuggingNewOperator
  13083. private:
  13084. class Pimpl;
  13085. friend class ScopedPointer <Pimpl>;
  13086. ScopedPointer <Pimpl> pimpl;
  13087. CriticalSection lock;
  13088. String name;
  13089. InterProcessLock (const InterProcessLock&);
  13090. InterProcessLock& operator= (const InterProcessLock&);
  13091. };
  13092. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13093. /*** End of inlined file: juce_InterProcessLock.h ***/
  13094. #endif
  13095. #ifndef __JUCE_PROCESS_JUCEHEADER__
  13096. /*** Start of inlined file: juce_Process.h ***/
  13097. #ifndef __JUCE_PROCESS_JUCEHEADER__
  13098. #define __JUCE_PROCESS_JUCEHEADER__
  13099. /** Represents the current executable's process.
  13100. This contains methods for controlling the current application at the
  13101. process-level.
  13102. @see Thread, JUCEApplication
  13103. */
  13104. class JUCE_API Process
  13105. {
  13106. public:
  13107. enum ProcessPriority
  13108. {
  13109. LowPriority = 0,
  13110. NormalPriority = 1,
  13111. HighPriority = 2,
  13112. RealtimePriority = 3
  13113. };
  13114. /** Changes the current process's priority.
  13115. @param priority the process priority, where
  13116. 0=low, 1=normal, 2=high, 3=realtime
  13117. */
  13118. static void setPriority (const ProcessPriority priority);
  13119. /** Kills the current process immediately.
  13120. This is an emergency process terminator that kills the application
  13121. immediately - it's intended only for use only when something goes
  13122. horribly wrong.
  13123. @see JUCEApplication::quit
  13124. */
  13125. static void terminate();
  13126. /** Returns true if this application process is the one that the user is
  13127. currently using.
  13128. */
  13129. static bool isForegroundProcess();
  13130. /** Raises the current process's privilege level.
  13131. Does nothing if this isn't supported by the current OS, or if process
  13132. privilege level is fixed.
  13133. */
  13134. static void raisePrivilege();
  13135. /** Lowers the current process's privilege level.
  13136. Does nothing if this isn't supported by the current OS, or if process
  13137. privilege level is fixed.
  13138. */
  13139. static void lowerPrivilege();
  13140. /** Returns true if this process is being hosted by a debugger.
  13141. */
  13142. static bool JUCE_CALLTYPE isRunningUnderDebugger();
  13143. private:
  13144. Process();
  13145. Process (const Process&);
  13146. Process& operator= (const Process&);
  13147. };
  13148. #endif // __JUCE_PROCESS_JUCEHEADER__
  13149. /*** End of inlined file: juce_Process.h ***/
  13150. #endif
  13151. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  13152. /*** Start of inlined file: juce_ReadWriteLock.h ***/
  13153. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  13154. #define __JUCE_READWRITELOCK_JUCEHEADER__
  13155. /*** Start of inlined file: juce_WaitableEvent.h ***/
  13156. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  13157. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  13158. /**
  13159. Allows threads to wait for events triggered by other threads.
  13160. A thread can call wait() on a WaitableObject, and this will suspend the
  13161. calling thread until another thread wakes it up by calling the signal()
  13162. method.
  13163. */
  13164. class JUCE_API WaitableEvent
  13165. {
  13166. public:
  13167. /** Creates a WaitableEvent object.
  13168. @param manualReset If this is false, the event will be reset automatically when the wait()
  13169. method is called. If manualReset is true, then once the event is signalled,
  13170. the only way to reset it will be by calling the reset() method.
  13171. */
  13172. WaitableEvent (bool manualReset = false) throw();
  13173. /** Destructor.
  13174. If other threads are waiting on this object when it gets deleted, this
  13175. can cause nasty errors, so be careful!
  13176. */
  13177. ~WaitableEvent() throw();
  13178. /** Suspends the calling thread until the event has been signalled.
  13179. This will wait until the object's signal() method is called by another thread,
  13180. or until the timeout expires.
  13181. After the event has been signalled, this method will return true and if manualReset
  13182. was set to false in the WaitableEvent's constructor, then the event will be reset.
  13183. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  13184. value will cause it to wait forever.
  13185. @returns true if the object has been signalled, false if the timeout expires first.
  13186. @see signal, reset
  13187. */
  13188. bool wait (int timeOutMilliseconds = -1) const throw();
  13189. /** Wakes up any threads that are currently waiting on this object.
  13190. If signal() is called when nothing is waiting, the next thread to call wait()
  13191. will return immediately and reset the signal.
  13192. @see wait, reset
  13193. */
  13194. void signal() const throw();
  13195. /** Resets the event to an unsignalled state.
  13196. If it's not already signalled, this does nothing.
  13197. */
  13198. void reset() const throw();
  13199. juce_UseDebuggingNewOperator
  13200. private:
  13201. void* internal;
  13202. WaitableEvent (const WaitableEvent&);
  13203. WaitableEvent& operator= (const WaitableEvent&);
  13204. };
  13205. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  13206. /*** End of inlined file: juce_WaitableEvent.h ***/
  13207. /*** Start of inlined file: juce_Thread.h ***/
  13208. #ifndef __JUCE_THREAD_JUCEHEADER__
  13209. #define __JUCE_THREAD_JUCEHEADER__
  13210. /**
  13211. Encapsulates a thread.
  13212. Subclasses derive from Thread and implement the run() method, in which they
  13213. do their business. The thread can then be started with the startThread() method
  13214. and controlled with various other methods.
  13215. This class also contains some thread-related static methods, such
  13216. as sleep(), yield(), getCurrentThreadId() etc.
  13217. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  13218. MessageManagerLock
  13219. */
  13220. class JUCE_API Thread
  13221. {
  13222. public:
  13223. /**
  13224. Creates a thread.
  13225. When first created, the thread is not running. Use the startThread()
  13226. method to start it.
  13227. */
  13228. explicit Thread (const String& threadName);
  13229. /** Destructor.
  13230. Deleting a Thread object that is running will only give the thread a
  13231. brief opportunity to stop itself cleanly, so it's recommended that you
  13232. should always call stopThread() with a decent timeout before deleting,
  13233. to avoid the thread being forcibly killed (which is a Bad Thing).
  13234. */
  13235. virtual ~Thread();
  13236. /** Must be implemented to perform the thread's actual code.
  13237. Remember that the thread must regularly check the threadShouldExit()
  13238. method whilst running, and if this returns true it should return from
  13239. the run() method as soon as possible to avoid being forcibly killed.
  13240. @see threadShouldExit, startThread
  13241. */
  13242. virtual void run() = 0;
  13243. // Thread control functions..
  13244. /** Starts the thread running.
  13245. This will start the thread's run() method.
  13246. (if it's already started, startThread() won't do anything).
  13247. @see stopThread
  13248. */
  13249. void startThread();
  13250. /** Starts the thread with a given priority.
  13251. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  13252. If the thread is already running, its priority will be changed.
  13253. @see startThread, setPriority
  13254. */
  13255. void startThread (int priority);
  13256. /** Attempts to stop the thread running.
  13257. This method will cause the threadShouldExit() method to return true
  13258. and call notify() in case the thread is currently waiting.
  13259. Hopefully the thread will then respond to this by exiting cleanly, and
  13260. the stopThread method will wait for a given time-period for this to
  13261. happen.
  13262. If the thread is stuck and fails to respond after the time-out, it gets
  13263. forcibly killed, which is a very bad thing to happen, as it could still
  13264. be holding locks, etc. which are needed by other parts of your program.
  13265. @param timeOutMilliseconds The number of milliseconds to wait for the
  13266. thread to finish before killing it by force. A negative
  13267. value in here will wait forever.
  13268. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  13269. */
  13270. void stopThread (int timeOutMilliseconds);
  13271. /** Returns true if the thread is currently active */
  13272. bool isThreadRunning() const;
  13273. /** Sets a flag to tell the thread it should stop.
  13274. Calling this means that the threadShouldExit() method will then return true.
  13275. The thread should be regularly checking this to see whether it should exit.
  13276. If your thread makes use of wait(), you might want to call notify() after calling
  13277. this method, to interrupt any waits that might be in progress, and allow it
  13278. to reach a point where it can exit.
  13279. @see threadShouldExit
  13280. @see waitForThreadToExit
  13281. */
  13282. void signalThreadShouldExit();
  13283. /** Checks whether the thread has been told to stop running.
  13284. Threads need to check this regularly, and if it returns true, they should
  13285. return from their run() method at the first possible opportunity.
  13286. @see signalThreadShouldExit
  13287. */
  13288. inline bool threadShouldExit() const { return threadShouldExit_; }
  13289. /** Waits for the thread to stop.
  13290. This will waits until isThreadRunning() is false or until a timeout expires.
  13291. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  13292. is less than zero, it will wait forever.
  13293. @returns true if the thread exits, or false if the timeout expires first.
  13294. */
  13295. bool waitForThreadToExit (int timeOutMilliseconds) const;
  13296. /** Changes the thread's priority.
  13297. May return false if for some reason the priority can't be changed.
  13298. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  13299. of 5 is normal.
  13300. */
  13301. bool setPriority (int priority);
  13302. /** Changes the priority of the caller thread.
  13303. Similar to setPriority(), but this static method acts on the caller thread.
  13304. May return false if for some reason the priority can't be changed.
  13305. @see setPriority
  13306. */
  13307. static bool setCurrentThreadPriority (int priority);
  13308. /** Sets the affinity mask for the thread.
  13309. This will only have an effect next time the thread is started - i.e. if the
  13310. thread is already running when called, it'll have no effect.
  13311. @see setCurrentThreadAffinityMask
  13312. */
  13313. void setAffinityMask (uint32 affinityMask);
  13314. /** Changes the affinity mask for the caller thread.
  13315. This will change the affinity mask for the thread that calls this static method.
  13316. @see setAffinityMask
  13317. */
  13318. static void setCurrentThreadAffinityMask (uint32 affinityMask);
  13319. // this can be called from any thread that needs to pause..
  13320. static void JUCE_CALLTYPE sleep (int milliseconds);
  13321. /** Yields the calling thread's current time-slot. */
  13322. static void JUCE_CALLTYPE yield();
  13323. /** Makes the thread wait for a notification.
  13324. This puts the thread to sleep until either the timeout period expires, or
  13325. another thread calls the notify() method to wake it up.
  13326. A negative time-out value means that the method will wait indefinitely.
  13327. @returns true if the event has been signalled, false if the timeout expires.
  13328. */
  13329. bool wait (int timeOutMilliseconds) const;
  13330. /** Wakes up the thread.
  13331. If the thread has called the wait() method, this will wake it up.
  13332. @see wait
  13333. */
  13334. void notify() const;
  13335. /** A value type used for thread IDs.
  13336. @see getCurrentThreadId(), getThreadId()
  13337. */
  13338. typedef void* ThreadID;
  13339. /** Returns an id that identifies the caller thread.
  13340. To find the ID of a particular thread object, use getThreadId().
  13341. @returns a unique identifier that identifies the calling thread.
  13342. @see getThreadId
  13343. */
  13344. static ThreadID getCurrentThreadId();
  13345. /** Finds the thread object that is currently running.
  13346. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  13347. object associated with them, so this will return 0.
  13348. */
  13349. static Thread* getCurrentThread();
  13350. /** Returns the ID of this thread.
  13351. That means the ID of this thread object - not of the thread that's calling the method.
  13352. This can change when the thread is started and stopped, and will be invalid if the
  13353. thread's not actually running.
  13354. @see getCurrentThreadId
  13355. */
  13356. ThreadID getThreadId() const throw() { return threadId_; }
  13357. /** Returns the name of the thread.
  13358. This is the name that gets set in the constructor.
  13359. */
  13360. const String getThreadName() const { return threadName_; }
  13361. /** Returns the number of currently-running threads.
  13362. @returns the number of Thread objects known to be currently running.
  13363. @see stopAllThreads
  13364. */
  13365. static int getNumRunningThreads();
  13366. /** Tries to stop all currently-running threads.
  13367. This will attempt to stop all the threads known to be running at the moment.
  13368. */
  13369. static void stopAllThreads (int timeoutInMillisecs);
  13370. juce_UseDebuggingNewOperator
  13371. private:
  13372. const String threadName_;
  13373. void* volatile threadHandle_;
  13374. CriticalSection startStopLock;
  13375. WaitableEvent startSuspensionEvent_, defaultEvent_;
  13376. int threadPriority_;
  13377. ThreadID threadId_;
  13378. uint32 affinityMask_;
  13379. bool volatile threadShouldExit_;
  13380. friend void JUCE_API juce_threadEntryPoint (void*);
  13381. static void threadEntryPoint (Thread* thread);
  13382. static Array<Thread*> runningThreads;
  13383. static CriticalSection runningThreadsLock;
  13384. Thread (const Thread&);
  13385. Thread& operator= (const Thread&);
  13386. };
  13387. #endif // __JUCE_THREAD_JUCEHEADER__
  13388. /*** End of inlined file: juce_Thread.h ***/
  13389. /**
  13390. A critical section that allows multiple simultaneous readers.
  13391. Features of this type of lock are:
  13392. - Multiple readers can hold the lock at the same time, but only one writer
  13393. can hold it at once.
  13394. - Writers trying to gain the lock will be blocked until all readers and writers
  13395. have released it
  13396. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  13397. blocked until the writer has obtained and released it
  13398. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  13399. there are no other readers
  13400. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  13401. - Recursive locking is supported.
  13402. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  13403. */
  13404. class JUCE_API ReadWriteLock
  13405. {
  13406. public:
  13407. /**
  13408. Creates a ReadWriteLock object.
  13409. */
  13410. ReadWriteLock() throw();
  13411. /** Destructor.
  13412. If the object is deleted whilst locked, any subsequent behaviour
  13413. is unpredictable.
  13414. */
  13415. ~ReadWriteLock() throw();
  13416. /** Locks this object for reading.
  13417. Multiple threads can simulaneously lock the object for reading, but if another
  13418. thread has it locked for writing, then this will block until it releases the
  13419. lock.
  13420. @see exitRead, ScopedReadLock
  13421. */
  13422. void enterRead() const throw();
  13423. /** Releases the read-lock.
  13424. If the caller thread hasn't got the lock, this can have unpredictable results.
  13425. If the enterRead() method has been called multiple times by the thread, each
  13426. call must be matched by a call to exitRead() before other threads will be allowed
  13427. to take over the lock.
  13428. @see enterRead, ScopedReadLock
  13429. */
  13430. void exitRead() const throw();
  13431. /** Locks this object for writing.
  13432. This will block until any other threads that have it locked for reading or
  13433. writing have released their lock.
  13434. @see exitWrite, ScopedWriteLock
  13435. */
  13436. void enterWrite() const throw();
  13437. /** Tries to lock this object for writing.
  13438. This is like enterWrite(), but doesn't block - it returns true if it manages
  13439. to obtain the lock.
  13440. @see enterWrite
  13441. */
  13442. bool tryEnterWrite() const throw();
  13443. /** Releases the write-lock.
  13444. If the caller thread hasn't got the lock, this can have unpredictable results.
  13445. If the enterWrite() method has been called multiple times by the thread, each
  13446. call must be matched by a call to exit() before other threads will be allowed
  13447. to take over the lock.
  13448. @see enterWrite, ScopedWriteLock
  13449. */
  13450. void exitWrite() const throw();
  13451. juce_UseDebuggingNewOperator
  13452. private:
  13453. CriticalSection accessLock;
  13454. WaitableEvent waitEvent;
  13455. mutable int numWaitingWriters, numWriters;
  13456. mutable Thread::ThreadID writerThreadId;
  13457. mutable Array <Thread::ThreadID> readerThreads;
  13458. ReadWriteLock (const ReadWriteLock&);
  13459. ReadWriteLock& operator= (const ReadWriteLock&);
  13460. };
  13461. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  13462. /*** End of inlined file: juce_ReadWriteLock.h ***/
  13463. #endif
  13464. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  13465. #endif
  13466. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13467. /*** Start of inlined file: juce_ScopedReadLock.h ***/
  13468. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13469. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13470. /**
  13471. Automatically locks and unlocks a ReadWriteLock object.
  13472. Use one of these as a local variable to control access to a ReadWriteLock.
  13473. e.g. @code
  13474. ReadWriteLock myLock;
  13475. for (;;)
  13476. {
  13477. const ScopedReadLock myScopedLock (myLock);
  13478. // myLock is now locked
  13479. ...do some stuff...
  13480. // myLock gets unlocked here.
  13481. }
  13482. @endcode
  13483. @see ReadWriteLock, ScopedWriteLock
  13484. */
  13485. class JUCE_API ScopedReadLock
  13486. {
  13487. public:
  13488. /** Creates a ScopedReadLock.
  13489. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  13490. when the ScopedReadLock object is deleted, the ReadWriteLock will
  13491. be unlocked.
  13492. Make sure this object is created and deleted by the same thread,
  13493. otherwise there are no guarantees what will happen! Best just to use it
  13494. as a local stack object, rather than creating one with the new() operator.
  13495. */
  13496. inline explicit ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  13497. /** Destructor.
  13498. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  13499. Make sure this object is created and deleted by the same thread,
  13500. otherwise there are no guarantees what will happen!
  13501. */
  13502. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  13503. private:
  13504. const ReadWriteLock& lock_;
  13505. ScopedReadLock (const ScopedReadLock&);
  13506. ScopedReadLock& operator= (const ScopedReadLock&);
  13507. };
  13508. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13509. /*** End of inlined file: juce_ScopedReadLock.h ***/
  13510. #endif
  13511. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13512. /*** Start of inlined file: juce_ScopedTryLock.h ***/
  13513. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13514. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13515. /**
  13516. Automatically tries to lock and unlock a CriticalSection object.
  13517. Use one of these as a local variable to control access to a CriticalSection.
  13518. e.g. @code
  13519. CriticalSection myCriticalSection;
  13520. for (;;)
  13521. {
  13522. const ScopedTryLock myScopedTryLock (myCriticalSection);
  13523. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  13524. // should test this with the isLocked() method before doing your thread-unsafe
  13525. // action..
  13526. if (myScopedTryLock.isLocked())
  13527. {
  13528. ...do some stuff...
  13529. }
  13530. else
  13531. {
  13532. ..our attempt at locking failed because another thread had already locked it..
  13533. }
  13534. // myCriticalSection gets unlocked here (if it was locked)
  13535. }
  13536. @endcode
  13537. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  13538. */
  13539. class JUCE_API ScopedTryLock
  13540. {
  13541. public:
  13542. /** Creates a ScopedTryLock.
  13543. As soon as it is created, this will try to lock the CriticalSection, and
  13544. when the ScopedTryLock object is deleted, the CriticalSection will
  13545. be unlocked if the lock was successful.
  13546. Make sure this object is created and deleted by the same thread,
  13547. otherwise there are no guarantees what will happen! Best just to use it
  13548. as a local stack object, rather than creating one with the new() operator.
  13549. */
  13550. inline explicit ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  13551. /** Destructor.
  13552. The CriticalSection will be unlocked (if locked) when the destructor is called.
  13553. Make sure this object is created and deleted by the same thread,
  13554. otherwise there are no guarantees what will happen!
  13555. */
  13556. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  13557. /** Returns true if the CriticalSection was successfully locked. */
  13558. bool isLocked() const throw() { return lockWasSuccessful; }
  13559. private:
  13560. const CriticalSection& lock_;
  13561. const bool lockWasSuccessful;
  13562. ScopedTryLock (const ScopedTryLock&);
  13563. ScopedTryLock& operator= (const ScopedTryLock&);
  13564. };
  13565. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13566. /*** End of inlined file: juce_ScopedTryLock.h ***/
  13567. #endif
  13568. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13569. /*** Start of inlined file: juce_ScopedWriteLock.h ***/
  13570. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13571. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13572. /**
  13573. Automatically locks and unlocks a ReadWriteLock object.
  13574. Use one of these as a local variable to control access to a ReadWriteLock.
  13575. e.g. @code
  13576. ReadWriteLock myLock;
  13577. for (;;)
  13578. {
  13579. const ScopedWriteLock myScopedLock (myLock);
  13580. // myLock is now locked
  13581. ...do some stuff...
  13582. // myLock gets unlocked here.
  13583. }
  13584. @endcode
  13585. @see ReadWriteLock, ScopedReadLock
  13586. */
  13587. class JUCE_API ScopedWriteLock
  13588. {
  13589. public:
  13590. /** Creates a ScopedWriteLock.
  13591. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  13592. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  13593. be unlocked.
  13594. Make sure this object is created and deleted by the same thread,
  13595. otherwise there are no guarantees what will happen! Best just to use it
  13596. as a local stack object, rather than creating one with the new() operator.
  13597. */
  13598. inline explicit ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  13599. /** Destructor.
  13600. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  13601. Make sure this object is created and deleted by the same thread,
  13602. otherwise there are no guarantees what will happen!
  13603. */
  13604. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  13605. private:
  13606. const ReadWriteLock& lock_;
  13607. ScopedWriteLock (const ScopedWriteLock&);
  13608. ScopedWriteLock& operator= (const ScopedWriteLock&);
  13609. };
  13610. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13611. /*** End of inlined file: juce_ScopedWriteLock.h ***/
  13612. #endif
  13613. #ifndef __JUCE_THREAD_JUCEHEADER__
  13614. #endif
  13615. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  13616. /*** Start of inlined file: juce_ThreadPool.h ***/
  13617. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  13618. #define __JUCE_THREADPOOL_JUCEHEADER__
  13619. class ThreadPool;
  13620. class ThreadPoolThread;
  13621. /**
  13622. A task that is executed by a ThreadPool object.
  13623. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  13624. its threads.
  13625. The runJob() method needs to be implemented to do the task, and if the code that
  13626. does the work takes a significant time to run, it must keep checking the shouldExit()
  13627. method to see if something is trying to interrupt the job. If shouldExit() returns
  13628. true, the runJob() method must return immediately.
  13629. @see ThreadPool, Thread
  13630. */
  13631. class JUCE_API ThreadPoolJob
  13632. {
  13633. public:
  13634. /** Creates a thread pool job object.
  13635. After creating your job, add it to a thread pool with ThreadPool::addJob().
  13636. */
  13637. explicit ThreadPoolJob (const String& name);
  13638. /** Destructor. */
  13639. virtual ~ThreadPoolJob();
  13640. /** Returns the name of this job.
  13641. @see setJobName
  13642. */
  13643. const String getJobName() const;
  13644. /** Changes the job's name.
  13645. @see getJobName
  13646. */
  13647. void setJobName (const String& newName);
  13648. /** These are the values that can be returned by the runJob() method.
  13649. */
  13650. enum JobStatus
  13651. {
  13652. jobHasFinished = 0, /**< indicates that the job has finished and can be
  13653. removed from the pool. */
  13654. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  13655. should be automatically deleted by the pool. */
  13656. jobNeedsRunningAgain /**< indicates that the job would like to be called
  13657. again when a thread is free. */
  13658. };
  13659. /** Peforms the actual work that this job needs to do.
  13660. Your subclass must implement this method, in which is does its work.
  13661. If the code in this method takes a significant time to run, it must repeatedly check
  13662. the shouldExit() method to see if something is trying to interrupt the job.
  13663. If shouldExit() ever returns true, the runJob() method must return immediately.
  13664. If this method returns jobHasFinished, then the job will be removed from the pool
  13665. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  13666. pool and will get a chance to run again as soon as a thread is free.
  13667. @see shouldExit()
  13668. */
  13669. virtual JobStatus runJob() = 0;
  13670. /** Returns true if this job is currently running its runJob() method. */
  13671. bool isRunning() const { return isActive; }
  13672. /** Returns true if something is trying to interrupt this job and make it stop.
  13673. Your runJob() method must call this whenever it gets a chance, and if it ever
  13674. returns true, the runJob() method must return immediately.
  13675. @see signalJobShouldExit()
  13676. */
  13677. bool shouldExit() const { return shouldStop; }
  13678. /** Calling this will cause the shouldExit() method to return true, and the job
  13679. should (if it's been implemented correctly) stop as soon as possible.
  13680. @see shouldExit()
  13681. */
  13682. void signalJobShouldExit();
  13683. juce_UseDebuggingNewOperator
  13684. private:
  13685. friend class ThreadPool;
  13686. friend class ThreadPoolThread;
  13687. String jobName;
  13688. ThreadPool* pool;
  13689. bool shouldStop, isActive, shouldBeDeleted;
  13690. ThreadPoolJob (const ThreadPoolJob&);
  13691. ThreadPoolJob& operator= (const ThreadPoolJob&);
  13692. };
  13693. /**
  13694. A set of threads that will run a list of jobs.
  13695. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  13696. will be called by the next pooled thread that becomes free.
  13697. @see ThreadPoolJob, Thread
  13698. */
  13699. class JUCE_API ThreadPool
  13700. {
  13701. public:
  13702. /** Creates a thread pool.
  13703. Once you've created a pool, you can give it some things to do with the addJob()
  13704. method.
  13705. @param numberOfThreads the maximum number of actual threads to run.
  13706. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  13707. until there are some jobs to run. If false, then
  13708. all the threads will be fired-up immediately so that
  13709. they're ready for action
  13710. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  13711. inactive for this length of time, they will automatically
  13712. be stopped until more jobs come along and they're needed
  13713. */
  13714. ThreadPool (int numberOfThreads,
  13715. bool startThreadsOnlyWhenNeeded = true,
  13716. int stopThreadsWhenNotUsedTimeoutMs = 5000);
  13717. /** Destructor.
  13718. This will attempt to remove all the jobs before deleting, but if you want to
  13719. specify a timeout, you should call removeAllJobs() explicitly before deleting
  13720. the pool.
  13721. */
  13722. ~ThreadPool();
  13723. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  13724. for some kind of operation.
  13725. @see ThreadPool::removeAllJobs
  13726. */
  13727. class JUCE_API JobSelector
  13728. {
  13729. public:
  13730. virtual ~JobSelector() {}
  13731. /** Should return true if the specified thread matches your criteria for whatever
  13732. operation that this object is being used for.
  13733. Any implementation of this method must be extremely fast and thread-safe!
  13734. */
  13735. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  13736. };
  13737. /** Adds a job to the queue.
  13738. Once a job has been added, then the next time a thread is free, it will run
  13739. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  13740. runJob() method, the pool will either remove the job from the pool or add it to
  13741. the back of the queue to be run again.
  13742. */
  13743. void addJob (ThreadPoolJob* job);
  13744. /** Tries to remove a job from the pool.
  13745. If the job isn't yet running, this will simply remove it. If it is running, it
  13746. will wait for it to finish.
  13747. If the timeout period expires before the job finishes running, then the job will be
  13748. left in the pool and this will return false. It returns true if the job is sucessfully
  13749. stopped and removed.
  13750. @param job the job to remove
  13751. @param interruptIfRunning if true, then if the job is currently busy, its
  13752. ThreadPoolJob::signalJobShouldExit() method will be called to try
  13753. to interrupt it. If false, then if the job will be allowed to run
  13754. until it stops normally (or the timeout expires)
  13755. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  13756. before giving up and returning false
  13757. */
  13758. bool removeJob (ThreadPoolJob* job,
  13759. bool interruptIfRunning,
  13760. int timeOutMilliseconds);
  13761. /** Tries to remove all jobs from the pool.
  13762. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  13763. methods called to try to interrupt them
  13764. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  13765. before giving up and returning false
  13766. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  13767. they will simply be removed from the pool. Jobs that are already running when
  13768. this method is called can choose whether they should be deleted by
  13769. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  13770. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  13771. jobs should be removed. If it is zero, all jobs are removed
  13772. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  13773. expires while waiting for one or more jobs to stop
  13774. */
  13775. bool removeAllJobs (bool interruptRunningJobs,
  13776. int timeOutMilliseconds,
  13777. bool deleteInactiveJobs = false,
  13778. JobSelector* selectedJobsToRemove = 0);
  13779. /** Returns the number of jobs currently running or queued.
  13780. */
  13781. int getNumJobs() const;
  13782. /** Returns one of the jobs in the queue.
  13783. Note that this can be a very volatile list as jobs might be continuously getting shifted
  13784. around in the list, and this method may return 0 if the index is currently out-of-range.
  13785. */
  13786. ThreadPoolJob* getJob (int index) const;
  13787. /** Returns true if the given job is currently queued or running.
  13788. @see isJobRunning()
  13789. */
  13790. bool contains (const ThreadPoolJob* job) const;
  13791. /** Returns true if the given job is currently being run by a thread.
  13792. */
  13793. bool isJobRunning (const ThreadPoolJob* job) const;
  13794. /** Waits until a job has finished running and has been removed from the pool.
  13795. This will wait until the job is no longer in the pool - i.e. until its
  13796. runJob() method returns ThreadPoolJob::jobHasFinished.
  13797. If the timeout period expires before the job finishes, this will return false;
  13798. it returns true if the job has finished successfully.
  13799. */
  13800. bool waitForJobToFinish (const ThreadPoolJob* job,
  13801. int timeOutMilliseconds) const;
  13802. /** Returns a list of the names of all the jobs currently running or queued.
  13803. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  13804. */
  13805. const StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  13806. /** Changes the priority of all the threads.
  13807. This will call Thread::setPriority() for each thread in the pool.
  13808. May return false if for some reason the priority can't be changed.
  13809. */
  13810. bool setThreadPriorities (int newPriority);
  13811. juce_UseDebuggingNewOperator
  13812. private:
  13813. const int threadStopTimeout;
  13814. int priority;
  13815. class ThreadPoolThread;
  13816. OwnedArray <ThreadPoolThread> threads;
  13817. Array <ThreadPoolJob*> jobs;
  13818. CriticalSection lock;
  13819. uint32 lastJobEndTime;
  13820. WaitableEvent jobFinishedSignal;
  13821. friend class ThreadPoolThread;
  13822. bool runNextJob();
  13823. ThreadPool (const ThreadPool&);
  13824. ThreadPool& operator= (const ThreadPool&);
  13825. };
  13826. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  13827. /*** End of inlined file: juce_ThreadPool.h ***/
  13828. #endif
  13829. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13830. /*** Start of inlined file: juce_TimeSliceThread.h ***/
  13831. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13832. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13833. /**
  13834. Used by the TimeSliceThread class.
  13835. To register your class with a TimeSliceThread, derive from this class and
  13836. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  13837. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  13838. deleting your client!
  13839. @see TimeSliceThread
  13840. */
  13841. class JUCE_API TimeSliceClient
  13842. {
  13843. public:
  13844. /** Destructor. */
  13845. virtual ~TimeSliceClient() {}
  13846. /** Called back by a TimeSliceThread.
  13847. When you register this class with it, a TimeSliceThread will repeatedly call
  13848. this method.
  13849. The implementation of this method should use its time-slice to do something that's
  13850. quick - never block for longer than absolutely necessary.
  13851. @returns Your method should return true if it needs more time, or false if it's
  13852. not too busy and doesn't need calling back urgently. If all the thread's
  13853. clients indicate that they're not busy, then it'll save CPU by sleeping for
  13854. up to half a second in between callbacks. You can force the TimeSliceThread
  13855. to wake up and poll again immediately by calling its notify() method.
  13856. */
  13857. virtual bool useTimeSlice() = 0;
  13858. };
  13859. /**
  13860. A thread that keeps a list of clients, and calls each one in turn, giving them
  13861. all a chance to run some sort of short task.
  13862. @see TimeSliceClient, Thread
  13863. */
  13864. class JUCE_API TimeSliceThread : public Thread
  13865. {
  13866. public:
  13867. /**
  13868. Creates a TimeSliceThread.
  13869. When first created, the thread is not running. Use the startThread()
  13870. method to start it.
  13871. */
  13872. explicit TimeSliceThread (const String& threadName);
  13873. /** Destructor.
  13874. Deleting a Thread object that is running will only give the thread a
  13875. brief opportunity to stop itself cleanly, so it's recommended that you
  13876. should always call stopThread() with a decent timeout before deleting,
  13877. to avoid the thread being forcibly killed (which is a Bad Thing).
  13878. */
  13879. ~TimeSliceThread();
  13880. /** Adds a client to the list.
  13881. The client's callbacks will start immediately (possibly before the method
  13882. has returned).
  13883. */
  13884. void addTimeSliceClient (TimeSliceClient* client);
  13885. /** Removes a client from the list.
  13886. This method will make sure that all callbacks to the client have completely
  13887. finished before the method returns.
  13888. */
  13889. void removeTimeSliceClient (TimeSliceClient* client);
  13890. /** Returns the number of registered clients. */
  13891. int getNumClients() const;
  13892. /** Returns one of the registered clients. */
  13893. TimeSliceClient* getClient (int index) const;
  13894. /** @internal */
  13895. void run();
  13896. juce_UseDebuggingNewOperator
  13897. private:
  13898. CriticalSection callbackLock, listLock;
  13899. Array <TimeSliceClient*> clients;
  13900. int index;
  13901. TimeSliceClient* clientBeingCalled;
  13902. bool clientsChanged;
  13903. TimeSliceThread (const TimeSliceThread&);
  13904. TimeSliceThread& operator= (const TimeSliceThread&);
  13905. };
  13906. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13907. /*** End of inlined file: juce_TimeSliceThread.h ***/
  13908. #endif
  13909. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  13910. #endif
  13911. #endif
  13912. /*** End of inlined file: juce_core_includes.h ***/
  13913. // if you're compiling a command-line app, you might want to just include the core headers,
  13914. // so you can set this macro before including juce.h
  13915. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  13916. /*** Start of inlined file: juce_app_includes.h ***/
  13917. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  13918. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  13919. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  13920. /*** Start of inlined file: juce_Application.h ***/
  13921. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  13922. #define __JUCE_APPLICATION_JUCEHEADER__
  13923. /*** Start of inlined file: juce_ApplicationCommandTarget.h ***/
  13924. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  13925. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  13926. /*** Start of inlined file: juce_Component.h ***/
  13927. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  13928. #define __JUCE_COMPONENT_JUCEHEADER__
  13929. /*** Start of inlined file: juce_MouseCursor.h ***/
  13930. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  13931. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  13932. class Image;
  13933. class ComponentPeer;
  13934. class Component;
  13935. /**
  13936. Represents a mouse cursor image.
  13937. This object can either be used to represent one of the standard mouse
  13938. cursor shapes, or a custom one generated from an image.
  13939. */
  13940. class JUCE_API MouseCursor
  13941. {
  13942. public:
  13943. /** The set of available standard mouse cursors. */
  13944. enum StandardCursorType
  13945. {
  13946. NoCursor = 0, /**< An invisible cursor. */
  13947. NormalCursor, /**< The stardard arrow cursor. */
  13948. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  13949. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  13950. CrosshairCursor, /**< A pair of crosshairs. */
  13951. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  13952. that you're dragging a copy of something. */
  13953. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  13954. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  13955. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  13956. UpDownResizeCursor, /**< an arrow pointing up and down. */
  13957. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  13958. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  13959. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  13960. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  13961. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  13962. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  13963. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  13964. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  13965. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  13966. };
  13967. /** Creates the standard arrow cursor. */
  13968. MouseCursor();
  13969. /** Creates one of the standard mouse cursor */
  13970. MouseCursor (StandardCursorType type);
  13971. /** Creates a custom cursor from an image.
  13972. @param image the image to use for the cursor - if this is bigger than the
  13973. system can manage, it might get scaled down first, and might
  13974. also have to be turned to black-and-white if it can't do colour
  13975. cursors.
  13976. @param hotSpotX the x position of the cursor's hotspot within the image
  13977. @param hotSpotY the y position of the cursor's hotspot within the image
  13978. */
  13979. MouseCursor (const Image& image, int hotSpotX, int hotSpotY);
  13980. /** Creates a copy of another cursor object. */
  13981. MouseCursor (const MouseCursor& other);
  13982. /** Copies this cursor from another object. */
  13983. MouseCursor& operator= (const MouseCursor& other);
  13984. /** Destructor. */
  13985. ~MouseCursor();
  13986. /** Checks whether two mouse cursors are the same.
  13987. For custom cursors, two cursors created from the same image won't be
  13988. recognised as the same, only MouseCursor objects that have been
  13989. copied from the same object.
  13990. */
  13991. bool operator== (const MouseCursor& other) const throw();
  13992. /** Checks whether two mouse cursors are the same.
  13993. For custom cursors, two cursors created from the same image won't be
  13994. recognised as the same, only MouseCursor objects that have been
  13995. copied from the same object.
  13996. */
  13997. bool operator!= (const MouseCursor& other) const throw();
  13998. /** Makes the system show its default 'busy' cursor.
  13999. This will turn the system cursor to an hourglass or spinning beachball
  14000. until the next time the mouse is moved, or hideWaitCursor() is called.
  14001. This is handy if the message loop is about to block for a couple of
  14002. seconds while busy and you want to give the user feedback about this.
  14003. @see MessageManager::setTimeBeforeShowingWaitCursor
  14004. */
  14005. static void showWaitCursor();
  14006. /** If showWaitCursor has been called, this will return the mouse to its
  14007. normal state.
  14008. This will look at what component is under the mouse, and update the
  14009. cursor to be the correct one for that component.
  14010. @see showWaitCursor
  14011. */
  14012. static void hideWaitCursor();
  14013. juce_UseDebuggingNewOperator
  14014. private:
  14015. class SharedCursorHandle;
  14016. friend class SharedCursorHandle;
  14017. SharedCursorHandle* cursorHandle;
  14018. friend class MouseInputSourceInternal;
  14019. void showInWindow (ComponentPeer* window) const;
  14020. void showInAllWindows() const;
  14021. void* getHandle() const throw();
  14022. static void* createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY);
  14023. static void* createStandardMouseCursor (MouseCursor::StandardCursorType type);
  14024. static void deleteMouseCursor (void* cursorHandle, bool isStandard);
  14025. };
  14026. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  14027. /*** End of inlined file: juce_MouseCursor.h ***/
  14028. /*** Start of inlined file: juce_MouseListener.h ***/
  14029. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  14030. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  14031. class MouseEvent;
  14032. /**
  14033. A MouseListener can be registered with a component to receive callbacks
  14034. about mouse events that happen to that component.
  14035. @see Component::addMouseListener, Component::removeMouseListener
  14036. */
  14037. class JUCE_API MouseListener
  14038. {
  14039. public:
  14040. /** Destructor. */
  14041. virtual ~MouseListener() {}
  14042. /** Called when the mouse moves inside a component.
  14043. If the mouse button isn't pressed and the mouse moves over a component,
  14044. this will be called to let the component react to this.
  14045. A component will always get a mouseEnter callback before a mouseMove.
  14046. @param e details about the position and status of the mouse event, including
  14047. the source component in which it occurred
  14048. @see mouseEnter, mouseExit, mouseDrag, contains
  14049. */
  14050. virtual void mouseMove (const MouseEvent& e);
  14051. /** Called when the mouse first enters a component.
  14052. If the mouse button isn't pressed and the mouse moves into a component,
  14053. this will be called to let the component react to this.
  14054. When the mouse button is pressed and held down while being moved in
  14055. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  14056. mouseDrag messages are sent to the component that the mouse was originally
  14057. clicked on, until the button is released.
  14058. @param e details about the position and status of the mouse event, including
  14059. the source component in which it occurred
  14060. @see mouseExit, mouseDrag, mouseMove, contains
  14061. */
  14062. virtual void mouseEnter (const MouseEvent& e);
  14063. /** Called when the mouse moves out of a component.
  14064. This will be called when the mouse moves off the edge of this
  14065. component.
  14066. If the mouse button was pressed, and it was then dragged off the
  14067. edge of the component and released, then this callback will happen
  14068. when the button is released, after the mouseUp callback.
  14069. @param e details about the position and status of the mouse event, including
  14070. the source component in which it occurred
  14071. @see mouseEnter, mouseDrag, mouseMove, contains
  14072. */
  14073. virtual void mouseExit (const MouseEvent& e);
  14074. /** Called when a mouse button is pressed.
  14075. The MouseEvent object passed in contains lots of methods for finding out
  14076. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  14077. were held down at the time.
  14078. Once a button is held down, the mouseDrag method will be called when the
  14079. mouse moves, until the button is released.
  14080. @param e details about the position and status of the mouse event, including
  14081. the source component in which it occurred
  14082. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  14083. */
  14084. virtual void mouseDown (const MouseEvent& e);
  14085. /** Called when the mouse is moved while a button is held down.
  14086. When a mouse button is pressed inside a component, that component
  14087. receives mouseDrag callbacks each time the mouse moves, even if the
  14088. mouse strays outside the component's bounds.
  14089. @param e details about the position and status of the mouse event, including
  14090. the source component in which it occurred
  14091. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  14092. */
  14093. virtual void mouseDrag (const MouseEvent& e);
  14094. /** Called when a mouse button is released.
  14095. A mouseUp callback is sent to the component in which a button was pressed
  14096. even if the mouse is actually over a different component when the
  14097. button is released.
  14098. The MouseEvent object passed in contains lots of methods for finding out
  14099. which buttons were down just before they were released.
  14100. @param e details about the position and status of the mouse event, including
  14101. the source component in which it occurred
  14102. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  14103. */
  14104. virtual void mouseUp (const MouseEvent& e);
  14105. /** Called when a mouse button has been double-clicked on a component.
  14106. The MouseEvent object passed in contains lots of methods for finding out
  14107. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  14108. were held down at the time.
  14109. @param e details about the position and status of the mouse event, including
  14110. the source component in which it occurred
  14111. @see mouseDown, mouseUp
  14112. */
  14113. virtual void mouseDoubleClick (const MouseEvent& e);
  14114. /** Called when the mouse-wheel is moved.
  14115. This callback is sent to the component that the mouse is over when the
  14116. wheel is moved.
  14117. If not overridden, the component will forward this message to its parent, so
  14118. that parent components can collect mouse-wheel messages that happen to
  14119. child components which aren't interested in them.
  14120. @param e details about the position and status of the mouse event, including
  14121. the source component in which it occurred
  14122. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  14123. value means the wheel has been pushed to the right, negative means it
  14124. was pushed to the left
  14125. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  14126. value means the wheel has been pushed upwards, negative means it
  14127. was pushed downwards
  14128. */
  14129. virtual void mouseWheelMove (const MouseEvent& e,
  14130. float wheelIncrementX,
  14131. float wheelIncrementY);
  14132. };
  14133. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  14134. /*** End of inlined file: juce_MouseListener.h ***/
  14135. /*** Start of inlined file: juce_MouseEvent.h ***/
  14136. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  14137. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  14138. class Component;
  14139. class MouseInputSource;
  14140. /*** Start of inlined file: juce_ModifierKeys.h ***/
  14141. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  14142. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  14143. /**
  14144. Represents the state of the mouse buttons and modifier keys.
  14145. This is used both by mouse events and by KeyPress objects to describe
  14146. the state of keys such as shift, control, alt, etc.
  14147. @see KeyPress, MouseEvent::mods
  14148. */
  14149. class JUCE_API ModifierKeys
  14150. {
  14151. public:
  14152. /** Creates a ModifierKeys object from a raw set of flags.
  14153. @param flags to represent the keys that are down
  14154. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  14155. rightButtonModifier, commandModifier, popupMenuClickModifier
  14156. */
  14157. ModifierKeys (int flags = 0) throw();
  14158. /** Creates a copy of another object. */
  14159. ModifierKeys (const ModifierKeys& other) throw();
  14160. /** Copies this object from another one. */
  14161. ModifierKeys& operator= (const ModifierKeys& other) throw();
  14162. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  14163. This is a platform-agnostic way of checking for the operating system's
  14164. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  14165. Windows/Linux, it's actually checking for the CTRL key.
  14166. */
  14167. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  14168. /** Checks whether the user is trying to launch a pop-up menu.
  14169. This checks for platform-specific modifiers that might indicate that the user
  14170. is following the operating system's normal method of showing a pop-up menu.
  14171. So on Windows/Linux, this method is really testing for a right-click.
  14172. On the Mac, it tests for either the CTRL key being down, or a right-click.
  14173. */
  14174. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  14175. /** Checks whether the flag is set for the left mouse-button. */
  14176. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  14177. /** Checks whether the flag is set for the right mouse-button.
  14178. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  14179. this is platform-independent (and makes your code more explanatory too).
  14180. */
  14181. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  14182. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  14183. /** Tests for any of the mouse-button flags. */
  14184. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  14185. /** Tests for any of the modifier key flags. */
  14186. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  14187. /** Checks whether the shift key's flag is set. */
  14188. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  14189. /** Checks whether the CTRL key's flag is set.
  14190. Remember that it's better to use the platform-agnostic routines to test for command-key and
  14191. popup-menu modifiers.
  14192. @see isCommandDown, isPopupMenu
  14193. */
  14194. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  14195. /** Checks whether the shift key's flag is set. */
  14196. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  14197. /** Flags that represent the different keys. */
  14198. enum Flags
  14199. {
  14200. /** Shift key flag. */
  14201. shiftModifier = 1,
  14202. /** CTRL key flag. */
  14203. ctrlModifier = 2,
  14204. /** ALT key flag. */
  14205. altModifier = 4,
  14206. /** Left mouse button flag. */
  14207. leftButtonModifier = 16,
  14208. /** Right mouse button flag. */
  14209. rightButtonModifier = 32,
  14210. /** Middle mouse button flag. */
  14211. middleButtonModifier = 64,
  14212. #if JUCE_MAC
  14213. /** Command key flag - on windows this is the same as the CTRL key flag. */
  14214. commandModifier = 8,
  14215. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  14216. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  14217. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  14218. #else
  14219. /** Command key flag - on windows this is the same as the CTRL key flag. */
  14220. commandModifier = ctrlModifier,
  14221. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  14222. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  14223. popupMenuClickModifier = rightButtonModifier,
  14224. #endif
  14225. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  14226. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  14227. /** Represents a combination of all the mouse buttons at once. */
  14228. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  14229. };
  14230. /** Returns a copy of only the mouse-button flags */
  14231. const ModifierKeys withOnlyMouseButtons() const throw() { return ModifierKeys (flags & allMouseButtonModifiers); }
  14232. /** Returns a copy of only the non-mouse flags */
  14233. const ModifierKeys withoutMouseButtons() const throw() { return ModifierKeys (flags & ~allMouseButtonModifiers); }
  14234. bool operator== (const ModifierKeys& other) const throw() { return flags == other.flags; }
  14235. bool operator!= (const ModifierKeys& other) const throw() { return flags != other.flags; }
  14236. /** Returns the raw flags for direct testing. */
  14237. inline int getRawFlags() const throw() { return flags; }
  14238. inline const ModifierKeys withoutFlags (int rawFlagsToClear) const throw() { return ModifierKeys (flags & ~rawFlagsToClear); }
  14239. inline const ModifierKeys withFlags (int rawFlagsToSet) const throw() { return ModifierKeys (flags | rawFlagsToSet); }
  14240. /** Tests a combination of flags and returns true if any of them are set. */
  14241. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  14242. /** Returns the total number of mouse buttons that are down. */
  14243. int getNumMouseButtonsDown() const throw();
  14244. /** Creates a ModifierKeys object to represent the last-known state of the
  14245. keyboard and mouse buttons.
  14246. @see getCurrentModifiersRealtime
  14247. */
  14248. static const ModifierKeys getCurrentModifiers() throw();
  14249. /** Creates a ModifierKeys object to represent the current state of the
  14250. keyboard and mouse buttons.
  14251. This isn't often needed and isn't recommended, but will actively check all the
  14252. mouse and key states rather than just returning their last-known state like
  14253. getCurrentModifiers() does.
  14254. This is only needed in special circumstances for up-to-date modifier information
  14255. at times when the app's event loop isn't running normally.
  14256. */
  14257. static const ModifierKeys getCurrentModifiersRealtime() throw();
  14258. private:
  14259. int flags;
  14260. static ModifierKeys currentModifiers;
  14261. friend class ComponentPeer;
  14262. friend class MouseInputSource;
  14263. friend class MouseInputSourceInternal;
  14264. static void updateCurrentModifiers() throw();
  14265. };
  14266. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  14267. /*** End of inlined file: juce_ModifierKeys.h ***/
  14268. /*** Start of inlined file: juce_Point.h ***/
  14269. #ifndef __JUCE_POINT_JUCEHEADER__
  14270. #define __JUCE_POINT_JUCEHEADER__
  14271. /*** Start of inlined file: juce_AffineTransform.h ***/
  14272. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  14273. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  14274. /**
  14275. Represents a 2D affine-transformation matrix.
  14276. An affine transformation is a transformation such as a rotation, scale, shear,
  14277. resize or translation.
  14278. These are used for various 2D transformation tasks, e.g. with Path objects.
  14279. @see Path, Point, Line
  14280. */
  14281. class JUCE_API AffineTransform
  14282. {
  14283. public:
  14284. /** Creates an identity transform. */
  14285. AffineTransform() throw();
  14286. /** Creates a copy of another transform. */
  14287. AffineTransform (const AffineTransform& other) throw();
  14288. /** Creates a transform from a set of raw matrix values.
  14289. The resulting matrix is:
  14290. (mat00 mat01 mat02)
  14291. (mat10 mat11 mat12)
  14292. ( 0 0 1 )
  14293. */
  14294. AffineTransform (float mat00, float mat01, float mat02,
  14295. float mat10, float mat11, float mat12) throw();
  14296. /** Copies from another AffineTransform object */
  14297. AffineTransform& operator= (const AffineTransform& other) throw();
  14298. /** Compares two transforms. */
  14299. bool operator== (const AffineTransform& other) const throw();
  14300. /** Compares two transforms. */
  14301. bool operator!= (const AffineTransform& other) const throw();
  14302. /** A ready-to-use identity transform, which you can use to append other
  14303. transformations to.
  14304. e.g. @code
  14305. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  14306. .scaled (2.0f);
  14307. @endcode
  14308. */
  14309. static const AffineTransform identity;
  14310. /** Transforms a 2D co-ordinate using this matrix. */
  14311. void transformPoint (float& x,
  14312. float& y) const throw();
  14313. /** Transforms a 2D co-ordinate using this matrix. */
  14314. void transformPoint (double& x,
  14315. double& y) const throw();
  14316. /** Returns a new transform which is the same as this one followed by a translation. */
  14317. const AffineTransform translated (float deltaX,
  14318. float deltaY) const throw();
  14319. /** Returns a new transform which is a translation. */
  14320. static const AffineTransform translation (float deltaX,
  14321. float deltaY) throw();
  14322. /** Returns a transform which is the same as this one followed by a rotation.
  14323. The rotation is specified by a number of radians to rotate clockwise, centred around
  14324. the origin (0, 0).
  14325. */
  14326. const AffineTransform rotated (float angleInRadians) const throw();
  14327. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  14328. The rotation is specified by a number of radians to rotate clockwise, centred around
  14329. the co-ordinates passed in.
  14330. */
  14331. const AffineTransform rotated (float angleInRadians,
  14332. float pivotX,
  14333. float pivotY) const throw();
  14334. /** Returns a new transform which is a rotation about (0, 0). */
  14335. static const AffineTransform rotation (float angleInRadians) throw();
  14336. /** Returns a new transform which is a rotation about a given point. */
  14337. static const AffineTransform rotation (float angleInRadians,
  14338. float pivotX,
  14339. float pivotY) throw();
  14340. /** Returns a transform which is the same as this one followed by a re-scaling.
  14341. The scaling is centred around the origin (0, 0).
  14342. */
  14343. const AffineTransform scaled (float factorX,
  14344. float factorY) const throw();
  14345. /** Returns a new transform which is a re-scale about the origin. */
  14346. static const AffineTransform scale (float factorX,
  14347. float factorY) throw();
  14348. /** Returns a transform which is the same as this one followed by a shear.
  14349. The shear is centred around the origin (0, 0).
  14350. */
  14351. const AffineTransform sheared (float shearX,
  14352. float shearY) const throw();
  14353. /** Returns a matrix which is the inverse operation of this one.
  14354. Some matrices don't have an inverse - in this case, the method will just return
  14355. an identity transform.
  14356. */
  14357. const AffineTransform inverted() const throw();
  14358. /** Returns the transform that will map three known points onto three coordinates
  14359. that are supplied.
  14360. This returns the transform that will transform (0, 0) into (x00, y00),
  14361. (1, 0) to (x10, y10), and (0, 1) to (x01, y01).
  14362. */
  14363. static const AffineTransform fromTargetPoints (float x00, float y00,
  14364. float x10, float y10,
  14365. float x01, float y01) throw();
  14366. /** Returns the transform that will map three specified points onto three target points.
  14367. */
  14368. static const AffineTransform fromTargetPoints (float sourceX1, float sourceY1, float targetX1, float targetY1,
  14369. float sourceX2, float sourceY2, float targetX2, float targetY2,
  14370. float sourceX3, float sourceY3, float targetX3, float targetY3) throw();
  14371. /** Returns the result of concatenating another transformation after this one. */
  14372. const AffineTransform followedBy (const AffineTransform& other) const throw();
  14373. /** Returns true if this transform has no effect on points. */
  14374. bool isIdentity() const throw();
  14375. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  14376. bool isSingularity() const throw();
  14377. /** Returns true if the transform only translates, and doesn't scale or rotate the
  14378. points. */
  14379. bool isOnlyTranslation() const throw();
  14380. /** If this transform is only a translation, this returns the X offset.
  14381. @see isOnlyTranslation
  14382. */
  14383. float getTranslationX() const throw() { return mat02; }
  14384. /** If this transform is only a translation, this returns the X offset.
  14385. @see isOnlyTranslation
  14386. */
  14387. float getTranslationY() const throw() { return mat12; }
  14388. /* The transform matrix is:
  14389. (mat00 mat01 mat02)
  14390. (mat10 mat11 mat12)
  14391. ( 0 0 1 )
  14392. */
  14393. float mat00, mat01, mat02;
  14394. float mat10, mat11, mat12;
  14395. juce_UseDebuggingNewOperator
  14396. private:
  14397. const AffineTransform followedBy (float mat00, float mat01, float mat02,
  14398. float mat10, float mat11, float mat12) const throw();
  14399. };
  14400. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  14401. /*** End of inlined file: juce_AffineTransform.h ***/
  14402. /**
  14403. A pair of (x, y) co-ordinates.
  14404. The ValueType template should be a primitive type such as int, float, double,
  14405. rather than a class.
  14406. @see Line, Path, AffineTransform
  14407. */
  14408. template <typename ValueType>
  14409. class Point
  14410. {
  14411. public:
  14412. /** Creates a point with co-ordinates (0, 0). */
  14413. Point() throw() : x (0), y (0) {}
  14414. /** Creates a copy of another point. */
  14415. Point (const Point& other) throw() : x (other.x), y (other.y) {}
  14416. /** Creates a point from an (x, y) position. */
  14417. Point (const ValueType initialX, const ValueType initialY) throw() : x (initialX), y (initialY) {}
  14418. /** Destructor. */
  14419. ~Point() throw() {}
  14420. /** Copies this point from another one. */
  14421. Point& operator= (const Point& other) throw() { x = other.x; y = other.y; return *this; }
  14422. inline bool operator== (const Point& other) const throw() { return x == other.x && y == other.y; }
  14423. inline bool operator!= (const Point& other) const throw() { return x != other.x || y != other.y; }
  14424. /** Returns true if the point is (0, 0). */
  14425. bool isOrigin() const throw() { return x == ValueType() && y == ValueType(); }
  14426. /** Returns the point's x co-ordinate. */
  14427. inline ValueType getX() const throw() { return x; }
  14428. /** Returns the point's y co-ordinate. */
  14429. inline ValueType getY() const throw() { return y; }
  14430. /** Sets the point's x co-ordinate. */
  14431. inline void setX (const ValueType newX) throw() { x = newX; }
  14432. /** Sets the point's y co-ordinate. */
  14433. inline void setY (const ValueType newY) throw() { y = newY; }
  14434. /** Returns a point which has the same Y position as this one, but a new X. */
  14435. const Point withX (const ValueType newX) const throw() { return Point (newX, y); }
  14436. /** Returns a point which has the same X position as this one, but a new Y. */
  14437. const Point withY (const ValueType newY) const throw() { return Point (x, newY); }
  14438. /** Changes the point's x and y co-ordinates. */
  14439. void setXY (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  14440. /** Adds a pair of co-ordinates to this value. */
  14441. void addXY (const ValueType xToAdd, const ValueType yToAdd) throw() { x += xToAdd; y += yToAdd; }
  14442. /** Returns a point with a given offset from this one. */
  14443. const Point translated (const ValueType xDelta, const ValueType yDelta) const throw() { return Point (x + xDelta, y + yDelta); }
  14444. /** Adds two points together. */
  14445. const Point operator+ (const Point& other) const throw() { return Point (x + other.x, y + other.y); }
  14446. /** Adds another point's co-ordinates to this one. */
  14447. Point& operator+= (const Point& other) throw() { x += other.x; y += other.y; return *this; }
  14448. /** Subtracts one points from another. */
  14449. const Point operator- (const Point& other) const throw() { return Point (x - other.x, y - other.y); }
  14450. /** Subtracts another point's co-ordinates to this one. */
  14451. Point& operator-= (const Point& other) throw() { x -= other.x; y -= other.y; return *this; }
  14452. /** Returns a point whose coordinates are multiplied by a given value. */
  14453. const Point operator* (const ValueType multiplier) const throw() { return Point (x * multiplier, y * multiplier); }
  14454. /** Multiplies the point's co-ordinates by a value. */
  14455. Point& operator*= (const ValueType multiplier) throw() { x *= multiplier; y *= multiplier; return *this; }
  14456. /** Returns a point whose coordinates are divided by a given value. */
  14457. const Point operator/ (const ValueType divisor) const throw() { return Point (x / divisor, y / divisor); }
  14458. /** Divides the point's co-ordinates by a value. */
  14459. Point& operator/= (const ValueType divisor) throw() { x /= divisor; y /= divisor; return *this; }
  14460. /** Returns the inverse of this point. */
  14461. const Point operator-() const throw() { return Point (-x, -y); }
  14462. /** Returns the straight-line distance between this point and another one. */
  14463. ValueType getDistanceFromOrigin() const throw() { return (ValueType) juce_hypot (x, y); }
  14464. /** Returns the straight-line distance between this point and another one. */
  14465. ValueType getDistanceFrom (const Point& other) const throw() { return (ValueType) juce_hypot (x - other.x, y - other.y); }
  14466. /** Returns the angle from this point to another one.
  14467. The return value is the number of radians clockwise from the 3 o'clock direction,
  14468. where this point is the centre and the other point is on the circumference.
  14469. */
  14470. ValueType getAngleToPoint (const Point& other) const throw() { return (ValueType) std::atan2 (other.x - x, other.y - y); }
  14471. /** Taking this point to be the centre of a circle, this returns a point on its circumference.
  14472. @param radius the radius of the circle.
  14473. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  14474. */
  14475. const Point getPointOnCircumference (const float radius, const float angle) const throw() { return Point<float> (x + radius * std::sin (angle),
  14476. y - radius * std::cos (angle)); }
  14477. /** Taking this point to be the centre of an ellipse, this returns a point on its circumference.
  14478. @param radiusX the horizontal radius of the circle.
  14479. @param radiusY the vertical radius of the circle.
  14480. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  14481. */
  14482. const Point getPointOnCircumference (const float radiusX, const float radiusY, const float angle) const throw() { return Point<float> (x + radiusX * std::sin (angle),
  14483. y - radiusY * std::cos (angle)); }
  14484. /** Uses a transform to change the point's co-ordinates.
  14485. This will only compile if ValueType = float!
  14486. @see AffineTransform::transformPoint
  14487. */
  14488. void applyTransform (const AffineTransform& transform) throw() { transform.transformPoint (x, y); }
  14489. /** Returns the position of this point, if it is transformed by a given AffineTransform. */
  14490. const Point transformedBy (const AffineTransform& transform) const throw() { ValueType x2 (x), y2 (y); transform.transformPoint (x2, y2); return Point (x2, y2); }
  14491. /** Casts this point to a Point<float> object. */
  14492. const Point<float> toFloat() const throw() { return Point<float> (static_cast <float> (x), static_cast<float> (y)); }
  14493. /** Returns the point as a string in the form "x, y". */
  14494. const String toString() const { return String (x) + ", " + String (y); }
  14495. juce_UseDebuggingNewOperator
  14496. private:
  14497. ValueType x, y;
  14498. };
  14499. #endif // __JUCE_POINT_JUCEHEADER__
  14500. /*** End of inlined file: juce_Point.h ***/
  14501. /**
  14502. Contains position and status information about a mouse event.
  14503. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  14504. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  14505. */
  14506. class JUCE_API MouseEvent
  14507. {
  14508. public:
  14509. /** Creates a MouseEvent.
  14510. Normally an application will never need to use this.
  14511. @param source the source that's invoking the event
  14512. @param position the position of the mouse, relative to the component that is passed-in
  14513. @param modifiers the key modifiers at the time of the event
  14514. @param eventComponent the component that the mouse event applies to
  14515. @param originator the component that originally received the event
  14516. @param eventTime the time the event happened
  14517. @param mouseDownPos the position of the corresponding mouse-down event (relative to the component that is passed-in).
  14518. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  14519. the same as the current mouse-x position.
  14520. @param mouseDownTime the time at which the corresponding mouse-down event happened
  14521. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  14522. the same as the current mouse-event time.
  14523. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  14524. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  14525. */
  14526. MouseEvent (MouseInputSource& source,
  14527. const Point<int>& position,
  14528. const ModifierKeys& modifiers,
  14529. Component* eventComponent,
  14530. Component* originator,
  14531. const Time& eventTime,
  14532. const Point<int> mouseDownPos,
  14533. const Time& mouseDownTime,
  14534. int numberOfClicks,
  14535. bool mouseWasDragged) throw();
  14536. /** Destructor. */
  14537. ~MouseEvent() throw();
  14538. /** The x-position of the mouse when the event occurred.
  14539. This value is relative to the top-left of the component to which the
  14540. event applies (as indicated by the MouseEvent::eventComponent field).
  14541. */
  14542. const int x;
  14543. /** The y-position of the mouse when the event occurred.
  14544. This value is relative to the top-left of the component to which the
  14545. event applies (as indicated by the MouseEvent::eventComponent field).
  14546. */
  14547. const int y;
  14548. /** The key modifiers associated with the event.
  14549. This will let you find out which mouse buttons were down, as well as which
  14550. modifier keys were held down.
  14551. When used for mouse-up events, this will indicate the state of the mouse buttons
  14552. just before they were released, so that you can tell which button they let go of.
  14553. */
  14554. const ModifierKeys mods;
  14555. /** The component that this event applies to.
  14556. This is usually the component that the mouse was over at the time, but for mouse-drag
  14557. events the mouse could actually be over a different component and the events are
  14558. still sent to the component that the button was originally pressed on.
  14559. The x and y member variables are relative to this component's position.
  14560. If you use getEventRelativeTo() to retarget this object to be relative to a different
  14561. component, this pointer will be updated, but originalComponent remains unchanged.
  14562. @see originalComponent
  14563. */
  14564. Component* const eventComponent;
  14565. /** The component that the event first occurred on.
  14566. If you use getEventRelativeTo() to retarget this object to be relative to a different
  14567. component, this value remains unchanged to indicate the first component that received it.
  14568. @see eventComponent
  14569. */
  14570. Component* const originalComponent;
  14571. /** The time that this mouse-event occurred.
  14572. */
  14573. const Time eventTime;
  14574. /** The source device that generated this event.
  14575. */
  14576. MouseInputSource& source;
  14577. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  14578. The co-ordinate is relative to the component specified in MouseEvent::component.
  14579. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  14580. */
  14581. int getMouseDownX() const throw();
  14582. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  14583. The co-ordinate is relative to the component specified in MouseEvent::component.
  14584. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  14585. */
  14586. int getMouseDownY() const throw();
  14587. /** Returns the co-ordinates of the last place that a mouse was pressed.
  14588. The co-ordinates are relative to the component specified in MouseEvent::component.
  14589. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  14590. */
  14591. const Point<int> getMouseDownPosition() const throw();
  14592. /** Returns the straight-line distance between where the mouse is now and where it
  14593. was the last time the button was pressed.
  14594. This is quite handy for things like deciding whether the user has moved far enough
  14595. for it to be considered a drag operation.
  14596. @see getDistanceFromDragStartX
  14597. */
  14598. int getDistanceFromDragStart() const throw();
  14599. /** Returns the difference between the mouse's current x postion and where it was
  14600. when the button was last pressed.
  14601. @see getDistanceFromDragStart
  14602. */
  14603. int getDistanceFromDragStartX() const throw();
  14604. /** Returns the difference between the mouse's current y postion and where it was
  14605. when the button was last pressed.
  14606. @see getDistanceFromDragStart
  14607. */
  14608. int getDistanceFromDragStartY() const throw();
  14609. /** Returns the difference between the mouse's current postion and where it was
  14610. when the button was last pressed.
  14611. @see getDistanceFromDragStart
  14612. */
  14613. const Point<int> getOffsetFromDragStart() const throw();
  14614. /** Returns true if the mouse has just been clicked.
  14615. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  14616. the user has dragged the mouse more than a few pixels from the place where the
  14617. mouse-down occurred.
  14618. Once they have dragged it far enough for this method to return false, it will continue
  14619. to return false until the mouse-up, even if they move the mouse back to the same
  14620. position where they originally pressed it. This means that it's very handy for
  14621. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  14622. callback to ignore any small movements they might make while clicking.
  14623. @returns true if the mouse wasn't dragged by more than a few pixels between
  14624. the last time the button was pressed and released.
  14625. */
  14626. bool mouseWasClicked() const throw();
  14627. /** For a click event, the number of times the mouse was clicked in succession.
  14628. So for example a double-click event will return 2, a triple-click 3, etc.
  14629. */
  14630. int getNumberOfClicks() const throw() { return numberOfClicks; }
  14631. /** Returns the time that the mouse button has been held down for.
  14632. If called from a mouseDrag or mouseUp callback, this will return the
  14633. number of milliseconds since the corresponding mouseDown event occurred.
  14634. If called in other contexts, e.g. a mouseMove, then the returned value
  14635. may be 0 or an undefined value.
  14636. */
  14637. int getLengthOfMousePress() const throw();
  14638. /** The position of the mouse when the event occurred.
  14639. This position is relative to the top-left of the component to which the
  14640. event applies (as indicated by the MouseEvent::eventComponent field).
  14641. */
  14642. const Point<int> getPosition() const throw();
  14643. /** Returns the mouse x position of this event, in global screen co-ordinates.
  14644. The co-ordinates are relative to the top-left of the main monitor.
  14645. @see getScreenPosition
  14646. */
  14647. int getScreenX() const;
  14648. /** Returns the mouse y position of this event, in global screen co-ordinates.
  14649. The co-ordinates are relative to the top-left of the main monitor.
  14650. @see getScreenPosition
  14651. */
  14652. int getScreenY() const;
  14653. /** Returns the mouse position of this event, in global screen co-ordinates.
  14654. The co-ordinates are relative to the top-left of the main monitor.
  14655. @see getMouseDownScreenPosition
  14656. */
  14657. const Point<int> getScreenPosition() const;
  14658. /** Returns the x co-ordinate at which the mouse button was last pressed.
  14659. The co-ordinates are relative to the top-left of the main monitor.
  14660. @see getMouseDownScreenPosition
  14661. */
  14662. int getMouseDownScreenX() const;
  14663. /** Returns the y co-ordinate at which the mouse button was last pressed.
  14664. The co-ordinates are relative to the top-left of the main monitor.
  14665. @see getMouseDownScreenPosition
  14666. */
  14667. int getMouseDownScreenY() const;
  14668. /** Returns the co-ordinates at which the mouse button was last pressed.
  14669. The co-ordinates are relative to the top-left of the main monitor.
  14670. @see getScreenPosition
  14671. */
  14672. const Point<int> getMouseDownScreenPosition() const;
  14673. /** Creates a version of this event that is relative to a different component.
  14674. The x and y positions of the event that is returned will have been
  14675. adjusted to be relative to the new component.
  14676. */
  14677. const MouseEvent getEventRelativeTo (Component* otherComponent) const throw();
  14678. /** Creates a copy of this event with a different position.
  14679. All other members of the event object are the same, but the x and y are
  14680. replaced with these new values.
  14681. */
  14682. const MouseEvent withNewPosition (const Point<int>& newPosition) const throw();
  14683. /** Changes the application-wide setting for the double-click time limit.
  14684. This is the maximum length of time between mouse-clicks for it to be
  14685. considered a double-click. It's used by the Component class.
  14686. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  14687. */
  14688. static void setDoubleClickTimeout (int timeOutMilliseconds) throw();
  14689. /** Returns the application-wide setting for the double-click time limit.
  14690. This is the maximum length of time between mouse-clicks for it to be
  14691. considered a double-click. It's used by the Component class.
  14692. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  14693. */
  14694. static int getDoubleClickTimeout() throw();
  14695. juce_UseDebuggingNewOperator
  14696. private:
  14697. const Point<int> mouseDownPos;
  14698. const Time mouseDownTime;
  14699. const int numberOfClicks;
  14700. const bool wasMovedSinceMouseDown;
  14701. MouseEvent& operator= (const MouseEvent&);
  14702. };
  14703. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  14704. /*** End of inlined file: juce_MouseEvent.h ***/
  14705. /*** Start of inlined file: juce_ComponentListener.h ***/
  14706. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  14707. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  14708. class Component;
  14709. /**
  14710. Gets informed about changes to a component's hierarchy or position.
  14711. To monitor a component for changes, register a subclass of ComponentListener
  14712. with the component using Component::addComponentListener().
  14713. Be sure to deregister listeners before you delete them!
  14714. @see Component::addComponentListener, Component::removeComponentListener
  14715. */
  14716. class JUCE_API ComponentListener
  14717. {
  14718. public:
  14719. /** Destructor. */
  14720. virtual ~ComponentListener() {}
  14721. /** Called when the component's position or size changes.
  14722. @param component the component that was moved or resized
  14723. @param wasMoved true if the component's top-left corner has just moved
  14724. @param wasResized true if the component's width or height has just changed
  14725. @see Component::setBounds, Component::resized, Component::moved
  14726. */
  14727. virtual void componentMovedOrResized (Component& component,
  14728. bool wasMoved,
  14729. bool wasResized);
  14730. /** Called when the component is brought to the top of the z-order.
  14731. @param component the component that was moved
  14732. @see Component::toFront, Component::broughtToFront
  14733. */
  14734. virtual void componentBroughtToFront (Component& component);
  14735. /** Called when the component is made visible or invisible.
  14736. @param component the component that changed
  14737. @see Component::setVisible
  14738. */
  14739. virtual void componentVisibilityChanged (Component& component);
  14740. /** Called when the component has children added or removed.
  14741. @param component the component whose children were changed
  14742. @see Component::childrenChanged, Component::addChildComponent,
  14743. Component::removeChildComponent
  14744. */
  14745. virtual void componentChildrenChanged (Component& component);
  14746. /** Called to indicate that the component's parents have changed.
  14747. When a component is added or removed from its parent, all of its children
  14748. will produce this notification (recursively - so all children of its
  14749. children will also be called as well).
  14750. @param component the component that this listener is registered with
  14751. @see Component::parentHierarchyChanged
  14752. */
  14753. virtual void componentParentHierarchyChanged (Component& component);
  14754. /** Called when the component's name is changed.
  14755. @see Component::setName, Component::getName
  14756. */
  14757. virtual void componentNameChanged (Component& component);
  14758. /** Called when the component is in the process of being deleted.
  14759. This callback is made from inside the destructor, so be very, very cautious
  14760. about what you do inside the callback.
  14761. It will be called before the component has been removed from its parent, and
  14762. before any child components have been removed.
  14763. */
  14764. virtual void componentBeingDeleted (Component& component);
  14765. };
  14766. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  14767. /*** End of inlined file: juce_ComponentListener.h ***/
  14768. /*** Start of inlined file: juce_KeyListener.h ***/
  14769. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  14770. #define __JUCE_KEYLISTENER_JUCEHEADER__
  14771. /*** Start of inlined file: juce_KeyPress.h ***/
  14772. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  14773. #define __JUCE_KEYPRESS_JUCEHEADER__
  14774. /**
  14775. Represents a key press, including any modifier keys that are needed.
  14776. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  14777. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  14778. */
  14779. class JUCE_API KeyPress
  14780. {
  14781. public:
  14782. /** Creates an (invalid) KeyPress.
  14783. @see isValid
  14784. */
  14785. KeyPress() throw();
  14786. /** Creates a KeyPress for a key and some modifiers.
  14787. e.g.
  14788. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  14789. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  14790. @param keyCode a code that represents the key - this value must be
  14791. one of special constants listed in this class, or an
  14792. 8-bit character code such as a letter (case is ignored),
  14793. digit or a simple key like "," or ".". Note that this
  14794. isn't the same as the textCharacter parameter, so for example
  14795. a keyCode of 'a' and a shift-key modifier should have a
  14796. textCharacter value of 'A'.
  14797. @param modifiers the modifiers to associate with the keystroke
  14798. @param textCharacter the character that would be printed if someone typed
  14799. this keypress into a text editor. This value may be
  14800. null if the keypress is a non-printing character
  14801. @see getKeyCode, isKeyCode, getModifiers
  14802. */
  14803. KeyPress (int keyCode,
  14804. const ModifierKeys& modifiers,
  14805. juce_wchar textCharacter) throw();
  14806. /** Creates a keypress with a keyCode but no modifiers or text character.
  14807. */
  14808. KeyPress (int keyCode) throw();
  14809. /** Creates a copy of another KeyPress. */
  14810. KeyPress (const KeyPress& other) throw();
  14811. /** Copies this KeyPress from another one. */
  14812. KeyPress& operator= (const KeyPress& other) throw();
  14813. /** Compares two KeyPress objects. */
  14814. bool operator== (const KeyPress& other) const throw();
  14815. /** Compares two KeyPress objects. */
  14816. bool operator!= (const KeyPress& other) const throw();
  14817. /** Returns true if this is a valid KeyPress.
  14818. A null keypress can be created by the default constructor, in case it's
  14819. needed.
  14820. */
  14821. bool isValid() const throw() { return keyCode != 0; }
  14822. /** Returns the key code itself.
  14823. This will either be one of the special constants defined in this class,
  14824. or an 8-bit character code.
  14825. */
  14826. int getKeyCode() const throw() { return keyCode; }
  14827. /** Returns the key modifiers.
  14828. @see ModifierKeys
  14829. */
  14830. const ModifierKeys getModifiers() const throw() { return mods; }
  14831. /** Returns the character that is associated with this keypress.
  14832. This is the character that you'd expect to see printed if you press this
  14833. keypress in a text editor or similar component.
  14834. */
  14835. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  14836. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  14837. the modifiers.
  14838. The values for key codes can either be one of the special constants defined in
  14839. this class, or an 8-bit character code.
  14840. @see getKeyCode
  14841. */
  14842. bool isKeyCode (int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  14843. /** Converts a textual key description to a KeyPress.
  14844. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  14845. This isn't designed to cope with any kind of input, but should be given the
  14846. strings that are created by the getTextDescription() method.
  14847. If the string can't be parsed, the object returned will be invalid.
  14848. @see getTextDescription
  14849. */
  14850. static const KeyPress createFromDescription (const String& textVersion);
  14851. /** Creates a textual description of the key combination.
  14852. e.g. "CTRL + C" or "DELETE".
  14853. To store a keypress in a file, use this method, along with createFromDescription()
  14854. to retrieve it later.
  14855. */
  14856. const String getTextDescription() const;
  14857. /** Checks whether the user is currently holding down the keys that make up this
  14858. KeyPress.
  14859. Note that this will return false if any extra modifier keys are
  14860. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  14861. then it will be false.
  14862. */
  14863. bool isCurrentlyDown() const;
  14864. /** Checks whether a particular key is held down, irrespective of modifiers.
  14865. The values for key codes can either be one of the special constants defined in
  14866. this class, or an 8-bit character code.
  14867. */
  14868. static bool isKeyCurrentlyDown (int keyCode);
  14869. // Key codes
  14870. //
  14871. // Note that the actual values of these are platform-specific and may change
  14872. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  14873. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  14874. //
  14875. static const int spaceKey; /**< key-code for the space bar */
  14876. static const int escapeKey; /**< key-code for the escape key */
  14877. static const int returnKey; /**< key-code for the return key*/
  14878. static const int tabKey; /**< key-code for the tab key*/
  14879. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  14880. static const int backspaceKey; /**< key-code for the backspace key */
  14881. static const int insertKey; /**< key-code for the insert key */
  14882. static const int upKey; /**< key-code for the cursor-up key */
  14883. static const int downKey; /**< key-code for the cursor-down key */
  14884. static const int leftKey; /**< key-code for the cursor-left key */
  14885. static const int rightKey; /**< key-code for the cursor-right key */
  14886. static const int pageUpKey; /**< key-code for the page-up key */
  14887. static const int pageDownKey; /**< key-code for the page-down key */
  14888. static const int homeKey; /**< key-code for the home key */
  14889. static const int endKey; /**< key-code for the end key */
  14890. static const int F1Key; /**< key-code for the F1 key */
  14891. static const int F2Key; /**< key-code for the F2 key */
  14892. static const int F3Key; /**< key-code for the F3 key */
  14893. static const int F4Key; /**< key-code for the F4 key */
  14894. static const int F5Key; /**< key-code for the F5 key */
  14895. static const int F6Key; /**< key-code for the F6 key */
  14896. static const int F7Key; /**< key-code for the F7 key */
  14897. static const int F8Key; /**< key-code for the F8 key */
  14898. static const int F9Key; /**< key-code for the F9 key */
  14899. static const int F10Key; /**< key-code for the F10 key */
  14900. static const int F11Key; /**< key-code for the F11 key */
  14901. static const int F12Key; /**< key-code for the F12 key */
  14902. static const int F13Key; /**< key-code for the F13 key */
  14903. static const int F14Key; /**< key-code for the F14 key */
  14904. static const int F15Key; /**< key-code for the F15 key */
  14905. static const int F16Key; /**< key-code for the F16 key */
  14906. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  14907. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  14908. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  14909. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  14910. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  14911. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  14912. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  14913. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  14914. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  14915. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  14916. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  14917. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  14918. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  14919. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  14920. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  14921. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  14922. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  14923. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  14924. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  14925. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  14926. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  14927. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  14928. juce_UseDebuggingNewOperator
  14929. private:
  14930. int keyCode;
  14931. ModifierKeys mods;
  14932. juce_wchar textCharacter;
  14933. };
  14934. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  14935. /*** End of inlined file: juce_KeyPress.h ***/
  14936. class Component;
  14937. /**
  14938. Receives callbacks when keys are pressed.
  14939. You can add a key listener to a component to be informed when that component
  14940. gets key events. See the Component::addListener method for more details.
  14941. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  14942. */
  14943. class JUCE_API KeyListener
  14944. {
  14945. public:
  14946. /** Destructor. */
  14947. virtual ~KeyListener() {}
  14948. /** Called to indicate that a key has been pressed.
  14949. If your implementation returns true, then the key event is considered to have
  14950. been consumed, and will not be passed on to any other components. If it returns
  14951. false, then the key will be passed to other components that might want to use it.
  14952. @param key the keystroke, including modifier keys
  14953. @param originatingComponent the component that received the key event
  14954. @see keyStateChanged, Component::keyPressed
  14955. */
  14956. virtual bool keyPressed (const KeyPress& key,
  14957. Component* originatingComponent) = 0;
  14958. /** Called when any key is pressed or released.
  14959. When this is called, classes that might be interested in
  14960. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  14961. check whether their key has changed.
  14962. If your implementation returns true, then the key event is considered to have
  14963. been consumed, and will not be passed on to any other components. If it returns
  14964. false, then the key will be passed to other components that might want to use it.
  14965. @param originatingComponent the component that received the key event
  14966. @param isKeyDown true if a key is being pressed, false if one is being released
  14967. @see KeyPress, Component::keyStateChanged
  14968. */
  14969. virtual bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  14970. };
  14971. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  14972. /*** End of inlined file: juce_KeyListener.h ***/
  14973. /*** Start of inlined file: juce_KeyboardFocusTraverser.h ***/
  14974. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  14975. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  14976. class Component;
  14977. /**
  14978. Controls the order in which focus moves between components.
  14979. The default algorithm used by this class to work out the order of traversal
  14980. is as follows:
  14981. - if two components both have an explicit focus order specified, then the
  14982. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  14983. method).
  14984. - any component with an explicit focus order greater than 0 comes before ones
  14985. that don't have an order specified.
  14986. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  14987. order.
  14988. If you need traversal in a more customised way, you can create a subclass
  14989. of KeyboardFocusTraverser that uses your own algorithm, and use
  14990. Component::createFocusTraverser() to create it.
  14991. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  14992. */
  14993. class JUCE_API KeyboardFocusTraverser
  14994. {
  14995. public:
  14996. KeyboardFocusTraverser();
  14997. /** Destructor. */
  14998. virtual ~KeyboardFocusTraverser();
  14999. /** Returns the component that should be given focus after the specified one
  15000. when moving "forwards".
  15001. The default implementation will return the next component which is to the
  15002. right of or below this one.
  15003. This may return 0 if there's no suitable candidate.
  15004. */
  15005. virtual Component* getNextComponent (Component* current);
  15006. /** Returns the component that should be given focus after the specified one
  15007. when moving "backwards".
  15008. The default implementation will return the next component which is to the
  15009. left of or above this one.
  15010. This may return 0 if there's no suitable candidate.
  15011. */
  15012. virtual Component* getPreviousComponent (Component* current);
  15013. /** Returns the component that should receive focus be default within the given
  15014. parent component.
  15015. The default implementation will just return the foremost child component that
  15016. wants focus.
  15017. This may return 0 if there's no suitable candidate.
  15018. */
  15019. virtual Component* getDefaultComponent (Component* parentComponent);
  15020. };
  15021. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  15022. /*** End of inlined file: juce_KeyboardFocusTraverser.h ***/
  15023. /*** Start of inlined file: juce_ImageEffectFilter.h ***/
  15024. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  15025. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  15026. /*** Start of inlined file: juce_Graphics.h ***/
  15027. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  15028. #define __JUCE_GRAPHICS_JUCEHEADER__
  15029. /*** Start of inlined file: juce_Font.h ***/
  15030. #ifndef __JUCE_FONT_JUCEHEADER__
  15031. #define __JUCE_FONT_JUCEHEADER__
  15032. /*** Start of inlined file: juce_Typeface.h ***/
  15033. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  15034. #define __JUCE_TYPEFACE_JUCEHEADER__
  15035. /*** Start of inlined file: juce_Path.h ***/
  15036. #ifndef __JUCE_PATH_JUCEHEADER__
  15037. #define __JUCE_PATH_JUCEHEADER__
  15038. /*** Start of inlined file: juce_Line.h ***/
  15039. #ifndef __JUCE_LINE_JUCEHEADER__
  15040. #define __JUCE_LINE_JUCEHEADER__
  15041. /**
  15042. Represents a line.
  15043. This class contains a bunch of useful methods for various geometric
  15044. tasks.
  15045. The ValueType template parameter should be a primitive type - float or double
  15046. are what it's designed for. Integer types will work in a basic way, but some methods
  15047. that perform mathematical operations may not compile, or they may not produce
  15048. sensible results.
  15049. @see Point, Rectangle, Path, Graphics::drawLine
  15050. */
  15051. template <typename ValueType>
  15052. class Line
  15053. {
  15054. public:
  15055. /** Creates a line, using (0, 0) as its start and end points. */
  15056. Line() throw() {}
  15057. /** Creates a copy of another line. */
  15058. Line (const Line& other) throw()
  15059. : start (other.start),
  15060. end (other.end)
  15061. {
  15062. }
  15063. /** Creates a line based on the co-ordinates of its start and end points. */
  15064. Line (ValueType startX, ValueType startY, ValueType endX, ValueType endY) throw()
  15065. : start (startX, startY),
  15066. end (endX, endY)
  15067. {
  15068. }
  15069. /** Creates a line from its start and end points. */
  15070. Line (const Point<ValueType>& startPoint,
  15071. const Point<ValueType>& endPoint) throw()
  15072. : start (startPoint),
  15073. end (endPoint)
  15074. {
  15075. }
  15076. /** Copies a line from another one. */
  15077. Line& operator= (const Line& other) throw()
  15078. {
  15079. start = other.start;
  15080. end = other.end;
  15081. return *this;
  15082. }
  15083. /** Destructor. */
  15084. ~Line() throw() {}
  15085. /** Returns the x co-ordinate of the line's start point. */
  15086. inline ValueType getStartX() const throw() { return start.getX(); }
  15087. /** Returns the y co-ordinate of the line's start point. */
  15088. inline ValueType getStartY() const throw() { return start.getY(); }
  15089. /** Returns the x co-ordinate of the line's end point. */
  15090. inline ValueType getEndX() const throw() { return end.getX(); }
  15091. /** Returns the y co-ordinate of the line's end point. */
  15092. inline ValueType getEndY() const throw() { return end.getY(); }
  15093. /** Returns the line's start point. */
  15094. inline const Point<ValueType>& getStart() const throw() { return start; }
  15095. /** Returns the line's end point. */
  15096. inline const Point<ValueType>& getEnd() const throw() { return end; }
  15097. /** Changes this line's start point */
  15098. void setStart (ValueType newStartX, ValueType newStartY) throw() { start.setXY (newStartX, newStartY); }
  15099. /** Changes this line's end point */
  15100. void setEnd (ValueType newEndX, ValueType newEndY) throw() { end.setXY (newEndX, newEndY); }
  15101. /** Changes this line's start point */
  15102. void setStart (const Point<ValueType>& newStart) throw() { start = newStart; }
  15103. /** Changes this line's end point */
  15104. void setEnd (const Point<ValueType>& newEnd) throw() { end = newEnd; }
  15105. /** Returns a line that is the same as this one, but with the start and end reversed, */
  15106. const Line reversed() const throw() { return Line (end, start); }
  15107. /** Applies an affine transform to the line's start and end points. */
  15108. void applyTransform (const AffineTransform& transform) throw()
  15109. {
  15110. start.applyTransform (transform);
  15111. end.applyTransform (transform);
  15112. }
  15113. /** Returns the length of the line. */
  15114. ValueType getLength() const throw() { return start.getDistanceFrom (end); }
  15115. /** Returns true if the line's start and end x co-ordinates are the same. */
  15116. bool isVertical() const throw() { return start.getX() == end.getX(); }
  15117. /** Returns true if the line's start and end y co-ordinates are the same. */
  15118. bool isHorizontal() const throw() { return start.getY() == end.getY(); }
  15119. /** Returns the line's angle.
  15120. This value is the number of radians clockwise from the 3 o'clock direction,
  15121. where the line's start point is considered to be at the centre.
  15122. */
  15123. ValueType getAngle() const throw() { return start.getAngleToPoint (end); }
  15124. /** Compares two lines. */
  15125. bool operator== (const Line& other) const throw() { return start == other.start && end == other.end; }
  15126. /** Compares two lines. */
  15127. bool operator!= (const Line& other) const throw() { return start != other.start || end != other.end; }
  15128. /** Finds the intersection between two lines.
  15129. @param line the other line
  15130. @param intersection the position of the point where the lines meet (or
  15131. where they would meet if they were infinitely long)
  15132. the intersection (if the lines intersect). If the lines
  15133. are parallel, this will just be set to the position
  15134. of one of the line's endpoints.
  15135. @returns true if the line segments intersect; false if they dont. Even if they
  15136. don't intersect, the intersection co-ordinates returned will still
  15137. be valid
  15138. */
  15139. bool intersects (const Line& line, Point<ValueType>& intersection) const throw()
  15140. {
  15141. return findIntersection (start, end, line.start, line.end, intersection);
  15142. }
  15143. /** Finds the intersection between two lines.
  15144. @param line the line to intersect with
  15145. @returns the point at which the lines intersect, even if this lies beyond the end of the lines
  15146. */
  15147. const Point<ValueType> getIntersection (const Line& line) const throw()
  15148. {
  15149. Point<ValueType> p;
  15150. findIntersection (start, end, line.start, line.end, p);
  15151. return p;
  15152. }
  15153. /** Returns the location of the point which is a given distance along this line.
  15154. @param distanceFromStart the distance to move along the line from its
  15155. start point. This value can be negative or longer
  15156. than the line itself
  15157. @see getPointAlongLineProportionally
  15158. */
  15159. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart) const throw()
  15160. {
  15161. return start + (end - start) * (distanceFromStart / getLength());
  15162. }
  15163. /** Returns a point which is a certain distance along and to the side of this line.
  15164. This effectively moves a given distance along the line, then another distance
  15165. perpendicularly to this, and returns the resulting position.
  15166. @param distanceFromStart the distance to move along the line from its
  15167. start point. This value can be negative or longer
  15168. than the line itself
  15169. @param perpendicularDistance how far to move sideways from the line. If you're
  15170. looking along the line from its start towards its
  15171. end, then a positive value here will move to the
  15172. right, negative value move to the left.
  15173. */
  15174. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart,
  15175. ValueType perpendicularDistance) const throw()
  15176. {
  15177. const Point<ValueType> delta (end - start);
  15178. const double length = juce_hypot (delta.getX(), delta.getY());
  15179. if (length == 0)
  15180. return start;
  15181. return Point<ValueType> (start.getX() + (ValueType) ((delta.getX() * distanceFromStart - delta.getY() * perpendicularDistance) / length),
  15182. start.getY() + (ValueType) ((delta.getY() * distanceFromStart + delta.getX() * perpendicularDistance) / length));
  15183. }
  15184. /** Returns the location of the point which is a given distance along this line
  15185. proportional to the line's length.
  15186. @param proportionOfLength the distance to move along the line from its
  15187. start point, in multiples of the line's length.
  15188. So a value of 0.0 will return the line's start point
  15189. and a value of 1.0 will return its end point. (This value
  15190. can be negative or greater than 1.0).
  15191. @see getPointAlongLine
  15192. */
  15193. const Point<ValueType> getPointAlongLineProportionally (ValueType proportionOfLength) const throw()
  15194. {
  15195. return start + (end - start) * proportionOfLength;
  15196. }
  15197. /** Returns the smallest distance between this line segment and a given point.
  15198. So if the point is close to the line, this will return the perpendicular
  15199. distance from the line; if the point is a long way beyond one of the line's
  15200. end-point's, it'll return the straight-line distance to the nearest end-point.
  15201. @returns the point's distance from the line
  15202. @see getPositionAlongLineOfNearestPoint
  15203. */
  15204. ValueType getDistanceFromPoint (const Point<ValueType>& point) const throw()
  15205. {
  15206. const Point<ValueType> delta (end - start);
  15207. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  15208. if (length > 0)
  15209. {
  15210. const double prop = ((point.getX() - start.getX()) * delta.getX()
  15211. + (point.getY() - start.getY()) * delta.getY()) / length;
  15212. if (prop >= 0 && prop <= 1.0)
  15213. return point.getDistanceFrom (start + delta * (ValueType) prop);
  15214. }
  15215. return jmin (point.getDistanceFrom (start),
  15216. point.getDistanceFrom (end));
  15217. }
  15218. /** Finds the point on this line which is nearest to a given point, and
  15219. returns its position as a proportional position along the line.
  15220. @returns a value 0 to 1.0 which is the distance along this line from the
  15221. line's start to the point which is nearest to the point passed-in. To
  15222. turn this number into a position, use getPointAlongLineProportionally().
  15223. @see getDistanceFromPoint, getPointAlongLineProportionally
  15224. */
  15225. ValueType findNearestProportionalPositionTo (const Point<ValueType>& point) const throw()
  15226. {
  15227. const Point<ValueType> delta (end - start);
  15228. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  15229. return length <= 0 ? 0
  15230. : jlimit ((ValueType) 0, (ValueType) 1,
  15231. (ValueType) (((point.getX() - start.getX()) * delta.getX()
  15232. + (point.getY() - start.getY()) * delta.getY()) / length));
  15233. }
  15234. /** Finds the point on this line which is nearest to a given point.
  15235. @see getDistanceFromPoint, findNearestProportionalPositionTo
  15236. */
  15237. const Point<ValueType> findNearestPointTo (const Point<ValueType>& point) const throw()
  15238. {
  15239. return getPointAlongLineProportionally (findNearestProportionalPositionTo (point));
  15240. }
  15241. /** Returns true if the given point lies above this line.
  15242. The return value is true if the point's y coordinate is less than the y
  15243. coordinate of this line at the given x (assuming the line extends infinitely
  15244. in both directions).
  15245. */
  15246. bool isPointAbove (const Point<ValueType>& point) const throw()
  15247. {
  15248. return start.getX() != end.getX()
  15249. && point.getY() < ((end.getY() - start.getY())
  15250. * (point.getX() - start.getX())) / (end.getX() - start.getX()) + start.getY();
  15251. }
  15252. /** Returns a shortened copy of this line.
  15253. This will chop off part of the start of this line by a certain amount, (leaving the
  15254. end-point the same), and return the new line.
  15255. */
  15256. const Line withShortenedStart (ValueType distanceToShortenBy) const throw()
  15257. {
  15258. return Line (getPointAlongLine (jmin (distanceToShortenBy, getLength())), end);
  15259. }
  15260. /** Returns a shortened copy of this line.
  15261. This will chop off part of the end of this line by a certain amount, (leaving the
  15262. start-point the same), and return the new line.
  15263. */
  15264. const Line withShortenedEnd (ValueType distanceToShortenBy) const throw()
  15265. {
  15266. const ValueType length = getLength();
  15267. return Line (start, getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  15268. }
  15269. juce_UseDebuggingNewOperator
  15270. private:
  15271. Point<ValueType> start, end;
  15272. static bool findIntersection (const Point<ValueType>& p1, const Point<ValueType>& p2,
  15273. const Point<ValueType>& p3, const Point<ValueType>& p4,
  15274. Point<ValueType>& intersection) throw()
  15275. {
  15276. if (p2 == p3)
  15277. {
  15278. intersection = p2;
  15279. return true;
  15280. }
  15281. const Point<ValueType> d1 (p2 - p1);
  15282. const Point<ValueType> d2 (p4 - p3);
  15283. const ValueType divisor = d1.getX() * d2.getY() - d2.getX() * d1.getY();
  15284. if (divisor == 0)
  15285. {
  15286. if (! (d1.isOrigin() || d2.isOrigin()))
  15287. {
  15288. if (d1.getY() == 0 && d2.getY() != 0)
  15289. {
  15290. const ValueType along = (p1.getY() - p3.getY()) / d2.getY();
  15291. intersection = p1.withX (p3.getX() + along * d2.getX());
  15292. return along >= 0 && along <= (ValueType) 1;
  15293. }
  15294. else if (d2.getY() == 0 && d1.getY() != 0)
  15295. {
  15296. const ValueType along = (p3.getY() - p1.getY()) / d1.getY();
  15297. intersection = p3.withX (p1.getX() + along * d1.getX());
  15298. return along >= 0 && along <= (ValueType) 1;
  15299. }
  15300. else if (d1.getX() == 0 && d2.getX() != 0)
  15301. {
  15302. const ValueType along = (p1.getX() - p3.getX()) / d2.getX();
  15303. intersection = p1.withY (p3.getY() + along * d2.getY());
  15304. return along >= 0 && along <= (ValueType) 1;
  15305. }
  15306. else if (d2.getX() == 0 && d1.getX() != 0)
  15307. {
  15308. const ValueType along = (p3.getX() - p1.getX()) / d1.getX();
  15309. intersection = p3.withY (p1.getY() + along * d1.getY());
  15310. return along >= 0 && along <= (ValueType) 1;
  15311. }
  15312. }
  15313. intersection = (p2 + p3) / (ValueType) 2;
  15314. return false;
  15315. }
  15316. const ValueType along1 = ((p1.getY() - p3.getY()) * d2.getX() - (p1.getX() - p3.getX()) * d2.getY()) / divisor;
  15317. intersection = p1 + d1 * along1;
  15318. if (along1 < 0 || along1 > (ValueType) 1)
  15319. return false;
  15320. const ValueType along2 = ((p1.getY() - p3.getY()) * d1.getX() - (p1.getX() - p3.getX()) * d1.getY()) / divisor;
  15321. return along2 >= 0 && along2 <= (ValueType) 1;
  15322. }
  15323. };
  15324. #endif // __JUCE_LINE_JUCEHEADER__
  15325. /*** End of inlined file: juce_Line.h ***/
  15326. /*** Start of inlined file: juce_Rectangle.h ***/
  15327. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  15328. #define __JUCE_RECTANGLE_JUCEHEADER__
  15329. class RectangleList;
  15330. /**
  15331. Manages a rectangle and allows geometric operations to be performed on it.
  15332. @see RectangleList, Path, Line, Point
  15333. */
  15334. template <typename ValueType>
  15335. class Rectangle
  15336. {
  15337. public:
  15338. /** Creates a rectangle of zero size.
  15339. The default co-ordinates will be (0, 0, 0, 0).
  15340. */
  15341. Rectangle() throw()
  15342. : x (0), y (0), w (0), h (0)
  15343. {
  15344. }
  15345. /** Creates a copy of another rectangle. */
  15346. Rectangle (const Rectangle& other) throw()
  15347. : x (other.x), y (other.y),
  15348. w (other.w), h (other.h)
  15349. {
  15350. }
  15351. /** Creates a rectangle with a given position and size. */
  15352. Rectangle (const ValueType initialX, const ValueType initialY,
  15353. const ValueType width, const ValueType height) throw()
  15354. : x (initialX), y (initialY),
  15355. w (width), h (height)
  15356. {
  15357. }
  15358. /** Creates a rectangle with a given size, and a position of (0, 0). */
  15359. Rectangle (const ValueType width, const ValueType height) throw()
  15360. : x (0), y (0), w (width), h (height)
  15361. {
  15362. }
  15363. /** Creates a Rectangle from the positions of two opposite corners. */
  15364. Rectangle (const Point<ValueType>& corner1, const Point<ValueType>& corner2) throw()
  15365. : x (jmin (corner1.getX(), corner2.getX())),
  15366. y (jmin (corner1.getY(), corner2.getY())),
  15367. w (corner1.getX() - corner2.getX()),
  15368. h (corner1.getY() - corner2.getY())
  15369. {
  15370. if (w < 0) w = -w;
  15371. if (h < 0) h = -h;
  15372. }
  15373. Rectangle& operator= (const Rectangle& other) throw()
  15374. {
  15375. x = other.x; y = other.y;
  15376. w = other.w; h = other.h;
  15377. return *this;
  15378. }
  15379. /** Destructor. */
  15380. ~Rectangle() throw() {}
  15381. /** Returns true if the rectangle's width and height are both zero or less */
  15382. bool isEmpty() const throw() { return w <= 0 || h <= 0; }
  15383. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  15384. inline ValueType getX() const throw() { return x; }
  15385. /** Returns the y co-ordinate of the rectangle's top edge. */
  15386. inline ValueType getY() const throw() { return y; }
  15387. /** Returns the width of the rectangle. */
  15388. inline ValueType getWidth() const throw() { return w; }
  15389. /** Returns the height of the rectangle. */
  15390. inline ValueType getHeight() const throw() { return h; }
  15391. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  15392. inline ValueType getRight() const throw() { return x + w; }
  15393. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  15394. inline ValueType getBottom() const throw() { return y + h; }
  15395. /** Returns the x co-ordinate of the rectangle's centre. */
  15396. ValueType getCentreX() const throw() { return x + w / (ValueType) 2; }
  15397. /** Returns the y co-ordinate of the rectangle's centre. */
  15398. ValueType getCentreY() const throw() { return y + h / (ValueType) 2; }
  15399. /** Returns the centre point of the rectangle. */
  15400. const Point<ValueType> getCentre() const throw() { return Point<ValueType> (x + w / (ValueType) 2, y + h / (ValueType) 2); }
  15401. /** Returns the aspect ratio of the rectangle's width / height.
  15402. If widthOverHeight is true, it returns width / height; if widthOverHeight is false,
  15403. it returns height / width. */
  15404. ValueType getAspectRatio (const bool widthOverHeight = true) const throw() { return widthOverHeight ? w / h : h / w; }
  15405. /** Returns the rectangle's top-left position as a Point. */
  15406. const Point<ValueType> getPosition() const throw() { return Point<ValueType> (x, y); }
  15407. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  15408. void setPosition (const Point<ValueType>& newPos) throw() { x = newPos.getX(); y = newPos.getY(); }
  15409. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  15410. void setPosition (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  15411. /** Returns a rectangle with the same size as this one, but a new position. */
  15412. const Rectangle withPosition (const Point<ValueType>& newPos) const throw() { return Rectangle (newPos.getX(), newPos.getY(), w, h); }
  15413. /** Returns the rectangle's top-left position as a Point. */
  15414. const Point<ValueType> getTopLeft() const throw() { return getPosition(); }
  15415. /** Returns the rectangle's top-right position as a Point. */
  15416. const Point<ValueType> getTopRight() const throw() { return Point<float> (x + w, y); }
  15417. /** Returns the rectangle's bottom-left position as a Point. */
  15418. const Point<ValueType> getBottomLeft() const throw() { return Point<float> (x, y + h); }
  15419. /** Returns the rectangle's bottom-right position as a Point. */
  15420. const Point<ValueType> getBottomRight() const throw() { return Point<float> (x + w, y + h); }
  15421. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  15422. void setSize (const ValueType newWidth, const ValueType newHeight) throw() { w = newWidth; h = newHeight; }
  15423. /** Returns a rectangle with the same position as this one, but a new size. */
  15424. const Rectangle withSize (const ValueType newWidth, const ValueType newHeight) const throw() { return Rectangle (x, y, newWidth, newHeight); }
  15425. /** Changes all the rectangle's co-ordinates. */
  15426. void setBounds (const ValueType newX, const ValueType newY,
  15427. const ValueType newWidth, const ValueType newHeight) throw()
  15428. {
  15429. x = newX; y = newY; w = newWidth; h = newHeight;
  15430. }
  15431. /** Changes the rectangle's width */
  15432. void setWidth (const ValueType newWidth) throw() { w = newWidth; }
  15433. /** Changes the rectangle's height */
  15434. void setHeight (const ValueType newHeight) throw() { h = newHeight; }
  15435. /** Returns a rectangle which has the same size and y-position as this one, but with a different x-position. */
  15436. const Rectangle withX (const ValueType newX) const throw() { return Rectangle (newX, y, w, h); }
  15437. /** Returns a rectangle which has the same size and x-position as this one, but with a different y-position. */
  15438. const Rectangle withY (const ValueType newY) const throw() { return Rectangle (x, newY, w, h); }
  15439. /** Returns a rectangle which has the same position and height as this one, but with a different width. */
  15440. const Rectangle withWidth (const ValueType newWidth) const throw() { return Rectangle (x, y, newWidth, h); }
  15441. /** Returns a rectangle which has the same position and width as this one, but with a different height. */
  15442. const Rectangle withHeight (const ValueType newHeight) const throw() { return Rectangle (x, y, w, newHeight); }
  15443. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  15444. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  15445. */
  15446. void setLeft (const ValueType newLeft) throw()
  15447. {
  15448. w = jmax (ValueType(), x + w - newLeft);
  15449. x = newLeft;
  15450. }
  15451. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  15452. If the y is moved to be below the current bottom edge, the height will be set to zero.
  15453. */
  15454. void setTop (const ValueType newTop) throw()
  15455. {
  15456. h = jmax (ValueType(), y + h - newTop);
  15457. y = newTop;
  15458. }
  15459. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  15460. If the new right is below the current X value, the X will be pushed down to match it.
  15461. @see getRight
  15462. */
  15463. void setRight (const ValueType newRight) throw()
  15464. {
  15465. x = jmin (x, newRight);
  15466. w = newRight - x;
  15467. }
  15468. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  15469. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  15470. @see getBottom
  15471. */
  15472. void setBottom (const ValueType newBottom) throw()
  15473. {
  15474. y = jmin (y, newBottom);
  15475. h = newBottom - y;
  15476. }
  15477. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  15478. void translate (const ValueType deltaX,
  15479. const ValueType deltaY) throw()
  15480. {
  15481. x += deltaX;
  15482. y += deltaY;
  15483. }
  15484. /** Returns a rectangle which is the same as this one moved by a given amount. */
  15485. const Rectangle translated (const ValueType deltaX,
  15486. const ValueType deltaY) const throw()
  15487. {
  15488. return Rectangle (x + deltaX, y + deltaY, w, h);
  15489. }
  15490. /** Returns a rectangle which is the same as this one moved by a given amount. */
  15491. const Rectangle operator+ (const Point<ValueType>& deltaPosition) const throw()
  15492. {
  15493. return Rectangle (x + deltaPosition.getX(), y + deltaPosition.getY(), w, h);
  15494. }
  15495. /** Moves this rectangle by a given amount. */
  15496. Rectangle& operator+= (const Point<ValueType>& deltaPosition) throw()
  15497. {
  15498. x += deltaPosition.getX(); y += deltaPosition.getY();
  15499. return *this;
  15500. }
  15501. /** Returns a rectangle which is the same as this one moved by a given amount. */
  15502. const Rectangle operator- (const Point<ValueType>& deltaPosition) const throw()
  15503. {
  15504. return Rectangle (x - deltaPosition.getX(), y - deltaPosition.getY(), w, h);
  15505. }
  15506. /** Moves this rectangle by a given amount. */
  15507. Rectangle& operator-= (const Point<ValueType>& deltaPosition) throw()
  15508. {
  15509. x -= deltaPosition.getX(); y -= deltaPosition.getY();
  15510. return *this;
  15511. }
  15512. /** Expands the rectangle by a given amount.
  15513. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  15514. @see expanded, reduce, reduced
  15515. */
  15516. void expand (const ValueType deltaX,
  15517. const ValueType deltaY) throw()
  15518. {
  15519. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  15520. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  15521. setBounds (x - deltaX, y - deltaY, nw, nh);
  15522. }
  15523. /** Returns a rectangle that is larger than this one by a given amount.
  15524. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  15525. @see expand, reduce, reduced
  15526. */
  15527. const Rectangle expanded (const ValueType deltaX,
  15528. const ValueType deltaY) const throw()
  15529. {
  15530. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  15531. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  15532. return Rectangle (x - deltaX, y - deltaY, nw, nh);
  15533. }
  15534. /** Shrinks the rectangle by a given amount.
  15535. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  15536. @see reduced, expand, expanded
  15537. */
  15538. void reduce (const ValueType deltaX,
  15539. const ValueType deltaY) throw()
  15540. {
  15541. expand (-deltaX, -deltaY);
  15542. }
  15543. /** Returns a rectangle that is smaller than this one by a given amount.
  15544. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  15545. @see reduce, expand, expanded
  15546. */
  15547. const Rectangle reduced (const ValueType deltaX,
  15548. const ValueType deltaY) const throw()
  15549. {
  15550. return expanded (-deltaX, -deltaY);
  15551. }
  15552. /** Returns true if the two rectangles are identical. */
  15553. bool operator== (const Rectangle& other) const throw()
  15554. {
  15555. return x == other.x && y == other.y
  15556. && w == other.w && h == other.h;
  15557. }
  15558. /** Returns true if the two rectangles are not identical. */
  15559. bool operator!= (const Rectangle& other) const throw()
  15560. {
  15561. return x != other.x || y != other.y
  15562. || w != other.w || h != other.h;
  15563. }
  15564. /** Returns true if this co-ordinate is inside the rectangle. */
  15565. bool contains (const ValueType xCoord, const ValueType yCoord) const throw()
  15566. {
  15567. return xCoord >= x && yCoord >= y && xCoord < x + w && yCoord < y + h;
  15568. }
  15569. /** Returns true if this co-ordinate is inside the rectangle. */
  15570. bool contains (const Point<ValueType>& point) const throw()
  15571. {
  15572. return point.getX() >= x && point.getY() >= y && point.getX() < x + w && point.getY() < y + h;
  15573. }
  15574. /** Returns true if this other rectangle is completely inside this one. */
  15575. bool contains (const Rectangle& other) const throw()
  15576. {
  15577. return x <= other.x && y <= other.y
  15578. && x + w >= other.x + other.w && y + h >= other.y + other.h;
  15579. }
  15580. /** Returns the nearest point to the specified point that lies within this rectangle. */
  15581. const Point<ValueType> getConstrainedPoint (const Point<ValueType>& point) const throw()
  15582. {
  15583. return Point<ValueType> (jlimit (x, x + w, point.getX()),
  15584. jlimit (y, y + h, point.getY()));
  15585. }
  15586. /** Returns true if any part of another rectangle overlaps this one. */
  15587. bool intersects (const Rectangle& other) const throw()
  15588. {
  15589. return x + w > other.x
  15590. && y + h > other.y
  15591. && x < other.x + other.w
  15592. && y < other.y + other.h
  15593. && w > ValueType() && h > ValueType();
  15594. }
  15595. /** Returns the region that is the overlap between this and another rectangle.
  15596. If the two rectangles don't overlap, the rectangle returned will be empty.
  15597. */
  15598. const Rectangle getIntersection (const Rectangle& other) const throw()
  15599. {
  15600. const ValueType nx = jmax (x, other.x);
  15601. const ValueType ny = jmax (y, other.y);
  15602. const ValueType nw = jmin (x + w, other.x + other.w) - nx;
  15603. const ValueType nh = jmin (y + h, other.y + other.h) - ny;
  15604. if (nw >= ValueType() && nh >= ValueType())
  15605. return Rectangle (nx, ny, nw, nh);
  15606. return Rectangle();
  15607. }
  15608. /** Clips a rectangle so that it lies only within this one.
  15609. This is a non-static version of intersectRectangles().
  15610. Returns false if the two regions didn't overlap.
  15611. */
  15612. bool intersectRectangle (ValueType& otherX, ValueType& otherY, ValueType& otherW, ValueType& otherH) const throw()
  15613. {
  15614. const int maxX = jmax (otherX, x);
  15615. otherW = jmin (otherX + otherW, x + w) - maxX;
  15616. if (otherW > 0)
  15617. {
  15618. const int maxY = jmax (otherY, y);
  15619. otherH = jmin (otherY + otherH, y + h) - maxY;
  15620. if (otherH > 0)
  15621. {
  15622. otherX = maxX; otherY = maxY;
  15623. return true;
  15624. }
  15625. }
  15626. return false;
  15627. }
  15628. /** Returns the smallest rectangle that contains both this one and the one passed-in.
  15629. If either this or the other rectangle are empty, they will not be counted as
  15630. part of the resulting region.
  15631. */
  15632. const Rectangle getUnion (const Rectangle& other) const throw()
  15633. {
  15634. if (other.isEmpty()) return *this;
  15635. if (isEmpty()) return other;
  15636. const ValueType newX = jmin (x, other.x);
  15637. const ValueType newY = jmin (y, other.y);
  15638. return Rectangle (newX, newY,
  15639. jmax (x + w, other.x + other.w) - newX,
  15640. jmax (y + h, other.y + other.h) - newY);
  15641. }
  15642. /** If this rectangle merged with another one results in a simple rectangle, this
  15643. will set this rectangle to the result, and return true.
  15644. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  15645. or if they form a complex region.
  15646. */
  15647. bool enlargeIfAdjacent (const Rectangle& other) throw()
  15648. {
  15649. if (x == other.x && getRight() == other.getRight()
  15650. && (other.getBottom() >= y && other.y <= getBottom()))
  15651. {
  15652. const ValueType newY = jmin (y, other.y);
  15653. h = jmax (getBottom(), other.getBottom()) - newY;
  15654. y = newY;
  15655. return true;
  15656. }
  15657. else if (y == other.y && getBottom() == other.getBottom()
  15658. && (other.getRight() >= x && other.x <= getRight()))
  15659. {
  15660. const ValueType newX = jmin (x, other.x);
  15661. w = jmax (getRight(), other.getRight()) - newX;
  15662. x = newX;
  15663. return true;
  15664. }
  15665. return false;
  15666. }
  15667. /** If after removing another rectangle from this one the result is a simple rectangle,
  15668. this will set this object's bounds to be the result, and return true.
  15669. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  15670. or if removing the other one would form a complex region.
  15671. */
  15672. bool reduceIfPartlyContainedIn (const Rectangle& other) throw()
  15673. {
  15674. int inside = 0;
  15675. const int otherR = other.getRight();
  15676. if (x >= other.x && x < otherR) inside = 1;
  15677. const int otherB = other.getBottom();
  15678. if (y >= other.y && y < otherB) inside |= 2;
  15679. const int r = x + w;
  15680. if (r >= other.x && r < otherR) inside |= 4;
  15681. const int b = y + h;
  15682. if (b >= other.y && b < otherB) inside |= 8;
  15683. switch (inside)
  15684. {
  15685. case 1 + 2 + 8: w = r - otherR; x = otherR; return true;
  15686. case 1 + 2 + 4: h = b - otherB; y = otherB; return true;
  15687. case 2 + 4 + 8: w = other.x - x; return true;
  15688. case 1 + 4 + 8: h = other.y - y; return true;
  15689. }
  15690. return false;
  15691. }
  15692. /** Returns the smallest rectangle that can contain the shape created by applying
  15693. a transform to this rectangle.
  15694. This should only be used on floating point rectangles.
  15695. */
  15696. const Rectangle<ValueType> transformed (const AffineTransform& transform) const throw()
  15697. {
  15698. float x1 = x, y1 = y;
  15699. float x2 = x + w, y2 = y;
  15700. float x3 = x, y3 = y + h;
  15701. float x4 = x2, y4 = y3;
  15702. transform.transformPoint (x1, y1);
  15703. transform.transformPoint (x2, y2);
  15704. transform.transformPoint (x3, y3);
  15705. transform.transformPoint (x4, y4);
  15706. const float rx = jmin (x1, x2, x3, x4);
  15707. const float ry = jmin (y1, y2, y3, y4);
  15708. return Rectangle (rx, ry,
  15709. jmax (x1, x2, x3, x4) - rx,
  15710. jmax (y1, y2, y3, y4) - ry);
  15711. }
  15712. /** Returns the smallest integer-aligned rectangle that completely contains this one.
  15713. This is only relevent for floating-point rectangles, of course.
  15714. @see toFloat()
  15715. */
  15716. const Rectangle<int> getSmallestIntegerContainer() const throw()
  15717. {
  15718. const int x1 = (int) std::floor (static_cast<float> (x));
  15719. const int y1 = (int) std::floor (static_cast<float> (y));
  15720. const int x2 = (int) std::floor (static_cast<float> (x + w + 0.9999f));
  15721. const int y2 = (int) std::floor (static_cast<float> (y + h + 0.9999f));
  15722. return Rectangle<int> (x1, y1, x2 - x1, y2 - y1);
  15723. }
  15724. /** Returns the smallest Rectangle that can contain a set of points. */
  15725. static const Rectangle findAreaContainingPoints (const Point<ValueType>* const points, const int numPoints) throw()
  15726. {
  15727. if (numPoints == 0)
  15728. return Rectangle();
  15729. ValueType minX (points[0].getX());
  15730. ValueType maxX (minX);
  15731. ValueType minY (points[0].getY());
  15732. ValueType maxY (minY);
  15733. for (int i = 1; i < numPoints; ++i)
  15734. {
  15735. minX = jmin (minX, points[i].getX());
  15736. maxX = jmax (maxX, points[i].getX());
  15737. minY = jmin (minY, points[i].getY());
  15738. maxY = jmax (maxY, points[i].getY());
  15739. }
  15740. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  15741. }
  15742. /** Casts this rectangle to a Rectangle<float>.
  15743. Obviously this is mainly useful for rectangles that use integer types.
  15744. @see getSmallestIntegerContainer
  15745. */
  15746. const Rectangle<float> toFloat() const throw()
  15747. {
  15748. return Rectangle<float> (static_cast<float> (x), static_cast<float> (y),
  15749. static_cast<float> (w), static_cast<float> (h));
  15750. }
  15751. /** Static utility to intersect two sets of rectangular co-ordinates.
  15752. Returns false if the two regions didn't overlap.
  15753. @see intersectRectangle
  15754. */
  15755. static bool intersectRectangles (ValueType& x1, ValueType& y1, ValueType& w1, ValueType& h1,
  15756. const ValueType x2, const ValueType y2, const ValueType w2, const ValueType h2) throw()
  15757. {
  15758. const ValueType x = jmax (x1, x2);
  15759. w1 = jmin (x1 + w1, x2 + w2) - x;
  15760. if (w1 > 0)
  15761. {
  15762. const ValueType y = jmax (y1, y2);
  15763. h1 = jmin (y1 + h1, y2 + h2) - y;
  15764. if (h1 > 0)
  15765. {
  15766. x1 = x; y1 = y;
  15767. return true;
  15768. }
  15769. }
  15770. return false;
  15771. }
  15772. /** Creates a string describing this rectangle.
  15773. The string will be of the form "x y width height", e.g. "100 100 400 200".
  15774. Coupled with the fromString() method, this is very handy for things like
  15775. storing rectangles (particularly component positions) in XML attributes.
  15776. @see fromString
  15777. */
  15778. const String toString() const
  15779. {
  15780. String s;
  15781. s.preallocateStorage (16);
  15782. s << x << ' ' << y << ' ' << w << ' ' << h;
  15783. return s;
  15784. }
  15785. /** Parses a string containing a rectangle's details.
  15786. The string should contain 4 integer tokens, in the form "x y width height". They
  15787. can be comma or whitespace separated.
  15788. This method is intended to go with the toString() method, to form an easy way
  15789. of saving/loading rectangles as strings.
  15790. @see toString
  15791. */
  15792. static const Rectangle fromString (const String& stringVersion)
  15793. {
  15794. StringArray toks;
  15795. toks.addTokens (stringVersion.trim(), ",; \t\r\n", String::empty);
  15796. return Rectangle (toks[0].trim().getIntValue(),
  15797. toks[1].trim().getIntValue(),
  15798. toks[2].trim().getIntValue(),
  15799. toks[3].trim().getIntValue());
  15800. }
  15801. juce_UseDebuggingNewOperator
  15802. private:
  15803. friend class RectangleList;
  15804. ValueType x, y, w, h;
  15805. };
  15806. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  15807. /*** End of inlined file: juce_Rectangle.h ***/
  15808. /*** Start of inlined file: juce_Justification.h ***/
  15809. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  15810. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  15811. /**
  15812. Represents a type of justification to be used when positioning graphical items.
  15813. e.g. it indicates whether something should be placed top-left, top-right,
  15814. centred, etc.
  15815. It is used in various places wherever this kind of information is needed.
  15816. */
  15817. class JUCE_API Justification
  15818. {
  15819. public:
  15820. /** Creates a Justification object using a combination of flags. */
  15821. inline Justification (int flags_) throw() : flags (flags_) {}
  15822. /** Creates a copy of another Justification object. */
  15823. Justification (const Justification& other) throw();
  15824. /** Copies another Justification object. */
  15825. Justification& operator= (const Justification& other) throw();
  15826. bool operator== (const Justification& other) const throw() { return flags == other.flags; }
  15827. bool operator!= (const Justification& other) const throw() { return flags != other.flags; }
  15828. /** Returns the raw flags that are set for this Justification object. */
  15829. inline int getFlags() const throw() { return flags; }
  15830. /** Tests a set of flags for this object.
  15831. @returns true if any of the flags passed in are set on this object.
  15832. */
  15833. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  15834. /** Returns just the flags from this object that deal with vertical layout. */
  15835. int getOnlyVerticalFlags() const throw();
  15836. /** Returns just the flags from this object that deal with horizontal layout. */
  15837. int getOnlyHorizontalFlags() const throw();
  15838. /** Adjusts the position of a rectangle to fit it into a space.
  15839. The (x, y) position of the rectangle will be updated to position it inside the
  15840. given space according to the justification flags.
  15841. */
  15842. void applyToRectangle (int& x, int& y, int w, int h,
  15843. int spaceX, int spaceY, int spaceW, int spaceH) const throw();
  15844. /** Flag values that can be combined and used in the constructor. */
  15845. enum
  15846. {
  15847. /** Indicates that the item should be aligned against the left edge of the available space. */
  15848. left = 1,
  15849. /** Indicates that the item should be aligned against the right edge of the available space. */
  15850. right = 2,
  15851. /** Indicates that the item should be placed in the centre between the left and right
  15852. sides of the available space. */
  15853. horizontallyCentred = 4,
  15854. /** Indicates that the item should be aligned against the top edge of the available space. */
  15855. top = 8,
  15856. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  15857. bottom = 16,
  15858. /** Indicates that the item should be placed in the centre between the top and bottom
  15859. sides of the available space. */
  15860. verticallyCentred = 32,
  15861. /** Indicates that lines of text should be spread out to fill the maximum width
  15862. available, so that both margins are aligned vertically.
  15863. */
  15864. horizontallyJustified = 64,
  15865. /** Indicates that the item should be centred vertically and horizontally.
  15866. This is equivalent to (horizontallyCentred | verticallyCentred)
  15867. */
  15868. centred = 36,
  15869. /** Indicates that the item should be centred vertically but placed on the left hand side.
  15870. This is equivalent to (left | verticallyCentred)
  15871. */
  15872. centredLeft = 33,
  15873. /** Indicates that the item should be centred vertically but placed on the right hand side.
  15874. This is equivalent to (right | verticallyCentred)
  15875. */
  15876. centredRight = 34,
  15877. /** Indicates that the item should be centred horizontally and placed at the top.
  15878. This is equivalent to (horizontallyCentred | top)
  15879. */
  15880. centredTop = 12,
  15881. /** Indicates that the item should be centred horizontally and placed at the bottom.
  15882. This is equivalent to (horizontallyCentred | bottom)
  15883. */
  15884. centredBottom = 20,
  15885. /** Indicates that the item should be placed in the top-left corner.
  15886. This is equivalent to (left | top)
  15887. */
  15888. topLeft = 9,
  15889. /** Indicates that the item should be placed in the top-right corner.
  15890. This is equivalent to (right | top)
  15891. */
  15892. topRight = 10,
  15893. /** Indicates that the item should be placed in the bottom-left corner.
  15894. This is equivalent to (left | bottom)
  15895. */
  15896. bottomLeft = 17,
  15897. /** Indicates that the item should be placed in the bottom-left corner.
  15898. This is equivalent to (right | bottom)
  15899. */
  15900. bottomRight = 18
  15901. };
  15902. private:
  15903. int flags;
  15904. };
  15905. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  15906. /*** End of inlined file: juce_Justification.h ***/
  15907. class Image;
  15908. /**
  15909. A path is a sequence of lines and curves that may either form a closed shape
  15910. or be open-ended.
  15911. To use a path, you can create an empty one, then add lines and curves to it
  15912. to create shapes, then it can be rendered by a Graphics context or used
  15913. for geometric operations.
  15914. e.g. @code
  15915. Path myPath;
  15916. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  15917. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  15918. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  15919. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  15920. // add an ellipse as well, which will form a second sub-path within the path..
  15921. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  15922. // double the width of the whole thing..
  15923. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  15924. // and draw it to a graphics context with a 5-pixel thick outline.
  15925. g.strokePath (myPath, PathStrokeType (5.0f));
  15926. @endcode
  15927. A path object can actually contain multiple sub-paths, which may themselves
  15928. be open or closed.
  15929. @see PathFlatteningIterator, PathStrokeType, Graphics
  15930. */
  15931. class JUCE_API Path
  15932. {
  15933. public:
  15934. /** Creates an empty path. */
  15935. Path();
  15936. /** Creates a copy of another path. */
  15937. Path (const Path& other);
  15938. /** Destructor. */
  15939. ~Path();
  15940. /** Copies this path from another one. */
  15941. Path& operator= (const Path& other);
  15942. bool operator== (const Path& other) const throw();
  15943. bool operator!= (const Path& other) const throw();
  15944. /** Returns true if the path doesn't contain any lines or curves. */
  15945. bool isEmpty() const throw();
  15946. /** Returns the smallest rectangle that contains all points within the path.
  15947. */
  15948. const Rectangle<float> getBounds() const throw();
  15949. /** Returns the smallest rectangle that contains all points within the path
  15950. after it's been transformed with the given tranasform matrix.
  15951. */
  15952. const Rectangle<float> getBoundsTransformed (const AffineTransform& transform) const throw();
  15953. /** Checks whether a point lies within the path.
  15954. This is only relevent for closed paths (see closeSubPath()), and
  15955. may produce false results if used on a path which has open sub-paths.
  15956. The path's winding rule is taken into account by this method.
  15957. The tolerence parameter is passed to the PathFlatteningIterator that
  15958. is used to trace the path - for more info about it, see the notes for
  15959. the PathFlatteningIterator constructor.
  15960. @see closeSubPath, setUsingNonZeroWinding
  15961. */
  15962. bool contains (float x, float y,
  15963. float tolerence = 10.0f) const;
  15964. /** Checks whether a point lies within the path.
  15965. This is only relevent for closed paths (see closeSubPath()), and
  15966. may produce false results if used on a path which has open sub-paths.
  15967. The path's winding rule is taken into account by this method.
  15968. The tolerence parameter is passed to the PathFlatteningIterator that
  15969. is used to trace the path - for more info about it, see the notes for
  15970. the PathFlatteningIterator constructor.
  15971. @see closeSubPath, setUsingNonZeroWinding
  15972. */
  15973. bool contains (const Point<float>& point,
  15974. float tolerence = 10.0f) const;
  15975. /** Checks whether a line crosses the path.
  15976. This will return positive if the line crosses any of the paths constituent
  15977. lines or curves. It doesn't take into account whether the line is inside
  15978. or outside the path, or whether the path is open or closed.
  15979. The tolerence parameter is passed to the PathFlatteningIterator that
  15980. is used to trace the path - for more info about it, see the notes for
  15981. the PathFlatteningIterator constructor.
  15982. */
  15983. bool intersectsLine (const Line<float>& line,
  15984. float tolerence = 10.0f);
  15985. /** Cuts off parts of a line to keep the parts that are either inside or
  15986. outside this path.
  15987. Note that this isn't smart enough to cope with situations where the
  15988. line would need to be cut into multiple pieces to correctly clip against
  15989. a re-entrant shape.
  15990. @param line the line to clip
  15991. @param keepSectionOutsidePath if true, it's the section outside the path
  15992. that will be kept; if false its the section inside
  15993. the path
  15994. */
  15995. const Line<float> getClippedLine (const Line<float>& line, bool keepSectionOutsidePath) const;
  15996. /** Removes all lines and curves, resetting the path completely. */
  15997. void clear() throw();
  15998. /** Begins a new subpath with a given starting position.
  15999. This will move the path's current position to the co-ordinates passed in and
  16000. make it ready to draw lines or curves starting from this position.
  16001. After adding whatever lines and curves are needed, you can either
  16002. close the current sub-path using closeSubPath() or call startNewSubPath()
  16003. to move to a new sub-path, leaving the old one open-ended.
  16004. @see lineTo, quadraticTo, cubicTo, closeSubPath
  16005. */
  16006. void startNewSubPath (float startX, float startY);
  16007. /** Begins a new subpath with a given starting position.
  16008. This will move the path's current position to the co-ordinates passed in and
  16009. make it ready to draw lines or curves starting from this position.
  16010. After adding whatever lines and curves are needed, you can either
  16011. close the current sub-path using closeSubPath() or call startNewSubPath()
  16012. to move to a new sub-path, leaving the old one open-ended.
  16013. @see lineTo, quadraticTo, cubicTo, closeSubPath
  16014. */
  16015. void startNewSubPath (const Point<float>& start);
  16016. /** Closes a the current sub-path with a line back to its start-point.
  16017. When creating a closed shape such as a triangle, don't use 3 lineTo()
  16018. calls - instead use two lineTo() calls, followed by a closeSubPath()
  16019. to join the final point back to the start.
  16020. This ensures that closes shapes are recognised as such, and this is
  16021. important for tasks like drawing strokes, which needs to know whether to
  16022. draw end-caps or not.
  16023. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  16024. */
  16025. void closeSubPath();
  16026. /** Adds a line from the shape's last position to a new end-point.
  16027. This will connect the end-point of the last line or curve that was added
  16028. to a new point, using a straight line.
  16029. See the class description for an example of how to add lines and curves to a path.
  16030. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  16031. */
  16032. void lineTo (float endX, float endY);
  16033. /** Adds a line from the shape's last position to a new end-point.
  16034. This will connect the end-point of the last line or curve that was added
  16035. to a new point, using a straight line.
  16036. See the class description for an example of how to add lines and curves to a path.
  16037. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  16038. */
  16039. void lineTo (const Point<float>& end);
  16040. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  16041. This will connect the end-point of the last line or curve that was added
  16042. to a new point, using a quadratic spline with one control-point.
  16043. See the class description for an example of how to add lines and curves to a path.
  16044. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  16045. */
  16046. void quadraticTo (float controlPointX,
  16047. float controlPointY,
  16048. float endPointX,
  16049. float endPointY);
  16050. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  16051. This will connect the end-point of the last line or curve that was added
  16052. to a new point, using a quadratic spline with one control-point.
  16053. See the class description for an example of how to add lines and curves to a path.
  16054. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  16055. */
  16056. void quadraticTo (const Point<float>& controlPoint,
  16057. const Point<float>& endPoint);
  16058. /** Adds a cubic bezier curve from the shape's last position to a new position.
  16059. This will connect the end-point of the last line or curve that was added
  16060. to a new point, using a cubic spline with two control-points.
  16061. See the class description for an example of how to add lines and curves to a path.
  16062. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  16063. */
  16064. void cubicTo (float controlPoint1X,
  16065. float controlPoint1Y,
  16066. float controlPoint2X,
  16067. float controlPoint2Y,
  16068. float endPointX,
  16069. float endPointY);
  16070. /** Adds a cubic bezier curve from the shape's last position to a new position.
  16071. This will connect the end-point of the last line or curve that was added
  16072. to a new point, using a cubic spline with two control-points.
  16073. See the class description for an example of how to add lines and curves to a path.
  16074. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  16075. */
  16076. void cubicTo (const Point<float>& controlPoint1,
  16077. const Point<float>& controlPoint2,
  16078. const Point<float>& endPoint);
  16079. /** Returns the last point that was added to the path by one of the drawing methods.
  16080. */
  16081. const Point<float> getCurrentPosition() const;
  16082. /** Adds a rectangle to the path.
  16083. The rectangle is added as a new sub-path. (Any currently open paths will be
  16084. left open).
  16085. @see addRoundedRectangle, addTriangle
  16086. */
  16087. void addRectangle (float x, float y, float width, float height);
  16088. /** Adds a rectangle to the path.
  16089. The rectangle is added as a new sub-path. (Any currently open paths will be
  16090. left open).
  16091. @see addRoundedRectangle, addTriangle
  16092. */
  16093. void addRectangle (const Rectangle<int>& rectangle);
  16094. /** Adds a rectangle with rounded corners to the path.
  16095. The rectangle is added as a new sub-path. (Any currently open paths will be
  16096. left open).
  16097. @see addRectangle, addTriangle
  16098. */
  16099. void addRoundedRectangle (float x, float y, float width, float height,
  16100. float cornerSize);
  16101. /** Adds a rectangle with rounded corners to the path.
  16102. The rectangle is added as a new sub-path. (Any currently open paths will be
  16103. left open).
  16104. @see addRectangle, addTriangle
  16105. */
  16106. void addRoundedRectangle (float x, float y, float width, float height,
  16107. float cornerSizeX,
  16108. float cornerSizeY);
  16109. /** Adds a triangle to the path.
  16110. The triangle is added as a new closed sub-path. (Any currently open paths will be
  16111. left open).
  16112. Note that whether the vertices are specified in clockwise or anticlockwise
  16113. order will affect how the triangle is filled when it overlaps other
  16114. shapes (the winding order setting will affect this of course).
  16115. */
  16116. void addTriangle (float x1, float y1,
  16117. float x2, float y2,
  16118. float x3, float y3);
  16119. /** Adds a quadrilateral to the path.
  16120. The quad is added as a new closed sub-path. (Any currently open paths will be
  16121. left open).
  16122. Note that whether the vertices are specified in clockwise or anticlockwise
  16123. order will affect how the quad is filled when it overlaps other
  16124. shapes (the winding order setting will affect this of course).
  16125. */
  16126. void addQuadrilateral (float x1, float y1,
  16127. float x2, float y2,
  16128. float x3, float y3,
  16129. float x4, float y4);
  16130. /** Adds an ellipse to the path.
  16131. The shape is added as a new sub-path. (Any currently open paths will be
  16132. left open).
  16133. @see addArc
  16134. */
  16135. void addEllipse (float x, float y, float width, float height);
  16136. /** Adds an elliptical arc to the current path.
  16137. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  16138. or anti-clockwise according to whether the end angle is greater than the start. This means
  16139. that sometimes you may need to use values greater than 2*Pi for the end angle.
  16140. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  16141. @param y the top edge of the rectangle in which the elliptical outline fits
  16142. @param width the width of the rectangle in which the elliptical outline fits
  16143. @param height the height of the rectangle in which the elliptical outline fits
  16144. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  16145. top-centre of the ellipse)
  16146. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  16147. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  16148. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  16149. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  16150. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  16151. it will be added to the current sub-path, continuing from the current postition
  16152. @see addCentredArc, arcTo, addPieSegment, addEllipse
  16153. */
  16154. void addArc (float x, float y, float width, float height,
  16155. float fromRadians,
  16156. float toRadians,
  16157. bool startAsNewSubPath = false);
  16158. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  16159. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  16160. or anti-clockwise according to whether the end angle is greater than the start. This means
  16161. that sometimes you may need to use values greater than 2*Pi for the end angle.
  16162. @param centreX the centre x of the ellipse
  16163. @param centreY the centre y of the ellipse
  16164. @param radiusX the horizontal radius of the ellipse
  16165. @param radiusY the vertical radius of the ellipse
  16166. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  16167. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  16168. top-centre of the ellipse)
  16169. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  16170. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  16171. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  16172. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  16173. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  16174. it will be added to the current sub-path, continuing from the current postition
  16175. @see addArc, arcTo
  16176. */
  16177. void addCentredArc (float centreX, float centreY,
  16178. float radiusX, float radiusY,
  16179. float rotationOfEllipse,
  16180. float fromRadians,
  16181. float toRadians,
  16182. bool startAsNewSubPath = false);
  16183. /** Adds a "pie-chart" shape to the path.
  16184. The shape is added as a new sub-path. (Any currently open paths will be
  16185. left open).
  16186. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  16187. or anti-clockwise according to whether the end angle is greater than the start. This means
  16188. that sometimes you may need to use values greater than 2*Pi for the end angle.
  16189. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  16190. @param y the top edge of the rectangle in which the elliptical outline fits
  16191. @param width the width of the rectangle in which the elliptical outline fits
  16192. @param height the height of the rectangle in which the elliptical outline fits
  16193. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  16194. top-centre of the ellipse)
  16195. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  16196. top-centre of the ellipse)
  16197. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  16198. ellipse at its centre, where this value indicates the inner ellipse's size with
  16199. respect to the outer one.
  16200. @see addArc
  16201. */
  16202. void addPieSegment (float x, float y,
  16203. float width, float height,
  16204. float fromRadians,
  16205. float toRadians,
  16206. float innerCircleProportionalSize);
  16207. /** Adds a line with a specified thickness.
  16208. The line is added as a new closed sub-path. (Any currently open paths will be
  16209. left open).
  16210. @see addArrow
  16211. */
  16212. void addLineSegment (const Line<float>& line, float lineThickness);
  16213. /** Adds a line with an arrowhead on the end.
  16214. The arrow is added as a new closed sub-path. (Any currently open paths will be left open).
  16215. @see PathStrokeType::createStrokeWithArrowheads
  16216. */
  16217. void addArrow (const Line<float>& line,
  16218. float lineThickness,
  16219. float arrowheadWidth,
  16220. float arrowheadLength);
  16221. /** Adds a polygon shape to the path.
  16222. @see addStar
  16223. */
  16224. void addPolygon (const Point<float>& centre,
  16225. int numberOfSides,
  16226. float radius,
  16227. float startAngle = 0.0f);
  16228. /** Adds a star shape to the path.
  16229. @see addPolygon
  16230. */
  16231. void addStar (const Point<float>& centre,
  16232. int numberOfPoints,
  16233. float innerRadius,
  16234. float outerRadius,
  16235. float startAngle = 0.0f);
  16236. /** Adds a speech-bubble shape to the path.
  16237. @param bodyX the left of the main body area of the bubble
  16238. @param bodyY the top of the main body area of the bubble
  16239. @param bodyW the width of the main body area of the bubble
  16240. @param bodyH the height of the main body area of the bubble
  16241. @param cornerSize the amount by which to round off the corners of the main body rectangle
  16242. @param arrowTipX the x position that the tip of the arrow should connect to
  16243. @param arrowTipY the y position that the tip of the arrow should connect to
  16244. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  16245. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  16246. arrow's base should be - this is a proportional distance between 0 and 1.0
  16247. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  16248. */
  16249. void addBubble (float bodyX, float bodyY,
  16250. float bodyW, float bodyH,
  16251. float cornerSize,
  16252. float arrowTipX,
  16253. float arrowTipY,
  16254. int whichSide,
  16255. float arrowPositionAlongEdgeProportional,
  16256. float arrowWidth);
  16257. /** Adds another path to this one.
  16258. The new path is added as a new sub-path. (Any currently open paths in this
  16259. path will be left open).
  16260. @param pathToAppend the path to add
  16261. */
  16262. void addPath (const Path& pathToAppend);
  16263. /** Adds another path to this one, transforming it on the way in.
  16264. The new path is added as a new sub-path, its points being transformed by the given
  16265. matrix before being added.
  16266. @param pathToAppend the path to add
  16267. @param transformToApply an optional transform to apply to the incoming vertices
  16268. */
  16269. void addPath (const Path& pathToAppend,
  16270. const AffineTransform& transformToApply);
  16271. /** Swaps the contents of this path with another one.
  16272. The internal data of the two paths is swapped over, so this is much faster than
  16273. copying it to a temp variable and back.
  16274. */
  16275. void swapWithPath (Path& other) throw();
  16276. /** Applies a 2D transform to all the vertices in the path.
  16277. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  16278. */
  16279. void applyTransform (const AffineTransform& transform) throw();
  16280. /** Rescales this path to make it fit neatly into a given space.
  16281. This is effectively a quick way of calling
  16282. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  16283. @param x the x position of the rectangle to fit the path inside
  16284. @param y the y position of the rectangle to fit the path inside
  16285. @param width the width of the rectangle to fit the path inside
  16286. @param height the height of the rectangle to fit the path inside
  16287. @param preserveProportions if true, it will fit the path into the space without altering its
  16288. horizontal/vertical scale ratio; if false, it will distort the
  16289. path to fill the specified ratio both horizontally and vertically
  16290. @see applyTransform, getTransformToScaleToFit
  16291. */
  16292. void scaleToFit (float x, float y, float width, float height,
  16293. bool preserveProportions) throw();
  16294. /** Returns a transform that can be used to rescale the path to fit into a given space.
  16295. @param x the x position of the rectangle to fit the path inside
  16296. @param y the y position of the rectangle to fit the path inside
  16297. @param width the width of the rectangle to fit the path inside
  16298. @param height the height of the rectangle to fit the path inside
  16299. @param preserveProportions if true, it will fit the path into the space without altering its
  16300. horizontal/vertical scale ratio; if false, it will distort the
  16301. path to fill the specified ratio both horizontally and vertically
  16302. @param justificationType if the proportions are preseved, the resultant path may be smaller
  16303. than the available rectangle, so this describes how it should be
  16304. positioned within the space.
  16305. @returns an appropriate transformation
  16306. @see applyTransform, scaleToFit
  16307. */
  16308. const AffineTransform getTransformToScaleToFit (float x, float y, float width, float height,
  16309. bool preserveProportions,
  16310. const Justification& justificationType = Justification::centred) const;
  16311. /** Creates a version of this path where all sharp corners have been replaced by curves.
  16312. Wherever two lines meet at an angle, this will replace the corner with a curve
  16313. of the given radius.
  16314. */
  16315. const Path createPathWithRoundedCorners (float cornerRadius) const;
  16316. /** Changes the winding-rule to be used when filling the path.
  16317. If set to true (which is the default), then the path uses a non-zero-winding rule
  16318. to determine which points are inside the path. If set to false, it uses an
  16319. alternate-winding rule.
  16320. The winding-rule comes into play when areas of the shape overlap other
  16321. areas, and determines whether the overlapping regions are considered to be
  16322. inside or outside.
  16323. Changing this value just sets a flag - it doesn't affect the contents of the
  16324. path.
  16325. @see isUsingNonZeroWinding
  16326. */
  16327. void setUsingNonZeroWinding (bool isNonZeroWinding) throw();
  16328. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  16329. The default for a new path is true.
  16330. @see setUsingNonZeroWinding
  16331. */
  16332. bool isUsingNonZeroWinding() const { return useNonZeroWinding; }
  16333. /** Iterates the lines and curves that a path contains.
  16334. @see Path, PathFlatteningIterator
  16335. */
  16336. class JUCE_API Iterator
  16337. {
  16338. public:
  16339. Iterator (const Path& path);
  16340. ~Iterator();
  16341. /** Moves onto the next element in the path.
  16342. If this returns false, there are no more elements. If it returns true,
  16343. the elementType variable will be set to the type of the current element,
  16344. and some of the x and y variables will be filled in with values.
  16345. */
  16346. bool next();
  16347. enum PathElementType
  16348. {
  16349. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  16350. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  16351. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  16352. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  16353. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  16354. };
  16355. PathElementType elementType;
  16356. float x1, y1, x2, y2, x3, y3;
  16357. private:
  16358. const Path& path;
  16359. size_t index;
  16360. Iterator (const Iterator&);
  16361. Iterator& operator= (const Iterator&);
  16362. };
  16363. /** Loads a stored path from a data stream.
  16364. The data in the stream must have been written using writePathToStream().
  16365. Note that this will append the stored path to whatever is currently in
  16366. this path, so you might need to call clear() beforehand.
  16367. @see loadPathFromData, writePathToStream
  16368. */
  16369. void loadPathFromStream (InputStream& source);
  16370. /** Loads a stored path from a block of data.
  16371. This is similar to loadPathFromStream(), but just reads from a block
  16372. of data. Useful if you're including stored shapes in your code as a
  16373. block of static data.
  16374. @see loadPathFromStream, writePathToStream
  16375. */
  16376. void loadPathFromData (const void* data, int numberOfBytes);
  16377. /** Stores the path by writing it out to a stream.
  16378. After writing out a path, you can reload it using loadPathFromStream().
  16379. @see loadPathFromStream, loadPathFromData
  16380. */
  16381. void writePathToStream (OutputStream& destination) const;
  16382. /** Creates a string containing a textual representation of this path.
  16383. @see restoreFromString
  16384. */
  16385. const String toString() const;
  16386. /** Restores this path from a string that was created with the toString() method.
  16387. @see toString()
  16388. */
  16389. void restoreFromString (const String& stringVersion);
  16390. juce_UseDebuggingNewOperator
  16391. private:
  16392. friend class PathFlatteningIterator;
  16393. friend class Path::Iterator;
  16394. ArrayAllocationBase <float, DummyCriticalSection> data;
  16395. size_t numElements;
  16396. float pathXMin, pathXMax, pathYMin, pathYMax;
  16397. bool useNonZeroWinding;
  16398. static const float lineMarker;
  16399. static const float moveMarker;
  16400. static const float quadMarker;
  16401. static const float cubicMarker;
  16402. static const float closeSubPathMarker;
  16403. };
  16404. #endif // __JUCE_PATH_JUCEHEADER__
  16405. /*** End of inlined file: juce_Path.h ***/
  16406. class Font;
  16407. /** A typeface represents a size-independent font.
  16408. This base class is abstract, but calling createSystemTypefaceFor() will return
  16409. a platform-specific subclass that can be used.
  16410. The CustomTypeface subclass allow you to build your own typeface, and to
  16411. load and save it in the Juce typeface format.
  16412. Normally you should never need to deal directly with Typeface objects - the Font
  16413. class does everything you typically need for rendering text.
  16414. @see CustomTypeface, Font
  16415. */
  16416. class JUCE_API Typeface : public ReferenceCountedObject
  16417. {
  16418. public:
  16419. /** A handy typedef for a pointer to a typeface. */
  16420. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  16421. /** Returns the name of the typeface.
  16422. @see Font::getTypefaceName
  16423. */
  16424. const String getName() const throw() { return name; }
  16425. /** Creates a new system typeface. */
  16426. static const Ptr createSystemTypefaceFor (const Font& font);
  16427. /** Destructor. */
  16428. virtual ~Typeface();
  16429. /** Returns the ascent of the font, as a proportion of its height.
  16430. The height is considered to always be normalised as 1.0, so this will be a
  16431. value less that 1.0, indicating the proportion of the font that lies above
  16432. its baseline.
  16433. */
  16434. virtual float getAscent() const = 0;
  16435. /** Returns the descent of the font, as a proportion of its height.
  16436. The height is considered to always be normalised as 1.0, so this will be a
  16437. value less that 1.0, indicating the proportion of the font that lies below
  16438. its baseline.
  16439. */
  16440. virtual float getDescent() const = 0;
  16441. /** Measures the width of a line of text.
  16442. The distance returned is based on the font having an normalised height of 1.0.
  16443. You should never need to call this directly! Use Font::getStringWidth() instead!
  16444. */
  16445. virtual float getStringWidth (const String& text) = 0;
  16446. /** Converts a line of text into its glyph numbers and their positions.
  16447. The distances returned are based on the font having an normalised height of 1.0.
  16448. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  16449. */
  16450. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  16451. /** Returns the outline for a glyph.
  16452. The path returned will be normalised to a font height of 1.0.
  16453. */
  16454. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  16455. juce_UseDebuggingNewOperator
  16456. protected:
  16457. String name;
  16458. explicit Typeface (const String& name) throw();
  16459. private:
  16460. Typeface (const Typeface&);
  16461. Typeface& operator= (const Typeface&);
  16462. };
  16463. /** A typeface that can be populated with custom glyphs.
  16464. You can create a CustomTypeface if you need one that contains your own glyphs,
  16465. or if you need to load a typeface from a Juce-formatted binary stream.
  16466. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  16467. to copy glyphs into this face.
  16468. @see Typeface, Font
  16469. */
  16470. class JUCE_API CustomTypeface : public Typeface
  16471. {
  16472. public:
  16473. /** Creates a new, empty typeface. */
  16474. CustomTypeface();
  16475. /** Loads a typeface from a previously saved stream.
  16476. The stream must have been created by writeToStream().
  16477. @see writeToStream
  16478. */
  16479. explicit CustomTypeface (InputStream& serialisedTypefaceStream);
  16480. /** Destructor. */
  16481. ~CustomTypeface();
  16482. /** Resets this typeface, deleting all its glyphs and settings. */
  16483. void clear();
  16484. /** Sets the vital statistics for the typeface.
  16485. @param name the typeface's name
  16486. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  16487. the value that will be returned by Typeface::getAscent(). The
  16488. descent is assumed to be (1.0 - ascent)
  16489. @param isBold should be true if the typeface is bold
  16490. @param isItalic should be true if the typeface is italic
  16491. @param defaultCharacter the character to be used as a replacement if there's
  16492. no glyph available for the character that's being drawn
  16493. */
  16494. void setCharacteristics (const String& name, float ascent,
  16495. bool isBold, bool isItalic,
  16496. juce_wchar defaultCharacter) throw();
  16497. /** Adds a glyph to the typeface.
  16498. The path that is passed in is normalised so that the font height is 1.0, and its
  16499. origin is the anchor point of the character on its baseline.
  16500. The width is the nominal width of the character, and any extra kerning values that
  16501. are specified will be added to this width.
  16502. */
  16503. void addGlyph (juce_wchar character, const Path& path, float width) throw();
  16504. /** Specifies an extra kerning amount to be used between a pair of characters.
  16505. The amount will be added to the nominal width of the first character when laying out a string.
  16506. */
  16507. void addKerningPair (juce_wchar char1, juce_wchar char2, float extraAmount) throw();
  16508. /** Adds a range of glyphs from another typeface.
  16509. This will attempt to pull in the paths and kerning information from another typeface and
  16510. add it to this one.
  16511. */
  16512. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw();
  16513. /** Saves this typeface as a Juce-formatted font file.
  16514. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  16515. constructor.
  16516. */
  16517. bool writeToStream (OutputStream& outputStream);
  16518. // The following methods implement the basic Typeface behaviour.
  16519. float getAscent() const;
  16520. float getDescent() const;
  16521. float getStringWidth (const String& text);
  16522. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  16523. bool getOutlineForGlyph (int glyphNumber, Path& path);
  16524. int getGlyphForCharacter (juce_wchar character);
  16525. juce_UseDebuggingNewOperator
  16526. protected:
  16527. juce_wchar defaultCharacter;
  16528. float ascent;
  16529. bool isBold, isItalic;
  16530. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  16531. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  16532. particular character and there's no corresponding glyph, they'll call this
  16533. method so that a subclass can try to add that glyph, returning true if it
  16534. manages to do so.
  16535. */
  16536. virtual bool loadGlyphIfPossible (juce_wchar characterNeeded);
  16537. private:
  16538. class GlyphInfo;
  16539. friend class OwnedArray<GlyphInfo>;
  16540. OwnedArray <GlyphInfo> glyphs;
  16541. short lookupTable [128];
  16542. CustomTypeface (const CustomTypeface&);
  16543. CustomTypeface& operator= (const CustomTypeface&);
  16544. GlyphInfo* findGlyph (const juce_wchar character, bool loadIfNeeded) throw();
  16545. GlyphInfo* findGlyphSubstituting (juce_wchar character) throw();
  16546. };
  16547. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  16548. /*** End of inlined file: juce_Typeface.h ***/
  16549. class LowLevelGraphicsContext;
  16550. /**
  16551. Represents a particular font, including its size, style, etc.
  16552. Apart from the typeface to be used, a Font object also dictates whether
  16553. the font is bold, italic, underlined, how big it is, and its kerning and
  16554. horizontal scale factor.
  16555. @see Typeface
  16556. */
  16557. class JUCE_API Font
  16558. {
  16559. public:
  16560. /** A combination of these values is used by the constructor to specify the
  16561. style of font to use.
  16562. */
  16563. enum FontStyleFlags
  16564. {
  16565. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  16566. bold = 1, /**< boldens the font. @see setStyleFlags */
  16567. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  16568. underlined = 4 /**< underlines the font. @see setStyleFlags */
  16569. };
  16570. /** Creates a sans-serif font in a given size.
  16571. @param fontHeight the height in pixels (can be fractional)
  16572. @param styleFlags the style to use - this can be a combination of the
  16573. Font::bold, Font::italic and Font::underlined, or
  16574. just Font::plain for the normal style.
  16575. @see FontStyleFlags, getDefaultSansSerifFontName
  16576. */
  16577. Font (float fontHeight,
  16578. int styleFlags = plain) throw();
  16579. /** Creates a font with a given typeface and parameters.
  16580. @param typefaceName the name of the typeface to use
  16581. @param fontHeight the height in pixels (can be fractional)
  16582. @param styleFlags the style to use - this can be a combination of the
  16583. Font::bold, Font::italic and Font::underlined, or
  16584. just Font::plain for the normal style.
  16585. @see FontStyleFlags, getDefaultSansSerifFontName
  16586. */
  16587. Font (const String& typefaceName,
  16588. float fontHeight,
  16589. int styleFlags) throw();
  16590. /** Creates a copy of another Font object. */
  16591. Font (const Font& other) throw();
  16592. /** Creates a font for a typeface. */
  16593. Font (const Typeface::Ptr& typeface) throw();
  16594. /** Creates a basic sans-serif font at a default height.
  16595. You should use one of the other constructors for creating a font that you're planning
  16596. on drawing with - this constructor is here to help initialise objects before changing
  16597. the font's settings later.
  16598. */
  16599. Font() throw();
  16600. /** Copies this font from another one. */
  16601. Font& operator= (const Font& other) throw();
  16602. bool operator== (const Font& other) const throw();
  16603. bool operator!= (const Font& other) const throw();
  16604. /** Destructor. */
  16605. ~Font() throw();
  16606. /** Changes the name of the typeface family.
  16607. e.g. "Arial", "Courier", etc.
  16608. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  16609. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  16610. but are generic names that are used to represent the various default fonts.
  16611. If you need to know the exact typeface name being used, you can call
  16612. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  16613. If a suitable font isn't found on the machine, it'll just use a default instead.
  16614. */
  16615. void setTypefaceName (const String& faceName) throw();
  16616. /** Returns the name of the typeface family that this font uses.
  16617. e.g. "Arial", "Courier", etc.
  16618. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  16619. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  16620. but are generic names that are used to represent the various default fonts.
  16621. If you need to know the exact typeface name being used, you can call
  16622. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  16623. */
  16624. const String& getTypefaceName() const throw() { return font->typefaceName; }
  16625. /** Returns a typeface name that represents the default sans-serif font.
  16626. This is also the typeface that will be used when a font is created without
  16627. specifying any typeface details.
  16628. Note that this method just returns a generic placeholder string that means "the default
  16629. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  16630. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  16631. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  16632. */
  16633. static const String getDefaultSansSerifFontName() throw();
  16634. /** Returns a typeface name that represents the default sans-serif font.
  16635. Note that this method just returns a generic placeholder string that means "the default
  16636. serif font" - it's not the actual name of this font. To get the actual name, use
  16637. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  16638. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  16639. */
  16640. static const String getDefaultSerifFontName() throw();
  16641. /** Returns a typeface name that represents the default sans-serif font.
  16642. Note that this method just returns a generic placeholder string that means "the default
  16643. monospaced font" - it's not the actual name of this font. To get the actual name, use
  16644. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  16645. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  16646. */
  16647. static const String getDefaultMonospacedFontName() throw();
  16648. /** Returns the typeface names of the default fonts on the current platform. */
  16649. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed);
  16650. /** Returns the total height of this font.
  16651. This is the maximum height, from the top of the ascent to the bottom of the
  16652. descenders.
  16653. @see setHeight, setHeightWithoutChangingWidth, getAscent
  16654. */
  16655. float getHeight() const throw() { return font->height; }
  16656. /** Changes the font's height.
  16657. @see getHeight, setHeightWithoutChangingWidth
  16658. */
  16659. void setHeight (float newHeight) throw();
  16660. /** Changes the font's height without changing its width.
  16661. This alters the horizontal scale to compensate for the change in height.
  16662. */
  16663. void setHeightWithoutChangingWidth (float newHeight) throw();
  16664. /** Returns the height of the font above its baseline.
  16665. This is the maximum height from the baseline to the top.
  16666. @see getHeight, getDescent
  16667. */
  16668. float getAscent() const throw();
  16669. /** Returns the amount that the font descends below its baseline.
  16670. This is calculated as (getHeight() - getAscent()).
  16671. @see getAscent, getHeight
  16672. */
  16673. float getDescent() const throw();
  16674. /** Returns the font's style flags.
  16675. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  16676. enum, to describe whether the font is bold, italic, etc.
  16677. @see FontStyleFlags
  16678. */
  16679. int getStyleFlags() const throw() { return font->styleFlags; }
  16680. /** Changes the font's style.
  16681. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  16682. enum, to set the font's properties
  16683. @see FontStyleFlags
  16684. */
  16685. void setStyleFlags (int newFlags) throw();
  16686. /** Makes the font bold or non-bold. */
  16687. void setBold (bool shouldBeBold) throw();
  16688. /** Returns true if the font is bold. */
  16689. bool isBold() const throw();
  16690. /** Makes the font italic or non-italic. */
  16691. void setItalic (bool shouldBeItalic) throw();
  16692. /** Returns true if the font is italic. */
  16693. bool isItalic() const throw();
  16694. /** Makes the font underlined or non-underlined. */
  16695. void setUnderline (bool shouldBeUnderlined) throw();
  16696. /** Returns true if the font is underlined. */
  16697. bool isUnderlined() const throw();
  16698. /** Changes the font's horizontal scale factor.
  16699. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  16700. narrower, greater than 1.0 will be stretched out.
  16701. */
  16702. void setHorizontalScale (float scaleFactor) throw();
  16703. /** Returns the font's horizontal scale.
  16704. A value of 1.0 is the normal scale, less than this will be narrower, greater
  16705. than 1.0 will be stretched out.
  16706. @see setHorizontalScale
  16707. */
  16708. float getHorizontalScale() const throw() { return font->horizontalScale; }
  16709. /** Changes the font's kerning.
  16710. @param extraKerning a multiple of the font's height that will be added
  16711. to space between the characters. So a value of zero is
  16712. normal spacing, positive values spread the letters out,
  16713. negative values make them closer together.
  16714. */
  16715. void setExtraKerningFactor (float extraKerning) throw();
  16716. /** Returns the font's kerning.
  16717. This is the extra space added between adjacent characters, as a proportion
  16718. of the font's height.
  16719. A value of zero is normal spacing, positive values will spread the letters
  16720. out more, and negative values make them closer together.
  16721. */
  16722. float getExtraKerningFactor() const throw() { return font->kerning; }
  16723. /** Changes all the font's characteristics with one call. */
  16724. void setSizeAndStyle (float newHeight,
  16725. int newStyleFlags,
  16726. float newHorizontalScale,
  16727. float newKerningAmount) throw();
  16728. /** Returns the total width of a string as it would be drawn using this font.
  16729. For a more accurate floating-point result, use getStringWidthFloat().
  16730. */
  16731. int getStringWidth (const String& text) const throw();
  16732. /** Returns the total width of a string as it would be drawn using this font.
  16733. @see getStringWidth
  16734. */
  16735. float getStringWidthFloat (const String& text) const throw();
  16736. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  16737. An extra x offset is added at the end of the run, to indicate where the right hand
  16738. edge of the last character is.
  16739. */
  16740. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw();
  16741. /** Returns the typeface used by this font.
  16742. Note that the object returned may go out of scope if this font is deleted
  16743. or has its style changed.
  16744. */
  16745. Typeface* getTypeface() const throw();
  16746. /** Creates an array of Font objects to represent all the fonts on the system.
  16747. If you just need the names of the typefaces, you can also use
  16748. findAllTypefaceNames() instead.
  16749. @param results the array to which new Font objects will be added.
  16750. */
  16751. static void findFonts (Array<Font>& results) throw();
  16752. /** Returns a list of all the available typeface names.
  16753. The names returned can be passed into setTypefaceName().
  16754. You can use this instead of findFonts() if you only need their names, and not
  16755. font objects.
  16756. */
  16757. static const StringArray findAllTypefaceNames();
  16758. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  16759. in the requested typeface.
  16760. */
  16761. static const String getFallbackFontName() throw();
  16762. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  16763. available in whatever font you're trying to use.
  16764. */
  16765. static void setFallbackFontName (const String& name) throw();
  16766. /** Creates a string to describe this font.
  16767. The string will contain information to describe the font's typeface, size, and
  16768. style. To recreate the font from this string, use fromString().
  16769. */
  16770. const String toString() const;
  16771. /** Recreates a font from its stringified encoding.
  16772. This method takes a string that was created by toString(), and recreates the
  16773. original font.
  16774. */
  16775. static const Font fromString (const String& fontDescription);
  16776. juce_UseDebuggingNewOperator
  16777. private:
  16778. friend class FontGlyphAlphaMap;
  16779. friend class TypefaceCache;
  16780. class SharedFontInternal : public ReferenceCountedObject
  16781. {
  16782. public:
  16783. SharedFontInternal (const String& typefaceName, float height, float horizontalScale,
  16784. float kerning, float ascent, int styleFlags,
  16785. Typeface* typeface) throw();
  16786. SharedFontInternal (const SharedFontInternal& other) throw();
  16787. String typefaceName;
  16788. float height, horizontalScale, kerning, ascent;
  16789. int styleFlags;
  16790. Typeface::Ptr typeface;
  16791. };
  16792. ReferenceCountedObjectPtr <SharedFontInternal> font;
  16793. void dupeInternalIfShared() throw();
  16794. };
  16795. #endif // __JUCE_FONT_JUCEHEADER__
  16796. /*** End of inlined file: juce_Font.h ***/
  16797. /*** Start of inlined file: juce_PathStrokeType.h ***/
  16798. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  16799. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  16800. /**
  16801. Describes a type of stroke used to render a solid outline along a path.
  16802. A PathStrokeType object can be used directly to create the shape of an outline
  16803. around a path, and is used by Graphics::strokePath to specify the type of
  16804. stroke to draw.
  16805. @see Path, Graphics::strokePath
  16806. */
  16807. class JUCE_API PathStrokeType
  16808. {
  16809. public:
  16810. /** The type of shape to use for the corners between two adjacent line segments. */
  16811. enum JointStyle
  16812. {
  16813. mitered, /**< Indicates that corners should be drawn with sharp joints.
  16814. Note that for angles that curve back on themselves, drawing a
  16815. mitre could require extending the point too far away from the
  16816. path, so a mitre limit is imposed and any corners that exceed it
  16817. are drawn as bevelled instead. */
  16818. curved, /**< Indicates that corners should be drawn as rounded-off. */
  16819. beveled /**< Indicates that corners should be drawn with a line flattening their
  16820. outside edge. */
  16821. };
  16822. /** The type shape to use for the ends of lines. */
  16823. enum EndCapStyle
  16824. {
  16825. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  16826. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  16827. the thickness of the stroke. */
  16828. rounded /**< Ends of lines are rounded-off with a circular shape. */
  16829. };
  16830. /** Creates a stroke type.
  16831. @param strokeThickness the width of the line to use
  16832. @param jointStyle the type of joints to use for corners
  16833. @param endStyle the type of end-caps to use for the ends of open paths.
  16834. */
  16835. PathStrokeType (float strokeThickness,
  16836. JointStyle jointStyle = mitered,
  16837. EndCapStyle endStyle = butt) throw();
  16838. /** Createes a copy of another stroke type. */
  16839. PathStrokeType (const PathStrokeType& other) throw();
  16840. /** Copies another stroke onto this one. */
  16841. PathStrokeType& operator= (const PathStrokeType& other) throw();
  16842. /** Destructor. */
  16843. ~PathStrokeType() throw();
  16844. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  16845. @param destPath the resultant stroked outline shape will be copied into this path.
  16846. Note that it's ok for the source and destination Paths to be
  16847. the same object, so you can easily turn a path into a stroked version
  16848. of itself.
  16849. @param sourcePath the path to use as the source
  16850. @param transform an optional transform to apply to the points from the source path
  16851. as they are being used
  16852. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  16853. a higher resolution, which improved the quality if you'll later want
  16854. to enlarge the stroked path
  16855. @see createDashedStroke
  16856. */
  16857. void createStrokedPath (Path& destPath,
  16858. const Path& sourcePath,
  16859. const AffineTransform& transform = AffineTransform::identity,
  16860. float extraAccuracy = 1.0f) const;
  16861. /** Applies this stroke type to a path, creating a dashed line.
  16862. This is similar to createStrokedPath, but uses the array passed in to
  16863. break the stroke up into a series of dashes.
  16864. @param destPath the resultant stroked outline shape will be copied into this path.
  16865. Note that it's ok for the source and destination Paths to be
  16866. the same object, so you can easily turn a path into a stroked version
  16867. of itself.
  16868. @param sourcePath the path to use as the source
  16869. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  16870. a line of length 2, then skip a length of 3, then add a line of length 4,
  16871. skip 5, and keep repeating this pattern.
  16872. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  16873. an even number, otherwise the pattern will get out of step as it
  16874. repeats.
  16875. @param transform an optional transform to apply to the points from the source path
  16876. as they are being used
  16877. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  16878. a higher resolution, which improved the quality if you'll later want
  16879. to enlarge the stroked path
  16880. */
  16881. void createDashedStroke (Path& destPath,
  16882. const Path& sourcePath,
  16883. const float* dashLengths,
  16884. int numDashLengths,
  16885. const AffineTransform& transform = AffineTransform::identity,
  16886. float extraAccuracy = 1.0f) const;
  16887. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  16888. @param destPath the resultant stroked outline shape will be copied into this path.
  16889. Note that it's ok for the source and destination Paths to be
  16890. the same object, so you can easily turn a path into a stroked version
  16891. of itself.
  16892. @param sourcePath the path to use as the source
  16893. @param arrowheadStartWidth the width of the arrowhead at the start of the path
  16894. @param arrowheadStartLength the length of the arrowhead at the start of the path
  16895. @param arrowheadEndWidth the width of the arrowhead at the end of the path
  16896. @param arrowheadEndLength the length of the arrowhead at the end of the path
  16897. @param transform an optional transform to apply to the points from the source path
  16898. as they are being used
  16899. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  16900. a higher resolution, which improved the quality if you'll later want
  16901. to enlarge the stroked path
  16902. @see createDashedStroke
  16903. */
  16904. void createStrokeWithArrowheads (Path& destPath,
  16905. const Path& sourcePath,
  16906. float arrowheadStartWidth, float arrowheadStartLength,
  16907. float arrowheadEndWidth, float arrowheadEndLength,
  16908. const AffineTransform& transform = AffineTransform::identity,
  16909. float extraAccuracy = 1.0f) const;
  16910. /** Returns the stroke thickness. */
  16911. float getStrokeThickness() const throw() { return thickness; }
  16912. /** Sets the stroke thickness. */
  16913. void setStrokeThickness (float newThickness) throw() { thickness = newThickness; }
  16914. /** Returns the joint style. */
  16915. JointStyle getJointStyle() const throw() { return jointStyle; }
  16916. /** Sets the joint style. */
  16917. void setJointStyle (JointStyle newStyle) throw() { jointStyle = newStyle; }
  16918. /** Returns the end-cap style. */
  16919. EndCapStyle getEndStyle() const throw() { return endStyle; }
  16920. /** Sets the end-cap style. */
  16921. void setEndStyle (EndCapStyle newStyle) throw() { endStyle = newStyle; }
  16922. juce_UseDebuggingNewOperator
  16923. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  16924. bool operator== (const PathStrokeType& other) const throw();
  16925. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  16926. bool operator!= (const PathStrokeType& other) const throw();
  16927. private:
  16928. float thickness;
  16929. JointStyle jointStyle;
  16930. EndCapStyle endStyle;
  16931. };
  16932. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  16933. /*** End of inlined file: juce_PathStrokeType.h ***/
  16934. /*** Start of inlined file: juce_Colours.h ***/
  16935. #ifndef __JUCE_COLOURS_JUCEHEADER__
  16936. #define __JUCE_COLOURS_JUCEHEADER__
  16937. /*** Start of inlined file: juce_Colour.h ***/
  16938. #ifndef __JUCE_COLOUR_JUCEHEADER__
  16939. #define __JUCE_COLOUR_JUCEHEADER__
  16940. /*** Start of inlined file: juce_PixelFormats.h ***/
  16941. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  16942. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  16943. #if JUCE_MSVC
  16944. #pragma pack (push, 1)
  16945. #define PACKED
  16946. #elif JUCE_GCC
  16947. #define PACKED __attribute__((packed))
  16948. #else
  16949. #define PACKED
  16950. #endif
  16951. class PixelRGB;
  16952. class PixelAlpha;
  16953. /**
  16954. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  16955. operations with it.
  16956. This is used internally by the imaging classes.
  16957. @see PixelRGB
  16958. */
  16959. class JUCE_API PixelARGB
  16960. {
  16961. public:
  16962. /** Creates a pixel without defining its colour. */
  16963. PixelARGB() throw() {}
  16964. ~PixelARGB() throw() {}
  16965. /** Creates a pixel from a 32-bit argb value.
  16966. */
  16967. PixelARGB (const uint32 argb_) throw()
  16968. : argb (argb_)
  16969. {
  16970. }
  16971. forcedinline uint32 getARGB() const throw() { return argb; }
  16972. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  16973. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  16974. forcedinline uint8 getAlpha() const throw() { return components.a; }
  16975. forcedinline uint8 getRed() const throw() { return components.r; }
  16976. forcedinline uint8 getGreen() const throw() { return components.g; }
  16977. forcedinline uint8 getBlue() const throw() { return components.b; }
  16978. /** Blends another pixel onto this one.
  16979. This takes into account the opacity of the pixel being overlaid, and blends
  16980. it accordingly.
  16981. */
  16982. forcedinline void blend (const PixelARGB& src) throw()
  16983. {
  16984. uint32 sargb = src.getARGB();
  16985. const uint32 alpha = 0x100 - (sargb >> 24);
  16986. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  16987. sargb += 0xff00ff00 & (getAG() * alpha);
  16988. argb = sargb;
  16989. }
  16990. /** Blends another pixel onto this one.
  16991. This takes into account the opacity of the pixel being overlaid, and blends
  16992. it accordingly.
  16993. */
  16994. forcedinline void blend (const PixelAlpha& src) throw();
  16995. /** Blends another pixel onto this one.
  16996. This takes into account the opacity of the pixel being overlaid, and blends
  16997. it accordingly.
  16998. */
  16999. forcedinline void blend (const PixelRGB& src) throw();
  17000. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  17001. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  17002. being used, so this can blend semi-transparently from a PixelRGB argument.
  17003. */
  17004. template <class Pixel>
  17005. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  17006. {
  17007. ++extraAlpha;
  17008. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  17009. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  17010. const uint32 alpha = 0x100 - (sargb >> 24);
  17011. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17012. sargb += 0xff00ff00 & (getAG() * alpha);
  17013. argb = sargb;
  17014. }
  17015. /** Blends another pixel with this one, creating a colour that is somewhere
  17016. between the two, as specified by the amount.
  17017. */
  17018. template <class Pixel>
  17019. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  17020. {
  17021. uint32 drb = getRB();
  17022. drb += (((src.getRB() - drb) * amount) >> 8);
  17023. drb &= 0x00ff00ff;
  17024. uint32 dag = getAG();
  17025. dag += (((src.getAG() - dag) * amount) >> 8);
  17026. dag &= 0x00ff00ff;
  17027. dag <<= 8;
  17028. dag |= drb;
  17029. argb = dag;
  17030. }
  17031. /** Copies another pixel colour over this one.
  17032. This doesn't blend it - this colour is simply replaced by the other one.
  17033. */
  17034. template <class Pixel>
  17035. forcedinline void set (const Pixel& src) throw()
  17036. {
  17037. argb = src.getARGB();
  17038. }
  17039. /** Replaces the colour's alpha value with another one. */
  17040. forcedinline void setAlpha (const uint8 newAlpha) throw()
  17041. {
  17042. components.a = newAlpha;
  17043. }
  17044. /** Multiplies the colour's alpha value with another one. */
  17045. forcedinline void multiplyAlpha (int multiplier) throw()
  17046. {
  17047. ++multiplier;
  17048. argb = ((multiplier * getAG()) & 0xff00ff00)
  17049. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  17050. }
  17051. forcedinline void multiplyAlpha (const float multiplier) throw()
  17052. {
  17053. multiplyAlpha ((int) (multiplier * 256.0f));
  17054. }
  17055. /** Sets the pixel's colour from individual components. */
  17056. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  17057. {
  17058. components.b = b;
  17059. components.g = g;
  17060. components.r = r;
  17061. components.a = a;
  17062. }
  17063. /** Premultiplies the pixel's RGB values by its alpha. */
  17064. forcedinline void premultiply() throw()
  17065. {
  17066. const uint32 alpha = components.a;
  17067. if (alpha < 0xff)
  17068. {
  17069. if (alpha == 0)
  17070. {
  17071. components.b = 0;
  17072. components.g = 0;
  17073. components.r = 0;
  17074. }
  17075. else
  17076. {
  17077. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  17078. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  17079. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  17080. }
  17081. }
  17082. }
  17083. /** Unpremultiplies the pixel's RGB values. */
  17084. forcedinline void unpremultiply() throw()
  17085. {
  17086. const uint32 alpha = components.a;
  17087. if (alpha < 0xff)
  17088. {
  17089. if (alpha == 0)
  17090. {
  17091. components.b = 0;
  17092. components.g = 0;
  17093. components.r = 0;
  17094. }
  17095. else
  17096. {
  17097. components.b = (uint8) jmin ((uint32) 0xff, (components.b * 0xff) / alpha);
  17098. components.g = (uint8) jmin ((uint32) 0xff, (components.g * 0xff) / alpha);
  17099. components.r = (uint8) jmin ((uint32) 0xff, (components.r * 0xff) / alpha);
  17100. }
  17101. }
  17102. }
  17103. forcedinline void desaturate() throw()
  17104. {
  17105. if (components.a < 0xff && components.a > 0)
  17106. {
  17107. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  17108. components.r = components.g = components.b
  17109. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  17110. }
  17111. else
  17112. {
  17113. components.r = components.g = components.b
  17114. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  17115. }
  17116. }
  17117. /** The indexes of the different components in the byte layout of this type of colour. */
  17118. #if JUCE_BIG_ENDIAN
  17119. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  17120. #else
  17121. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  17122. #endif
  17123. private:
  17124. union
  17125. {
  17126. uint32 argb;
  17127. struct
  17128. {
  17129. #if JUCE_BIG_ENDIAN
  17130. uint8 a : 8, r : 8, g : 8, b : 8;
  17131. #else
  17132. uint8 b, g, r, a;
  17133. #endif
  17134. } PACKED components;
  17135. };
  17136. } PACKED;
  17137. /**
  17138. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  17139. This is used internally by the imaging classes.
  17140. @see PixelARGB
  17141. */
  17142. class JUCE_API PixelRGB
  17143. {
  17144. public:
  17145. /** Creates a pixel without defining its colour. */
  17146. PixelRGB() throw() {}
  17147. ~PixelRGB() throw() {}
  17148. /** Creates a pixel from a 32-bit argb value.
  17149. (The argb format is that used by PixelARGB)
  17150. */
  17151. PixelRGB (const uint32 argb) throw()
  17152. {
  17153. r = (uint8) (argb >> 16);
  17154. g = (uint8) (argb >> 8);
  17155. b = (uint8) (argb);
  17156. }
  17157. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  17158. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  17159. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  17160. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  17161. forcedinline uint8 getRed() const throw() { return r; }
  17162. forcedinline uint8 getGreen() const throw() { return g; }
  17163. forcedinline uint8 getBlue() const throw() { return b; }
  17164. /** Blends another pixel onto this one.
  17165. This takes into account the opacity of the pixel being overlaid, and blends
  17166. it accordingly.
  17167. */
  17168. forcedinline void blend (const PixelARGB& src) throw()
  17169. {
  17170. uint32 sargb = src.getARGB();
  17171. const uint32 alpha = 0x100 - (sargb >> 24);
  17172. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17173. sargb += 0x0000ff00 & (g * alpha);
  17174. r = (uint8) (sargb >> 16);
  17175. g = (uint8) (sargb >> 8);
  17176. b = (uint8) sargb;
  17177. }
  17178. forcedinline void blend (const PixelRGB& src) throw()
  17179. {
  17180. set (src);
  17181. }
  17182. forcedinline void blend (const PixelAlpha& src) throw();
  17183. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  17184. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  17185. being used, so this can blend semi-transparently from a PixelRGB argument.
  17186. */
  17187. template <class Pixel>
  17188. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  17189. {
  17190. ++extraAlpha;
  17191. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  17192. const uint32 sag = extraAlpha * src.getAG();
  17193. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  17194. const uint32 alpha = 0x100 - (sargb >> 24);
  17195. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17196. sargb += 0x0000ff00 & (g * alpha);
  17197. b = (uint8) sargb;
  17198. g = (uint8) (sargb >> 8);
  17199. r = (uint8) (sargb >> 16);
  17200. }
  17201. /** Blends another pixel with this one, creating a colour that is somewhere
  17202. between the two, as specified by the amount.
  17203. */
  17204. template <class Pixel>
  17205. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  17206. {
  17207. uint32 drb = getRB();
  17208. drb += (((src.getRB() - drb) * amount) >> 8);
  17209. uint32 dag = getAG();
  17210. dag += (((src.getAG() - dag) * amount) >> 8);
  17211. b = (uint8) drb;
  17212. g = (uint8) dag;
  17213. r = (uint8) (drb >> 16);
  17214. }
  17215. /** Copies another pixel colour over this one.
  17216. This doesn't blend it - this colour is simply replaced by the other one.
  17217. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  17218. is thrown away.
  17219. */
  17220. template <class Pixel>
  17221. forcedinline void set (const Pixel& src) throw()
  17222. {
  17223. b = src.getBlue();
  17224. g = src.getGreen();
  17225. r = src.getRed();
  17226. }
  17227. /** This method is included for compatibility with the PixelARGB class. */
  17228. forcedinline void setAlpha (const uint8) throw() {}
  17229. /** Multiplies the colour's alpha value with another one. */
  17230. forcedinline void multiplyAlpha (int) throw() {}
  17231. /** Sets the pixel's colour from individual components. */
  17232. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  17233. {
  17234. r = r_;
  17235. g = g_;
  17236. b = b_;
  17237. }
  17238. /** Premultiplies the pixel's RGB values by its alpha. */
  17239. forcedinline void premultiply() throw() {}
  17240. /** Unpremultiplies the pixel's RGB values. */
  17241. forcedinline void unpremultiply() throw() {}
  17242. forcedinline void desaturate() throw()
  17243. {
  17244. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  17245. }
  17246. /** The indexes of the different components in the byte layout of this type of colour. */
  17247. #if JUCE_MAC
  17248. enum { indexR = 0, indexG = 1, indexB = 2 };
  17249. #else
  17250. enum { indexR = 2, indexG = 1, indexB = 0 };
  17251. #endif
  17252. private:
  17253. #if JUCE_MAC
  17254. uint8 r, g, b;
  17255. #else
  17256. uint8 b, g, r;
  17257. #endif
  17258. } PACKED;
  17259. forcedinline void PixelARGB::blend (const PixelRGB& src) throw()
  17260. {
  17261. set (src);
  17262. }
  17263. /**
  17264. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  17265. This is used internally by the imaging classes.
  17266. @see PixelARGB, PixelRGB
  17267. */
  17268. class JUCE_API PixelAlpha
  17269. {
  17270. public:
  17271. /** Creates a pixel without defining its colour. */
  17272. PixelAlpha() throw() {}
  17273. ~PixelAlpha() throw() {}
  17274. /** Creates a pixel from a 32-bit argb value.
  17275. (The argb format is that used by PixelARGB)
  17276. */
  17277. PixelAlpha (const uint32 argb) throw()
  17278. {
  17279. a = (uint8) (argb >> 24);
  17280. }
  17281. forcedinline uint32 getARGB() const throw() { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  17282. forcedinline uint32 getRB() const throw() { return (((uint32) a) << 16) | a; }
  17283. forcedinline uint32 getAG() const throw() { return (((uint32) a) << 16) | a; }
  17284. forcedinline uint8 getAlpha() const throw() { return a; }
  17285. forcedinline uint8 getRed() const throw() { return 0; }
  17286. forcedinline uint8 getGreen() const throw() { return 0; }
  17287. forcedinline uint8 getBlue() const throw() { return 0; }
  17288. /** Blends another pixel onto this one.
  17289. This takes into account the opacity of the pixel being overlaid, and blends
  17290. it accordingly.
  17291. */
  17292. template <class Pixel>
  17293. forcedinline void blend (const Pixel& src) throw()
  17294. {
  17295. const int srcA = src.getAlpha();
  17296. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  17297. }
  17298. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  17299. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  17300. being used, so this can blend semi-transparently from a PixelRGB argument.
  17301. */
  17302. template <class Pixel>
  17303. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  17304. {
  17305. ++extraAlpha;
  17306. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  17307. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  17308. }
  17309. /** Blends another pixel with this one, creating a colour that is somewhere
  17310. between the two, as specified by the amount.
  17311. */
  17312. template <class Pixel>
  17313. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  17314. {
  17315. a += ((src,getAlpha() - a) * amount) >> 8;
  17316. }
  17317. /** Copies another pixel colour over this one.
  17318. This doesn't blend it - this colour is simply replaced by the other one.
  17319. */
  17320. template <class Pixel>
  17321. forcedinline void set (const Pixel& src) throw()
  17322. {
  17323. a = src.getAlpha();
  17324. }
  17325. /** Replaces the colour's alpha value with another one. */
  17326. forcedinline void setAlpha (const uint8 newAlpha) throw()
  17327. {
  17328. a = newAlpha;
  17329. }
  17330. /** Multiplies the colour's alpha value with another one. */
  17331. forcedinline void multiplyAlpha (int multiplier) throw()
  17332. {
  17333. ++multiplier;
  17334. a = (uint8) ((a * multiplier) >> 8);
  17335. }
  17336. forcedinline void multiplyAlpha (const float multiplier) throw()
  17337. {
  17338. a = (uint8) (a * multiplier);
  17339. }
  17340. /** Sets the pixel's colour from individual components. */
  17341. forcedinline void setARGB (const uint8 a_, const uint8 /*r*/, const uint8 /*g*/, const uint8 /*b*/) throw()
  17342. {
  17343. a = a_;
  17344. }
  17345. /** Premultiplies the pixel's RGB values by its alpha. */
  17346. forcedinline void premultiply() throw()
  17347. {
  17348. }
  17349. /** Unpremultiplies the pixel's RGB values. */
  17350. forcedinline void unpremultiply() throw()
  17351. {
  17352. }
  17353. forcedinline void desaturate() throw()
  17354. {
  17355. }
  17356. /** The indexes of the different components in the byte layout of this type of colour. */
  17357. enum { indexA = 0 };
  17358. private:
  17359. uint8 a : 8;
  17360. } PACKED;
  17361. forcedinline void PixelRGB::blend (const PixelAlpha& src) throw()
  17362. {
  17363. blend (PixelARGB (src.getARGB()));
  17364. }
  17365. forcedinline void PixelARGB::blend (const PixelAlpha& src) throw()
  17366. {
  17367. uint32 sargb = src.getARGB();
  17368. const uint32 alpha = 0x100 - (sargb >> 24);
  17369. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17370. sargb += 0xff00ff00 & (getAG() * alpha);
  17371. argb = sargb;
  17372. }
  17373. #if JUCE_MSVC
  17374. #pragma pack (pop)
  17375. #endif
  17376. #undef PACKED
  17377. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  17378. /*** End of inlined file: juce_PixelFormats.h ***/
  17379. /**
  17380. Represents a colour, also including a transparency value.
  17381. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  17382. */
  17383. class JUCE_API Colour
  17384. {
  17385. public:
  17386. /** Creates a transparent black colour. */
  17387. Colour() throw();
  17388. /** Creates a copy of another Colour object. */
  17389. Colour (const Colour& other) throw();
  17390. /** Creates a colour from a 32-bit ARGB value.
  17391. The format of this number is:
  17392. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  17393. All components in the range 0x00 to 0xff.
  17394. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  17395. @see getPixelARGB
  17396. */
  17397. explicit Colour (uint32 argb) throw();
  17398. /** Creates an opaque colour using 8-bit red, green and blue values */
  17399. Colour (uint8 red,
  17400. uint8 green,
  17401. uint8 blue) throw();
  17402. /** Creates an opaque colour using 8-bit red, green and blue values */
  17403. static const Colour fromRGB (uint8 red,
  17404. uint8 green,
  17405. uint8 blue) throw();
  17406. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  17407. Colour (uint8 red,
  17408. uint8 green,
  17409. uint8 blue,
  17410. uint8 alpha) throw();
  17411. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  17412. static const Colour fromRGBA (uint8 red,
  17413. uint8 green,
  17414. uint8 blue,
  17415. uint8 alpha) throw();
  17416. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  17417. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  17418. Values outside the valid range will be clipped.
  17419. */
  17420. Colour (uint8 red,
  17421. uint8 green,
  17422. uint8 blue,
  17423. float alpha) throw();
  17424. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  17425. static const Colour fromRGBAFloat (uint8 red,
  17426. uint8 green,
  17427. uint8 blue,
  17428. float alpha) throw();
  17429. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  17430. The floating point values must be between 0.0 and 1.0.
  17431. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  17432. Values outside the valid range will be clipped.
  17433. */
  17434. Colour (float hue,
  17435. float saturation,
  17436. float brightness,
  17437. uint8 alpha) throw();
  17438. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  17439. All values must be between 0.0 and 1.0.
  17440. Numbers outside the valid range will be clipped.
  17441. */
  17442. Colour (float hue,
  17443. float saturation,
  17444. float brightness,
  17445. float alpha) throw();
  17446. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  17447. The floating point values must be between 0.0 and 1.0.
  17448. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  17449. Values outside the valid range will be clipped.
  17450. */
  17451. static const Colour fromHSV (float hue,
  17452. float saturation,
  17453. float brightness,
  17454. float alpha) throw();
  17455. /** Destructor. */
  17456. ~Colour() throw();
  17457. /** Copies another Colour object. */
  17458. Colour& operator= (const Colour& other) throw();
  17459. /** Compares two colours. */
  17460. bool operator== (const Colour& other) const throw();
  17461. /** Compares two colours. */
  17462. bool operator!= (const Colour& other) const throw();
  17463. /** Returns the red component of this colour.
  17464. @returns a value between 0x00 and 0xff.
  17465. */
  17466. uint8 getRed() const throw() { return argb.getRed(); }
  17467. /** Returns the green component of this colour.
  17468. @returns a value between 0x00 and 0xff.
  17469. */
  17470. uint8 getGreen() const throw() { return argb.getGreen(); }
  17471. /** Returns the blue component of this colour.
  17472. @returns a value between 0x00 and 0xff.
  17473. */
  17474. uint8 getBlue() const throw() { return argb.getBlue(); }
  17475. /** Returns the red component of this colour as a floating point value.
  17476. @returns a value between 0.0 and 1.0
  17477. */
  17478. float getFloatRed() const throw();
  17479. /** Returns the green component of this colour as a floating point value.
  17480. @returns a value between 0.0 and 1.0
  17481. */
  17482. float getFloatGreen() const throw();
  17483. /** Returns the blue component of this colour as a floating point value.
  17484. @returns a value between 0.0 and 1.0
  17485. */
  17486. float getFloatBlue() const throw();
  17487. /** Returns a premultiplied ARGB pixel object that represents this colour.
  17488. */
  17489. const PixelARGB getPixelARGB() const throw();
  17490. /** Returns a 32-bit integer that represents this colour.
  17491. The format of this number is:
  17492. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  17493. */
  17494. uint32 getARGB() const throw();
  17495. /** Returns the colour's alpha (opacity).
  17496. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  17497. */
  17498. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  17499. /** Returns the colour's alpha (opacity) as a floating point value.
  17500. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  17501. */
  17502. float getFloatAlpha() const throw();
  17503. /** Returns true if this colour is completely opaque.
  17504. Equivalent to (getAlpha() == 0xff).
  17505. */
  17506. bool isOpaque() const throw();
  17507. /** Returns true if this colour is completely transparent.
  17508. Equivalent to (getAlpha() == 0x00).
  17509. */
  17510. bool isTransparent() const throw();
  17511. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  17512. const Colour withAlpha (uint8 newAlpha) const throw();
  17513. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  17514. const Colour withAlpha (float newAlpha) const throw();
  17515. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  17516. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  17517. */
  17518. const Colour withMultipliedAlpha (float alphaMultiplier) const throw();
  17519. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  17520. If the foreground colour is semi-transparent, it is blended onto this colour
  17521. accordingly.
  17522. */
  17523. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  17524. /** Returns a colour that lies somewhere between this one and another.
  17525. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  17526. is 1.0, the result is 100% of the other colour.
  17527. */
  17528. const Colour interpolatedWith (const Colour& other, float proportionOfOther) const throw();
  17529. /** Returns the colour's hue component.
  17530. The value returned is in the range 0.0 to 1.0
  17531. */
  17532. float getHue() const throw();
  17533. /** Returns the colour's saturation component.
  17534. The value returned is in the range 0.0 to 1.0
  17535. */
  17536. float getSaturation() const throw();
  17537. /** Returns the colour's brightness component.
  17538. The value returned is in the range 0.0 to 1.0
  17539. */
  17540. float getBrightness() const throw();
  17541. /** Returns the colour's hue, saturation and brightness components all at once.
  17542. The values returned are in the range 0.0 to 1.0
  17543. */
  17544. void getHSB (float& hue,
  17545. float& saturation,
  17546. float& brightness) const throw();
  17547. /** Returns a copy of this colour with a different hue. */
  17548. const Colour withHue (float newHue) const throw();
  17549. /** Returns a copy of this colour with a different saturation. */
  17550. const Colour withSaturation (float newSaturation) const throw();
  17551. /** Returns a copy of this colour with a different brightness.
  17552. @see brighter, darker, withMultipliedBrightness
  17553. */
  17554. const Colour withBrightness (float newBrightness) const throw();
  17555. /** Returns a copy of this colour with it hue rotated.
  17556. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  17557. @see brighter, darker, withMultipliedBrightness
  17558. */
  17559. const Colour withRotatedHue (float amountToRotate) const throw();
  17560. /** Returns a copy of this colour with its saturation multiplied by the given value.
  17561. The new colour's saturation is (this->getSaturation() * multiplier)
  17562. (the result is clipped to legal limits).
  17563. */
  17564. const Colour withMultipliedSaturation (float multiplier) const throw();
  17565. /** Returns a copy of this colour with its brightness multiplied by the given value.
  17566. The new colour's saturation is (this->getBrightness() * multiplier)
  17567. (the result is clipped to legal limits).
  17568. */
  17569. const Colour withMultipliedBrightness (float amount) const throw();
  17570. /** Returns a brighter version of this colour.
  17571. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  17572. unchanged, and higher values make it brighter
  17573. @see withMultipliedBrightness
  17574. */
  17575. const Colour brighter (float amountBrighter = 0.4f) const throw();
  17576. /** Returns a darker version of this colour.
  17577. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  17578. unchanged, and higher values make it darker
  17579. @see withMultipliedBrightness
  17580. */
  17581. const Colour darker (float amountDarker = 0.4f) const throw();
  17582. /** Returns a colour that will be clearly visible against this colour.
  17583. The amount parameter indicates how contrasting the new colour should
  17584. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  17585. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  17586. return white; Colours::white.contrasting (1.0f) will return black, etc.
  17587. */
  17588. const Colour contrasting (float amount = 1.0f) const throw();
  17589. /** Returns a colour that contrasts against two colours.
  17590. Looks for a colour that contrasts with both of the colours passed-in.
  17591. Handy for things like choosing a highlight colour in text editors, etc.
  17592. */
  17593. static const Colour contrasting (const Colour& colour1,
  17594. const Colour& colour2) throw();
  17595. /** Returns an opaque shade of grey.
  17596. @param brightness the level of grey to return - 0 is black, 1.0 is white
  17597. */
  17598. static const Colour greyLevel (float brightness) throw();
  17599. /** Returns a stringified version of this colour.
  17600. The string can be turned back into a colour using the fromString() method.
  17601. */
  17602. const String toString() const;
  17603. /** Reads the colour from a string that was created with toString().
  17604. */
  17605. static const Colour fromString (const String& encodedColourString);
  17606. /** Returns the colour as a hex string in the form RRGGBB or AARRGGBB. */
  17607. const String toDisplayString (bool includeAlphaValue) const;
  17608. juce_UseDebuggingNewOperator
  17609. private:
  17610. PixelARGB argb;
  17611. };
  17612. #endif // __JUCE_COLOUR_JUCEHEADER__
  17613. /*** End of inlined file: juce_Colour.h ***/
  17614. /**
  17615. Contains a set of predefined named colours (mostly standard HTML colours)
  17616. @see Colour, Colours::greyLevel
  17617. */
  17618. class Colours
  17619. {
  17620. public:
  17621. static JUCE_API const Colour
  17622. transparentBlack, /**< ARGB = 0x00000000 */
  17623. transparentWhite, /**< ARGB = 0x00ffffff */
  17624. black, /**< ARGB = 0xff000000 */
  17625. white, /**< ARGB = 0xffffffff */
  17626. blue, /**< ARGB = 0xff0000ff */
  17627. grey, /**< ARGB = 0xff808080 */
  17628. green, /**< ARGB = 0xff008000 */
  17629. red, /**< ARGB = 0xffff0000 */
  17630. yellow, /**< ARGB = 0xffffff00 */
  17631. aliceblue, antiquewhite, aqua, aquamarine,
  17632. azure, beige, bisque, blanchedalmond,
  17633. blueviolet, brown, burlywood, cadetblue,
  17634. chartreuse, chocolate, coral, cornflowerblue,
  17635. cornsilk, crimson, cyan, darkblue,
  17636. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  17637. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  17638. darkorchid, darkred, darksalmon, darkseagreen,
  17639. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  17640. deeppink, deepskyblue, dimgrey, dodgerblue,
  17641. firebrick, floralwhite, forestgreen, fuchsia,
  17642. gainsboro, gold, goldenrod, greenyellow,
  17643. honeydew, hotpink, indianred, indigo,
  17644. ivory, khaki, lavender, lavenderblush,
  17645. lemonchiffon, lightblue, lightcoral, lightcyan,
  17646. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  17647. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  17648. lightsteelblue, lightyellow, lime, limegreen,
  17649. linen, magenta, maroon, mediumaquamarine,
  17650. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  17651. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  17652. midnightblue, mintcream, mistyrose, navajowhite,
  17653. navy, oldlace, olive, olivedrab,
  17654. orange, orangered, orchid, palegoldenrod,
  17655. palegreen, paleturquoise, palevioletred, papayawhip,
  17656. peachpuff, peru, pink, plum,
  17657. powderblue, purple, rosybrown, royalblue,
  17658. saddlebrown, salmon, sandybrown, seagreen,
  17659. seashell, sienna, silver, skyblue,
  17660. slateblue, slategrey, snow, springgreen,
  17661. steelblue, tan, teal, thistle,
  17662. tomato, turquoise, violet, wheat,
  17663. whitesmoke, yellowgreen;
  17664. /** Attempts to look up a string in the list of known colour names, and return
  17665. the appropriate colour.
  17666. A non-case-sensitive search is made of the list of predefined colours, and
  17667. if a match is found, that colour is returned. If no match is found, the
  17668. colour passed in as the defaultColour parameter is returned.
  17669. */
  17670. static JUCE_API const Colour findColourForName (const String& colourName,
  17671. const Colour& defaultColour);
  17672. private:
  17673. // this isn't a class you should ever instantiate - it's just here for the
  17674. // static values in it.
  17675. Colours();
  17676. Colours (const Colours&);
  17677. Colours& operator= (const Colours&);
  17678. };
  17679. #endif // __JUCE_COLOURS_JUCEHEADER__
  17680. /*** End of inlined file: juce_Colours.h ***/
  17681. /*** Start of inlined file: juce_ColourGradient.h ***/
  17682. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  17683. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  17684. /**
  17685. Describes the layout and colours that should be used to paint a colour gradient.
  17686. @see Graphics::setGradientFill
  17687. */
  17688. class JUCE_API ColourGradient
  17689. {
  17690. public:
  17691. /** Creates a gradient object.
  17692. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  17693. colour2 should be. In between them there's a gradient.
  17694. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  17695. its centre.
  17696. The alpha transparencies of the colours are used, so note that
  17697. if you blend from transparent to a solid colour, the RGB of the transparent
  17698. colour will become visible in parts of the gradient. e.g. blending
  17699. from Colour::transparentBlack to Colours::white will produce a
  17700. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  17701. will be white all the way across.
  17702. @see ColourGradient
  17703. */
  17704. ColourGradient (const Colour& colour1, float x1, float y1,
  17705. const Colour& colour2, float x2, float y2,
  17706. bool isRadial);
  17707. /** Creates an uninitialised gradient.
  17708. If you use this constructor instead of the other one, be sure to set all the
  17709. object's public member variables before using it!
  17710. */
  17711. ColourGradient() throw();
  17712. /** Destructor */
  17713. ~ColourGradient();
  17714. /** Removes any colours that have been added.
  17715. This will also remove any start and end colours, so the gradient won't work. You'll
  17716. need to add more colours with addColour().
  17717. */
  17718. void clearColours();
  17719. /** Adds a colour at a point along the length of the gradient.
  17720. This allows the gradient to go through a spectrum of colours, instead of just a
  17721. start and end colour.
  17722. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  17723. of the distance along the line between the two points
  17724. at which the colour should occur.
  17725. @param colour the colour that should be used at this point
  17726. @returns the index at which the new point was added
  17727. */
  17728. int addColour (double proportionAlongGradient,
  17729. const Colour& colour);
  17730. /** Removes one of the colours from the gradient. */
  17731. void removeColour (int index);
  17732. /** Multiplies the alpha value of all the colours by the given scale factor */
  17733. void multiplyOpacity (float multiplier) throw();
  17734. /** Returns the number of colour-stops that have been added. */
  17735. int getNumColours() const throw();
  17736. /** Returns the position along the length of the gradient of the colour with this index.
  17737. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  17738. */
  17739. double getColourPosition (int index) const throw();
  17740. /** Returns the colour that was added with a given index.
  17741. The index is from 0 to getNumColours() - 1.
  17742. */
  17743. const Colour getColour (int index) const throw();
  17744. /** Changes the colour at a given index.
  17745. The index is from 0 to getNumColours() - 1.
  17746. */
  17747. void setColour (int index, const Colour& newColour) throw();
  17748. /** Returns the an interpolated colour at any position along the gradient.
  17749. @param position the position along the gradient, between 0 and 1
  17750. */
  17751. const Colour getColourAtPosition (double position) const throw();
  17752. /** Creates a set of interpolated premultiplied ARGB values.
  17753. This will resize the HeapBlock, fill it with the colours, and will return the number of
  17754. colours that it added.
  17755. */
  17756. int createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& resultLookupTable) const;
  17757. /** Returns true if all colours are opaque. */
  17758. bool isOpaque() const throw();
  17759. /** Returns true if all colours are completely transparent. */
  17760. bool isInvisible() const throw();
  17761. Point<float> point1, point2;
  17762. /** If true, the gradient should be filled circularly, centred around
  17763. point1, with point2 defining a point on the circumference.
  17764. If false, the gradient is linear between the two points.
  17765. */
  17766. bool isRadial;
  17767. bool operator== (const ColourGradient& other) const throw();
  17768. bool operator!= (const ColourGradient& other) const throw();
  17769. juce_UseDebuggingNewOperator
  17770. private:
  17771. struct ColourPoint
  17772. {
  17773. ColourPoint() throw() {}
  17774. ColourPoint (const double position_, const Colour& colour_) throw()
  17775. : position (position_), colour (colour_)
  17776. {}
  17777. bool operator== (const ColourPoint& other) const throw() { return position == other.position && colour == other.colour; }
  17778. bool operator!= (const ColourPoint& other) const throw() { return position != other.position || colour != other.colour; }
  17779. double position;
  17780. Colour colour;
  17781. };
  17782. Array <ColourPoint> colours;
  17783. };
  17784. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  17785. /*** End of inlined file: juce_ColourGradient.h ***/
  17786. /*** Start of inlined file: juce_RectanglePlacement.h ***/
  17787. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  17788. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  17789. /**
  17790. Defines the method used to postion some kind of rectangular object within
  17791. a rectangular viewport.
  17792. Although similar to Justification, this is more specific, and has some extra
  17793. options.
  17794. */
  17795. class JUCE_API RectanglePlacement
  17796. {
  17797. public:
  17798. /** Creates a RectanglePlacement object using a combination of flags. */
  17799. inline RectanglePlacement (int flags_) throw() : flags (flags_) {}
  17800. /** Creates a copy of another RectanglePlacement object. */
  17801. RectanglePlacement (const RectanglePlacement& other) throw();
  17802. /** Copies another RectanglePlacement object. */
  17803. RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  17804. /** Flag values that can be combined and used in the constructor. */
  17805. enum
  17806. {
  17807. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  17808. xLeft = 1,
  17809. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  17810. xRight = 2,
  17811. /** Indicates that the source should be placed in the centre between the left and right
  17812. sides of the available space. */
  17813. xMid = 4,
  17814. /** Indicates that the source's top edge should be aligned with the top edge of the
  17815. destination rectangle. */
  17816. yTop = 8,
  17817. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  17818. destination rectangle. */
  17819. yBottom = 16,
  17820. /** Indicates that the source should be placed in the centre between the top and bottom
  17821. sides of the available space. */
  17822. yMid = 32,
  17823. /** If this flag is set, then the source rectangle will be resized to completely fill
  17824. the destination rectangle, and all other flags are ignored.
  17825. */
  17826. stretchToFit = 64,
  17827. /** If this flag is set, then the source rectangle will be resized so that it is the
  17828. minimum size to completely fill the destination rectangle, without changing its
  17829. aspect ratio. This means that some of the source rectangle may fall outside
  17830. the destination.
  17831. If this flag is not set, the source will be given the maximum size at which none
  17832. of it falls outside the destination rectangle.
  17833. */
  17834. fillDestination = 128,
  17835. /** Indicates that the source rectangle can be reduced in size if required, but should
  17836. never be made larger than its original size.
  17837. */
  17838. onlyReduceInSize = 256,
  17839. /** Indicates that the source rectangle can be enlarged if required, but should
  17840. never be made smaller than its original size.
  17841. */
  17842. onlyIncreaseInSize = 512,
  17843. /** Indicates that the source rectangle's size should be left unchanged.
  17844. */
  17845. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  17846. /** A shorthand value that is equivalent to (xMid | yMid). */
  17847. centred = 4 + 32
  17848. };
  17849. /** Returns the raw flags that are set for this object. */
  17850. inline int getFlags() const throw() { return flags; }
  17851. /** Tests a set of flags for this object.
  17852. @returns true if any of the flags passed in are set on this object.
  17853. */
  17854. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  17855. /** Adjusts the position and size of a rectangle to fit it into a space.
  17856. The source rectangle co-ordinates will be adjusted so that they fit into
  17857. the destination rectangle based on this object's flags.
  17858. */
  17859. void applyTo (double& sourceX,
  17860. double& sourceY,
  17861. double& sourceW,
  17862. double& sourceH,
  17863. double destinationX,
  17864. double destinationY,
  17865. double destinationW,
  17866. double destinationH) const throw();
  17867. /** Returns the transform that should be applied to these source co-ordinates to fit them
  17868. into the destination rectangle using the current flags.
  17869. */
  17870. const AffineTransform getTransformToFit (float sourceX,
  17871. float sourceY,
  17872. float sourceW,
  17873. float sourceH,
  17874. float destinationX,
  17875. float destinationY,
  17876. float destinationW,
  17877. float destinationH) const throw();
  17878. private:
  17879. int flags;
  17880. };
  17881. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  17882. /*** End of inlined file: juce_RectanglePlacement.h ***/
  17883. class LowLevelGraphicsContext;
  17884. class Image;
  17885. class FillType;
  17886. class RectangleList;
  17887. /**
  17888. A graphics context, used for drawing a component or image.
  17889. When a Component needs painting, a Graphics context is passed to its
  17890. Component::paint() method, and this you then call methods within this
  17891. object to actually draw the component's content.
  17892. A Graphics can also be created from an image, to allow drawing directly onto
  17893. that image.
  17894. @see Component::paint
  17895. */
  17896. class JUCE_API Graphics
  17897. {
  17898. public:
  17899. /** Creates a Graphics object to draw directly onto the given image.
  17900. The graphics object that is created will be set up to draw onto the image,
  17901. with the context's clipping area being the entire size of the image, and its
  17902. origin being the image's origin. To draw into a subsection of an image, use the
  17903. reduceClipRegion() and setOrigin() methods.
  17904. Obviously you shouldn't delete the image before this context is deleted.
  17905. */
  17906. explicit Graphics (const Image& imageToDrawOnto);
  17907. /** Destructor. */
  17908. ~Graphics();
  17909. /** Changes the current drawing colour.
  17910. This sets the colour that will now be used for drawing operations - it also
  17911. sets the opacity to that of the colour passed-in.
  17912. If a brush is being used when this method is called, the brush will be deselected,
  17913. and any subsequent drawing will be done with a solid colour brush instead.
  17914. @see setOpacity
  17915. */
  17916. void setColour (const Colour& newColour);
  17917. /** Changes the opacity to use with the current colour.
  17918. If a solid colour is being used for drawing, this changes its opacity
  17919. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  17920. If a gradient is being used, this will have no effect on it.
  17921. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  17922. */
  17923. void setOpacity (const float newOpacity);
  17924. /** Sets the context to use a gradient for its fill pattern.
  17925. */
  17926. void setGradientFill (const ColourGradient& gradient);
  17927. /** Sets the context to use a tiled image pattern for filling.
  17928. Make sure that you don't delete this image while it's still being used by
  17929. this context!
  17930. */
  17931. void setTiledImageFill (const Image& imageToUse,
  17932. int anchorX, int anchorY,
  17933. float opacity);
  17934. /** Changes the current fill settings.
  17935. @see setColour, setGradientFill, setTiledImageFill
  17936. */
  17937. void setFillType (const FillType& newFill);
  17938. /** Changes the font to use for subsequent text-drawing functions.
  17939. Note there's also a setFont (float, int) method to quickly change the size and
  17940. style of the current font.
  17941. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  17942. */
  17943. void setFont (const Font& newFont);
  17944. /** Changes the size and style of the currently-selected font.
  17945. This is a convenient shortcut that changes the context's current font to a
  17946. different size or style. The typeface won't be changed.
  17947. @see Font
  17948. */
  17949. void setFont (float newFontHeight, int fontStyleFlags = Font::plain);
  17950. /** Returns the currently selected font. */
  17951. const Font getCurrentFont() const;
  17952. /** Draws a one-line text string.
  17953. This will use the current colour (or brush) to fill the text. The font is the last
  17954. one specified by setFont().
  17955. @param text the string to draw
  17956. @param startX the position to draw the left-hand edge of the text
  17957. @param baselineY the position of the text's baseline
  17958. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  17959. */
  17960. void drawSingleLineText (const String& text,
  17961. int startX, int baselineY) const;
  17962. /** Draws text across multiple lines.
  17963. This will break the text onto a new line where there's a new-line or
  17964. carriage-return character, or at a word-boundary when the text becomes wider
  17965. than the size specified by the maximumLineWidth parameter.
  17966. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  17967. */
  17968. void drawMultiLineText (const String& text,
  17969. int startX, int baselineY,
  17970. int maximumLineWidth) const;
  17971. /** Renders a string of text as a vector path.
  17972. This allows a string to be transformed with an arbitrary AffineTransform and
  17973. rendered using the current colour/brush. It's much slower than the normal text methods
  17974. but more accurate.
  17975. @see setFont
  17976. */
  17977. void drawTextAsPath (const String& text,
  17978. const AffineTransform& transform) const;
  17979. /** Draws a line of text within a specified rectangle.
  17980. The text will be positioned within the rectangle based on the justification
  17981. flags passed-in. If the string is too long to fit inside the rectangle, it will
  17982. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  17983. flag is true).
  17984. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  17985. */
  17986. void drawText (const String& text,
  17987. int x, int y, int width, int height,
  17988. const Justification& justificationType,
  17989. bool useEllipsesIfTooBig) const;
  17990. /** Tries to draw a text string inside a given space.
  17991. This does its best to make the given text readable within the specified rectangle,
  17992. so it useful for labelling things.
  17993. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  17994. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  17995. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  17996. it's been truncated.
  17997. A Justification parameter lets you specify how the text is laid out within the rectangle,
  17998. both horizontally and vertically.
  17999. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  18000. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  18001. can set this value to 1.0f.
  18002. @see GlyphArrangement::addFittedText
  18003. */
  18004. void drawFittedText (const String& text,
  18005. int x, int y, int width, int height,
  18006. const Justification& justificationFlags,
  18007. int maximumNumberOfLines,
  18008. float minimumHorizontalScale = 0.7f) const;
  18009. /** Fills the context's entire clip region with the current colour or brush.
  18010. (See also the fillAll (const Colour&) method which is a quick way of filling
  18011. it with a given colour).
  18012. */
  18013. void fillAll() const;
  18014. /** Fills the context's entire clip region with a given colour.
  18015. This leaves the context's current colour and brush unchanged, it just
  18016. uses the specified colour temporarily.
  18017. */
  18018. void fillAll (const Colour& colourToUse) const;
  18019. /** Fills a rectangle with the current colour or brush.
  18020. @see drawRect, fillRoundedRectangle
  18021. */
  18022. void fillRect (int x, int y, int width, int height) const;
  18023. /** Fills a rectangle with the current colour or brush. */
  18024. void fillRect (const Rectangle<int>& rectangle) const;
  18025. /** Fills a rectangle with the current colour or brush.
  18026. This uses sub-pixel positioning so is slower than the fillRect method which
  18027. takes integer co-ordinates.
  18028. */
  18029. void fillRect (float x, float y, float width, float height) const;
  18030. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  18031. @see drawRoundedRectangle, Path::addRoundedRectangle
  18032. */
  18033. void fillRoundedRectangle (float x, float y, float width, float height,
  18034. float cornerSize) const;
  18035. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  18036. @see drawRoundedRectangle, Path::addRoundedRectangle
  18037. */
  18038. void fillRoundedRectangle (const Rectangle<float>& rectangle,
  18039. float cornerSize) const;
  18040. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  18041. */
  18042. void fillCheckerBoard (int x, int y, int width, int height,
  18043. int checkWidth, int checkHeight,
  18044. const Colour& colour1, const Colour& colour2) const;
  18045. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  18046. The lines are drawn inside the given rectangle, and greater line thicknesses
  18047. extend inwards.
  18048. @see fillRect
  18049. */
  18050. void drawRect (int x, int y, int width, int height,
  18051. int lineThickness = 1) const;
  18052. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  18053. The lines are drawn inside the given rectangle, and greater line thicknesses
  18054. extend inwards.
  18055. @see fillRect
  18056. */
  18057. void drawRect (float x, float y, float width, float height,
  18058. float lineThickness = 1.0f) const;
  18059. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  18060. The lines are drawn inside the given rectangle, and greater line thicknesses
  18061. extend inwards.
  18062. @see fillRect
  18063. */
  18064. void drawRect (const Rectangle<int>& rectangle,
  18065. int lineThickness = 1) const;
  18066. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  18067. @see fillRoundedRectangle, Path::addRoundedRectangle
  18068. */
  18069. void drawRoundedRectangle (float x, float y, float width, float height,
  18070. float cornerSize, float lineThickness) const;
  18071. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  18072. @see fillRoundedRectangle, Path::addRoundedRectangle
  18073. */
  18074. void drawRoundedRectangle (const Rectangle<float>& rectangle,
  18075. float cornerSize, float lineThickness) const;
  18076. /** Draws a 3D raised (or indented) bevel using two colours.
  18077. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  18078. extend inwards.
  18079. The top-left colour is used for the top- and left-hand edges of the
  18080. bevel; the bottom-right colour is used for the bottom- and right-hand
  18081. edges.
  18082. If useGradient is true, then the bevel fades out to make it look more curved
  18083. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  18084. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  18085. the centre edges are sharp and it fades towards the outside.
  18086. */
  18087. void drawBevel (int x, int y, int width, int height,
  18088. int bevelThickness,
  18089. const Colour& topLeftColour = Colours::white,
  18090. const Colour& bottomRightColour = Colours::black,
  18091. bool useGradient = true,
  18092. bool sharpEdgeOnOutside = true) const;
  18093. /** Draws a pixel using the current colour or brush.
  18094. */
  18095. void setPixel (int x, int y) const;
  18096. /** Fills an ellipse with the current colour or brush.
  18097. The ellipse is drawn to fit inside the given rectangle.
  18098. @see drawEllipse, Path::addEllipse
  18099. */
  18100. void fillEllipse (float x, float y, float width, float height) const;
  18101. /** Draws an elliptical stroke using the current colour or brush.
  18102. @see fillEllipse, Path::addEllipse
  18103. */
  18104. void drawEllipse (float x, float y, float width, float height,
  18105. float lineThickness) const;
  18106. /** Draws a line between two points.
  18107. The line is 1 pixel wide and drawn with the current colour or brush.
  18108. */
  18109. void drawLine (float startX, float startY, float endX, float endY) const;
  18110. /** Draws a line between two points with a given thickness.
  18111. @see Path::addLineSegment
  18112. */
  18113. void drawLine (float startX, float startY, float endX, float endY,
  18114. float lineThickness) const;
  18115. /** Draws a line between two points.
  18116. The line is 1 pixel wide and drawn with the current colour or brush.
  18117. */
  18118. void drawLine (const Line<float>& line) const;
  18119. /** Draws a line between two points with a given thickness.
  18120. @see Path::addLineSegment
  18121. */
  18122. void drawLine (const Line<float>& line, float lineThickness) const;
  18123. /** Draws a dashed line using a custom set of dash-lengths.
  18124. @param startX the line's start x co-ordinate
  18125. @param startY the line's start y co-ordinate
  18126. @param endX the line's end x co-ordinate
  18127. @param endY the line's end y co-ordinate
  18128. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  18129. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  18130. draw 6 pixels, skip 7 pixels, and then repeat.
  18131. @param numDashLengths the number of elements in the array (this must be an even number).
  18132. @param lineThickness the thickness of the line to draw
  18133. @see PathStrokeType::createDashedStroke
  18134. */
  18135. void drawDashedLine (float startX, float startY,
  18136. float endX, float endY,
  18137. const float* dashLengths, int numDashLengths,
  18138. float lineThickness = 1.0f) const;
  18139. /** Draws a vertical line of pixels at a given x position.
  18140. The x position is an integer, but the top and bottom of the line can be sub-pixel
  18141. positions, and these will be anti-aliased if necessary.
  18142. */
  18143. void drawVerticalLine (int x, float top, float bottom) const;
  18144. /** Draws a horizontal line of pixels at a given y position.
  18145. The y position is an integer, but the left and right ends of the line can be sub-pixel
  18146. positions, and these will be anti-aliased if necessary.
  18147. */
  18148. void drawHorizontalLine (int y, float left, float right) const;
  18149. /** Fills a path using the currently selected colour or brush.
  18150. */
  18151. void fillPath (const Path& path,
  18152. const AffineTransform& transform = AffineTransform::identity) const;
  18153. /** Draws a path's outline using the currently selected colour or brush.
  18154. */
  18155. void strokePath (const Path& path,
  18156. const PathStrokeType& strokeType,
  18157. const AffineTransform& transform = AffineTransform::identity) const;
  18158. /** Draws a line with an arrowhead at its end.
  18159. @param line the line to draw
  18160. @param lineThickness the thickness of the line
  18161. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  18162. @param arrowheadLength the length of the arrow head (along the length of the line)
  18163. */
  18164. void drawArrow (const Line<float>& line,
  18165. float lineThickness,
  18166. float arrowheadWidth,
  18167. float arrowheadLength) const;
  18168. /** Types of rendering quality that can be specified when drawing images.
  18169. @see blendImage, Graphics::setImageResamplingQuality
  18170. */
  18171. enum ResamplingQuality
  18172. {
  18173. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  18174. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  18175. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  18176. };
  18177. /** Changes the quality that will be used when resampling images.
  18178. By default a Graphics object will be set to mediumRenderingQuality.
  18179. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  18180. */
  18181. void setImageResamplingQuality (const ResamplingQuality newQuality);
  18182. /** Draws an image.
  18183. This will draw the whole of an image, positioning its top-left corner at the
  18184. given co-ordinates, and keeping its size the same. This is the simplest image
  18185. drawing method - the others give more control over the scaling and clipping
  18186. of the images.
  18187. Images are composited using the context's current opacity, so if you
  18188. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  18189. (or setColour() with an opaque colour) before drawing images.
  18190. */
  18191. void drawImageAt (const Image& imageToDraw, int topLeftX, int topLeftY,
  18192. bool fillAlphaChannelWithCurrentBrush = false) const;
  18193. /** Draws part of an image, rescaling it to fit in a given target region.
  18194. The specified area of the source image is rescaled and drawn to fill the
  18195. specifed destination rectangle.
  18196. Images are composited using the context's current opacity, so if you
  18197. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  18198. (or setColour() with an opaque colour) before drawing images.
  18199. @param imageToDraw the image to overlay
  18200. @param destX the left of the destination rectangle
  18201. @param destY the top of the destination rectangle
  18202. @param destWidth the width of the destination rectangle
  18203. @param destHeight the height of the destination rectangle
  18204. @param sourceX the left of the rectangle to copy from the source image
  18205. @param sourceY the top of the rectangle to copy from the source image
  18206. @param sourceWidth the width of the rectangle to copy from the source image
  18207. @param sourceHeight the height of the rectangle to copy from the source image
  18208. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  18209. the source image's alpha channel is used as a mask with
  18210. which to fill the destination using the current colour
  18211. or brush. (If the source is has no alpha channel, then
  18212. it will just fill the target with a solid rectangle)
  18213. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  18214. */
  18215. void drawImage (const Image& imageToDraw,
  18216. int destX, int destY, int destWidth, int destHeight,
  18217. int sourceX, int sourceY, int sourceWidth, int sourceHeight,
  18218. bool fillAlphaChannelWithCurrentBrush = false) const;
  18219. /** Draws part of an image, having applied an affine transform to it.
  18220. This lets you throw the image around in some wacky ways, rotate it, shear,
  18221. scale it, etc.
  18222. A subregion is specified within the source image, and all transformations
  18223. will be treated as relative to the origin of this sub-region. So, for example if
  18224. your subregion is (50, 50, 100, 100), and your transform is a translation of (20, 20),
  18225. the resulting pixel drawn at (20, 20) in the destination context is from (50, 50) in
  18226. your image. If you want to use the whole image, then Image::getBounds() returns a
  18227. suitable rectangle to use as the imageSubRegion parameter.
  18228. Images are composited using the context's current opacity, so if you
  18229. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  18230. (or setColour() with an opaque colour) before drawing images.
  18231. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  18232. are ignored and it is filled with the current brush, masked by its alpha channel.
  18233. @see setImageResamplingQuality, drawImage
  18234. */
  18235. void drawImageTransformed (const Image& imageToDraw,
  18236. const Rectangle<int>& imageSubRegion,
  18237. const AffineTransform& transform,
  18238. bool fillAlphaChannelWithCurrentBrush = false) const;
  18239. /** Draws an image to fit within a designated rectangle.
  18240. If the image is too big or too small for the space, it will be rescaled
  18241. to fit as nicely as it can do without affecting its aspect ratio. It will
  18242. then be placed within the target rectangle according to the justification flags
  18243. specified.
  18244. @param imageToDraw the source image to draw
  18245. @param destX top-left of the target rectangle to fit it into
  18246. @param destY top-left of the target rectangle to fit it into
  18247. @param destWidth size of the target rectangle to fit the image into
  18248. @param destHeight size of the target rectangle to fit the image into
  18249. @param placementWithinTarget this specifies how the image should be positioned
  18250. within the target rectangle - see the RectanglePlacement
  18251. class for more details about this.
  18252. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  18253. alpha channel will be used as a mask with which to
  18254. draw with the current brush or colour. This is
  18255. similar to fillAlphaMap(), and see also drawImage()
  18256. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  18257. */
  18258. void drawImageWithin (const Image& imageToDraw,
  18259. int destX, int destY, int destWidth, int destHeight,
  18260. const RectanglePlacement& placementWithinTarget,
  18261. bool fillAlphaChannelWithCurrentBrush = false) const;
  18262. /** Returns the position of the bounding box for the current clipping region.
  18263. @see getClipRegion, clipRegionIntersects
  18264. */
  18265. const Rectangle<int> getClipBounds() const;
  18266. /** Checks whether a rectangle overlaps the context's clipping region.
  18267. If this returns false, no part of the given area can be drawn onto, so this
  18268. method can be used to optimise a component's paint() method, by letting it
  18269. avoid drawing complex objects that aren't within the region being repainted.
  18270. */
  18271. bool clipRegionIntersects (const Rectangle<int>& area) const;
  18272. /** Intersects the current clipping region with another region.
  18273. @returns true if the resulting clipping region is non-zero in size
  18274. @see setOrigin, clipRegionIntersects
  18275. */
  18276. bool reduceClipRegion (int x, int y, int width, int height);
  18277. /** Intersects the current clipping region with a rectangle list region.
  18278. @returns true if the resulting clipping region is non-zero in size
  18279. @see setOrigin, clipRegionIntersects
  18280. */
  18281. bool reduceClipRegion (const RectangleList& clipRegion);
  18282. /** Intersects the current clipping region with a path.
  18283. @returns true if the resulting clipping region is non-zero in size
  18284. @see reduceClipRegion
  18285. */
  18286. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity);
  18287. /** Intersects the current clipping region with an image's alpha-channel.
  18288. The current clipping path is intersected with the area covered by this image's
  18289. alpha-channel, after the image has been transformed by the specified matrix.
  18290. @param image the image whose alpha-channel should be used. If the image doesn't
  18291. have an alpha-channel, it is treated as entirely opaque.
  18292. @param sourceClipRegion a subsection of the image that should be used. To use the
  18293. entire image, just pass a rectangle of bounds
  18294. (0, 0, image.getWidth(), image.getHeight()).
  18295. @param transform a matrix to apply to the image
  18296. @returns true if the resulting clipping region is non-zero in size
  18297. @see reduceClipRegion
  18298. */
  18299. bool reduceClipRegion (const Image& image, const Rectangle<int>& sourceClipRegion,
  18300. const AffineTransform& transform);
  18301. /** Excludes a rectangle to stop it being drawn into. */
  18302. void excludeClipRegion (const Rectangle<int>& rectangleToExclude);
  18303. /** Returns true if no drawing can be done because the clip region is zero. */
  18304. bool isClipEmpty() const;
  18305. /** Saves the current graphics state on an internal stack.
  18306. To restore the state, use restoreState().
  18307. */
  18308. void saveState();
  18309. /** Restores a graphics state that was previously saved with saveState().
  18310. */
  18311. void restoreState();
  18312. /** Moves the position of the context's origin.
  18313. This changes the position that the context considers to be (0, 0) to
  18314. the specified position.
  18315. So if you call setOrigin (100, 100), then the position that was previously
  18316. referred to as (100, 100) will subsequently be considered to be (0, 0).
  18317. @see reduceClipRegion
  18318. */
  18319. void setOrigin (int newOriginX, int newOriginY);
  18320. /** Resets the current colour, brush, and font to default settings. */
  18321. void resetToDefaultState();
  18322. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  18323. bool isVectorDevice() const;
  18324. juce_UseDebuggingNewOperator
  18325. /** Create a graphics that uses a given low-level renderer.
  18326. For internal use only.
  18327. NB. The context will NOT be deleted by this object when it is deleted.
  18328. */
  18329. Graphics (LowLevelGraphicsContext* const internalContext) throw();
  18330. /** @internal */
  18331. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  18332. private:
  18333. LowLevelGraphicsContext* const context;
  18334. ScopedPointer <LowLevelGraphicsContext> contextToDelete;
  18335. bool saveStatePending;
  18336. void saveStateIfPending();
  18337. Graphics (const Graphics&);
  18338. Graphics& operator= (const Graphics& other);
  18339. };
  18340. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  18341. /*** End of inlined file: juce_Graphics.h ***/
  18342. /**
  18343. A graphical effect filter that can be applied to components.
  18344. An ImageEffectFilter can be applied to the image that a component
  18345. paints before it hits the screen.
  18346. This is used for adding effects like shadows, blurs, etc.
  18347. @see Component::setComponentEffect
  18348. */
  18349. class JUCE_API ImageEffectFilter
  18350. {
  18351. public:
  18352. /** Overridden to render the effect.
  18353. The implementation of this method must use the image that is passed in
  18354. as its source, and should render its output to the graphics context passed in.
  18355. @param sourceImage the image that the source component has just rendered with
  18356. its paint() method. The image may or may not have an alpha
  18357. channel, depending on whether the component is opaque.
  18358. @param destContext the graphics context to use to draw the resultant image.
  18359. */
  18360. virtual void applyEffect (Image& sourceImage,
  18361. Graphics& destContext) = 0;
  18362. /** Destructor. */
  18363. virtual ~ImageEffectFilter() {}
  18364. };
  18365. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  18366. /*** End of inlined file: juce_ImageEffectFilter.h ***/
  18367. /*** Start of inlined file: juce_Image.h ***/
  18368. #ifndef __JUCE_IMAGE_JUCEHEADER__
  18369. #define __JUCE_IMAGE_JUCEHEADER__
  18370. /**
  18371. Holds a fixed-size bitmap.
  18372. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  18373. To draw into an image, create a Graphics object for it.
  18374. e.g. @code
  18375. // create a transparent 500x500 image..
  18376. Image myImage (Image::RGB, 500, 500, true);
  18377. Graphics g (myImage);
  18378. g.setColour (Colours::red);
  18379. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  18380. @endcode
  18381. Other useful ways to create an image are with the ImageCache class, or the
  18382. ImageFileFormat, which provides a way to load common image files.
  18383. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  18384. */
  18385. class JUCE_API Image
  18386. {
  18387. public:
  18388. /**
  18389. */
  18390. enum PixelFormat
  18391. {
  18392. UnknownFormat,
  18393. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  18394. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  18395. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  18396. };
  18397. /**
  18398. */
  18399. enum ImageType
  18400. {
  18401. SoftwareImage = 0,
  18402. NativeImage
  18403. };
  18404. /** Creates a null image. */
  18405. Image();
  18406. /** Creates an image with a specified size and format.
  18407. @param format the number of colour channels in the image
  18408. @param imageWidth the desired width of the image, in pixels - this value must be
  18409. greater than zero (otherwise a width of 1 will be used)
  18410. @param imageHeight the desired width of the image, in pixels - this value must be
  18411. greater than zero (otherwise a height of 1 will be used)
  18412. @param clearImage if true, the image will initially be cleared to black (if it's RGB)
  18413. or transparent black (if it's ARGB). If false, the image may contain
  18414. junk initially, so you need to make sure you overwrite it thoroughly.
  18415. @param type the type of image - this lets you specify whether you want a purely
  18416. memory-based image, or one that may be managed by the OS if possible.
  18417. */
  18418. Image (PixelFormat format,
  18419. int imageWidth,
  18420. int imageHeight,
  18421. bool clearImage,
  18422. ImageType type = NativeImage);
  18423. /** Creates a shared reference to another image.
  18424. This won't create a duplicate of the image - when Image objects are copied, they simply
  18425. point to the same shared image data. To make sure that an Image object has its own unique,
  18426. unshared internal data, call duplicateIfShared().
  18427. */
  18428. Image (const Image& other);
  18429. /** Makes this image refer to the same underlying image as another object.
  18430. This won't create a duplicate of the image - when Image objects are copied, they simply
  18431. point to the same shared image data. To make sure that an Image object has its own unique,
  18432. unshared internal data, call duplicateIfShared().
  18433. */
  18434. Image& operator= (const Image&);
  18435. /** Destructor. */
  18436. ~Image();
  18437. /** Returns true if the two images are referring to the same internal, shared image. */
  18438. bool operator== (const Image& other) const throw() { return image == other.image; }
  18439. /** Returns true if the two images are not referring to the same internal, shared image. */
  18440. bool operator!= (const Image& other) const throw() { return image != other.image; }
  18441. /** Returns true if this image isn't null.
  18442. If you create an Image with the default constructor, it has no size or content, and is null
  18443. until you reassign it to an Image which contains some actual data.
  18444. The isNull() method is the opposite of isValid().
  18445. @see isNull
  18446. */
  18447. inline bool isValid() const throw() { return image != 0; }
  18448. /** Returns true if this image is not valid.
  18449. If you create an Image with the default constructor, it has no size or content, and is null
  18450. until you reassign it to an Image which contains some actual data.
  18451. The isNull() method is the opposite of isValid().
  18452. @see isValid
  18453. */
  18454. inline bool isNull() const throw() { return image == 0; }
  18455. /** Returns the image's width (in pixels). */
  18456. int getWidth() const throw() { return image == 0 ? 0 : image->width; }
  18457. /** Returns the image's height (in pixels). */
  18458. int getHeight() const throw() { return image == 0 ? 0 : image->height; }
  18459. /** Returns a rectangle with the same size as this image.
  18460. The rectangle's origin is always (0, 0).
  18461. */
  18462. const Rectangle<int> getBounds() const throw() { return image == 0 ? Rectangle<int>() : Rectangle<int> (0, 0, image->width, image->height); }
  18463. /** Returns the image's pixel format. */
  18464. PixelFormat getFormat() const throw() { return image == 0 ? UnknownFormat : image->format; }
  18465. /** True if the image's format is ARGB. */
  18466. bool isARGB() const throw() { return getFormat() == ARGB; }
  18467. /** True if the image's format is RGB. */
  18468. bool isRGB() const throw() { return getFormat() == RGB; }
  18469. /** True if the image's format is a single-channel alpha map. */
  18470. bool isSingleChannel() const throw() { return getFormat() == SingleChannel; }
  18471. /** True if the image contains an alpha-channel. */
  18472. bool hasAlphaChannel() const throw() { return getFormat() != RGB; }
  18473. /** Clears a section of the image with a given colour.
  18474. This won't do any alpha-blending - it just sets all pixels in the image to
  18475. the given colour (which may be non-opaque if the image has an alpha channel).
  18476. */
  18477. void clear (const Rectangle<int>& area, const Colour& colourToClearTo = Colour (0x00000000));
  18478. /** Returns a rescaled version of this image.
  18479. A new image is returned which is a copy of this one, rescaled to the given size.
  18480. Note that if the new size is identical to the existing image, this will just return
  18481. a reference to the original image, and won't actually create a duplicate.
  18482. */
  18483. const Image rescaled (int newWidth, int newHeight,
  18484. Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  18485. /** Returns a version of this image with a different image format.
  18486. A new image is returned which has been converted to the specified format.
  18487. Note that if the new format is no different to the current one, this will just return
  18488. a reference to the original image, and won't actually create a copy.
  18489. */
  18490. const Image convertedToFormat (PixelFormat newFormat) const;
  18491. /** Makes sure that no other Image objects share the same underlying data as this one.
  18492. If no other Image objects refer to the same shared data as this one, this method has no
  18493. effect. But if there are other references to the data, this will create a new copy of
  18494. the data internally.
  18495. Call this if you want to draw onto the image, but want to make sure that this doesn't
  18496. affect any other code that may be sharing the same data.
  18497. @see getReferenceCount
  18498. */
  18499. void duplicateIfShared();
  18500. /** Returns the colour of one of the pixels in the image.
  18501. If the co-ordinates given are beyond the image's boundaries, this will
  18502. return Colours::transparentBlack.
  18503. @see setPixelAt, Image::BitmapData::getPixelColour
  18504. */
  18505. const Colour getPixelAt (int x, int y) const;
  18506. /** Sets the colour of one of the image's pixels.
  18507. If the co-ordinates are beyond the image's boundaries, then nothing will happen.
  18508. Note that this won't do any alpha-blending, it'll just replace the existing pixel
  18509. with the given one. The colour's opacity will be ignored if this image doesn't have
  18510. an alpha-channel.
  18511. @see getPixelAt, Image::BitmapData::setPixelColour
  18512. */
  18513. void setPixelAt (int x, int y, const Colour& colour);
  18514. /** Changes the opacity of a pixel.
  18515. This only has an effect if the image has an alpha channel and if the
  18516. given co-ordinates are inside the image's boundary.
  18517. The multiplier must be in the range 0 to 1.0, and the current alpha
  18518. at the given co-ordinates will be multiplied by this value.
  18519. @see setPixelAt
  18520. */
  18521. void multiplyAlphaAt (int x, int y, float multiplier);
  18522. /** Changes the overall opacity of the image.
  18523. This will multiply the alpha value of each pixel in the image by the given
  18524. amount (limiting the resulting alpha values between 0 and 255). This allows
  18525. you to make an image more or less transparent.
  18526. If the image doesn't have an alpha channel, this won't have any effect.
  18527. */
  18528. void multiplyAllAlphas (float amountToMultiplyBy);
  18529. /** Changes all the colours to be shades of grey, based on their current luminosity.
  18530. */
  18531. void desaturate();
  18532. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  18533. You should only use this class as a last resort - messing about with the internals of
  18534. an image is only recommended for people who really know what they're doing!
  18535. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  18536. hanging around while the image is being used elsewhere.
  18537. Depending on the way the image class is implemented, this may create a temporary buffer
  18538. which is copied back to the image when the object is deleted, or it may just get a pointer
  18539. directly into the image's raw data.
  18540. You can use the stride and data values in this class directly, but don't alter them!
  18541. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  18542. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  18543. */
  18544. class BitmapData
  18545. {
  18546. public:
  18547. BitmapData (Image& image, int x, int y, int w, int h, bool needsToBeWritable);
  18548. BitmapData (const Image& image, int x, int y, int w, int h);
  18549. ~BitmapData();
  18550. /** Returns a pointer to the start of a line in the image.
  18551. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  18552. sure it's not out-of-range.
  18553. */
  18554. inline uint8* getLinePointer (int y) const throw() { return data + y * lineStride; }
  18555. /** Returns a pointer to a pixel in the image.
  18556. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  18557. not out-of-range.
  18558. */
  18559. inline uint8* getPixelPointer (int x, int y) const throw() { return data + y * lineStride + x * pixelStride; }
  18560. /** Returns the colour of a given pixel.
  18561. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  18562. repsonsibility to make sure they're within the image's size.
  18563. */
  18564. const Colour getPixelColour (int x, int y) const throw();
  18565. /** Sets the colour of a given pixel.
  18566. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  18567. repsonsibility to make sure they're within the image's size.
  18568. */
  18569. void setPixelColour (int x, int y, const Colour& colour) const throw();
  18570. uint8* data;
  18571. const PixelFormat pixelFormat;
  18572. int lineStride, pixelStride, width, height;
  18573. private:
  18574. BitmapData (const BitmapData&);
  18575. BitmapData& operator= (const BitmapData&);
  18576. };
  18577. /** Copies some pixel values to a rectangle of the image.
  18578. The format of the pixel data must match that of the image itself, and the
  18579. rectangle supplied must be within the image's bounds.
  18580. */
  18581. void setPixelData (int destX, int destY, int destW, int destH,
  18582. const uint8* sourcePixelData, int sourceLineStride);
  18583. /** Copies a section of the image to somewhere else within itself. */
  18584. void moveImageSection (int destX, int destY,
  18585. int sourceX, int sourceY,
  18586. int width, int height);
  18587. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  18588. of the image.
  18589. @param result the list that will have the area added to it
  18590. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  18591. above this level will be considered opaque
  18592. */
  18593. void createSolidAreaMask (RectangleList& result,
  18594. float alphaThreshold = 0.5f) const;
  18595. /** Returns a user-specified data item that was set with setTag().
  18596. setTag() and getTag() allow you to attach an arbitrary identifier value to an
  18597. image. The value is shared between all Image object that are referring to the
  18598. same underlying image data object.
  18599. */
  18600. const var getTag() const;
  18601. /** Attaches a user-specified data item to this image, which can be retrieved using getTag().
  18602. setTag() and getTag() allow you to attach an arbitrary identifier value to an
  18603. image. The value is shared between all Image object that are referring to the
  18604. same underlying image data object.
  18605. Note that if this Image is null, this method will fail to store the data.
  18606. */
  18607. void setTag (const var& newTag);
  18608. /** Creates a context suitable for drawing onto this image.
  18609. Don't call this method directly! It's used internally by the Graphics class.
  18610. */
  18611. LowLevelGraphicsContext* createLowLevelContext() const;
  18612. /** Returns the number of Image objects which are currently referring to the same internal
  18613. shared image data.
  18614. @see duplicateIfShared
  18615. */
  18616. int getReferenceCount() const throw() { return image == 0 ? 0 : image->getReferenceCount(); }
  18617. /** This is a base class for task-specific types of image.
  18618. Don't use this class directly! It's used internally by the Image class.
  18619. */
  18620. class SharedImage : public ReferenceCountedObject
  18621. {
  18622. public:
  18623. SharedImage (PixelFormat format, int width, int height);
  18624. ~SharedImage();
  18625. virtual LowLevelGraphicsContext* createLowLevelContext() = 0;
  18626. virtual SharedImage* clone() = 0;
  18627. virtual ImageType getType() const = 0;
  18628. static SharedImage* createNativeImage (PixelFormat format, int width, int height, bool clearImage);
  18629. static SharedImage* createSoftwareImage (PixelFormat format, int width, int height, bool clearImage);
  18630. protected:
  18631. friend class Image;
  18632. friend class Image::BitmapData;
  18633. const PixelFormat format;
  18634. const int width, height;
  18635. int pixelStride, lineStride;
  18636. uint8* imageData;
  18637. var userTag;
  18638. uint8* getPixelData (int x, int y) const throw();
  18639. SharedImage (const SharedImage&);
  18640. SharedImage& operator= (const SharedImage&);
  18641. };
  18642. /** @internal */
  18643. SharedImage* getSharedImage() const throw() { return image; }
  18644. /** @internal */
  18645. explicit Image (SharedImage* instance);
  18646. juce_UseDebuggingNewOperator
  18647. private:
  18648. ReferenceCountedObjectPtr<SharedImage> image;
  18649. };
  18650. #endif // __JUCE_IMAGE_JUCEHEADER__
  18651. /*** End of inlined file: juce_Image.h ***/
  18652. /*** Start of inlined file: juce_RectangleList.h ***/
  18653. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  18654. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  18655. /**
  18656. Maintains a set of rectangles as a complex region.
  18657. This class allows a set of rectangles to be treated as a solid shape, and can
  18658. add and remove rectangular sections of it, and simplify overlapping or
  18659. adjacent rectangles.
  18660. @see Rectangle
  18661. */
  18662. class JUCE_API RectangleList
  18663. {
  18664. public:
  18665. /** Creates an empty RectangleList */
  18666. RectangleList() throw();
  18667. /** Creates a copy of another list */
  18668. RectangleList (const RectangleList& other);
  18669. /** Creates a list containing just one rectangle. */
  18670. RectangleList (const Rectangle<int>& rect);
  18671. /** Copies this list from another one. */
  18672. RectangleList& operator= (const RectangleList& other);
  18673. /** Destructor. */
  18674. ~RectangleList();
  18675. /** Returns true if the region is empty. */
  18676. bool isEmpty() const throw();
  18677. /** Returns the number of rectangles in the list. */
  18678. int getNumRectangles() const throw() { return rects.size(); }
  18679. /** Returns one of the rectangles at a particular index.
  18680. @returns the rectangle at the index, or an empty rectangle if the
  18681. index is out-of-range.
  18682. */
  18683. const Rectangle<int> getRectangle (int index) const throw();
  18684. /** Removes all rectangles to leave an empty region. */
  18685. void clear();
  18686. /** Merges a new rectangle into the list.
  18687. The rectangle being added will first be clipped to remove any parts of it
  18688. that overlap existing rectangles in the list.
  18689. */
  18690. void add (int x, int y, int width, int height);
  18691. /** Merges a new rectangle into the list.
  18692. The rectangle being added will first be clipped to remove any parts of it
  18693. that overlap existing rectangles in the list, and adjacent rectangles will be
  18694. merged into it.
  18695. */
  18696. void add (const Rectangle<int>& rect);
  18697. /** Dumbly adds a rectangle to the list without checking for overlaps.
  18698. This simply adds the rectangle to the end, it doesn't merge it or remove
  18699. any overlapping bits.
  18700. */
  18701. void addWithoutMerging (const Rectangle<int>& rect);
  18702. /** Merges another rectangle list into this one.
  18703. Any overlaps between the two lists will be clipped, so that the result is
  18704. the union of both lists.
  18705. */
  18706. void add (const RectangleList& other);
  18707. /** Removes a rectangular region from the list.
  18708. Any rectangles in the list which overlap this will be clipped and subdivided
  18709. if necessary.
  18710. */
  18711. void subtract (const Rectangle<int>& rect);
  18712. /** Removes all areas in another RectangleList from this one.
  18713. Any rectangles in the list which overlap this will be clipped and subdivided
  18714. if necessary.
  18715. @returns true if the resulting list is non-empty.
  18716. */
  18717. bool subtract (const RectangleList& otherList);
  18718. /** Removes any areas of the region that lie outside a given rectangle.
  18719. Any rectangles in the list which overlap this will be clipped and subdivided
  18720. if necessary.
  18721. Returns true if the resulting region is not empty, false if it is empty.
  18722. @see getIntersectionWith
  18723. */
  18724. bool clipTo (const Rectangle<int>& rect);
  18725. /** Removes any areas of the region that lie outside a given rectangle list.
  18726. Any rectangles in this object which overlap the specified list will be clipped
  18727. and subdivided if necessary.
  18728. Returns true if the resulting region is not empty, false if it is empty.
  18729. @see getIntersectionWith
  18730. */
  18731. bool clipTo (const RectangleList& other);
  18732. /** Creates a region which is the result of clipping this one to a given rectangle.
  18733. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  18734. resulting region into the list whose reference is passed-in.
  18735. Returns true if the resulting region is not empty, false if it is empty.
  18736. @see clipTo
  18737. */
  18738. bool getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const;
  18739. /** Swaps the contents of this and another list.
  18740. This swaps their internal pointers, so is hugely faster than using copy-by-value
  18741. to swap them.
  18742. */
  18743. void swapWith (RectangleList& otherList) throw();
  18744. /** Checks whether the region contains a given point.
  18745. @returns true if the point lies within one of the rectangles in the list
  18746. */
  18747. bool containsPoint (int x, int y) const throw();
  18748. /** Checks whether the region contains the whole of a given rectangle.
  18749. @returns true all parts of the rectangle passed in lie within the region
  18750. defined by this object
  18751. @see intersectsRectangle, containsPoint
  18752. */
  18753. bool containsRectangle (const Rectangle<int>& rectangleToCheck) const;
  18754. /** Checks whether the region contains any part of a given rectangle.
  18755. @returns true if any part of the rectangle passed in lies within the region
  18756. defined by this object
  18757. @see containsRectangle
  18758. */
  18759. bool intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw();
  18760. /** Checks whether this region intersects any part of another one.
  18761. @see intersectsRectangle
  18762. */
  18763. bool intersects (const RectangleList& other) const throw();
  18764. /** Returns the smallest rectangle that can enclose the whole of this region. */
  18765. const Rectangle<int> getBounds() const throw();
  18766. /** Optimises the list into a minimum number of constituent rectangles.
  18767. This will try to combine any adjacent rectangles into larger ones where
  18768. possible, to simplify lists that might have been fragmented by repeated
  18769. add/subtract calls.
  18770. */
  18771. void consolidate();
  18772. /** Adds an x and y value to all the co-ordinates. */
  18773. void offsetAll (int dx, int dy) throw();
  18774. /** Creates a Path object to represent this region. */
  18775. const Path toPath() const;
  18776. /** An iterator for accessing all the rectangles in a RectangleList. */
  18777. class Iterator
  18778. {
  18779. public:
  18780. Iterator (const RectangleList& list) throw();
  18781. ~Iterator();
  18782. /** Advances to the next rectangle, and returns true if it's not finished.
  18783. Call this before using getRectangle() to find the rectangle that was returned.
  18784. */
  18785. bool next() throw();
  18786. /** Returns the current rectangle. */
  18787. const Rectangle<int>* getRectangle() const throw() { return current; }
  18788. juce_UseDebuggingNewOperator
  18789. private:
  18790. const Rectangle<int>* current;
  18791. const RectangleList& owner;
  18792. int index;
  18793. Iterator (const Iterator&);
  18794. Iterator& operator= (const Iterator&);
  18795. };
  18796. juce_UseDebuggingNewOperator
  18797. private:
  18798. friend class Iterator;
  18799. Array <Rectangle<int> > rects;
  18800. };
  18801. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  18802. /*** End of inlined file: juce_RectangleList.h ***/
  18803. /*** Start of inlined file: juce_BorderSize.h ***/
  18804. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  18805. #define __JUCE_BORDERSIZE_JUCEHEADER__
  18806. /**
  18807. Specifies a set of gaps to be left around the sides of a rectangle.
  18808. This is basically the size of the spaces at the top, bottom, left and right of
  18809. a rectangle. It's used by various component classes to specify borders.
  18810. @see Rectangle
  18811. */
  18812. class JUCE_API BorderSize
  18813. {
  18814. public:
  18815. /** Creates a null border.
  18816. All sizes are left as 0.
  18817. */
  18818. BorderSize() throw();
  18819. /** Creates a copy of another border. */
  18820. BorderSize (const BorderSize& other) throw();
  18821. /** Creates a border with the given gaps. */
  18822. BorderSize (int topGap,
  18823. int leftGap,
  18824. int bottomGap,
  18825. int rightGap) throw();
  18826. /** Creates a border with the given gap on all sides. */
  18827. explicit BorderSize (int allGaps) throw();
  18828. /** Destructor. */
  18829. ~BorderSize() throw();
  18830. /** Returns the gap that should be left at the top of the region. */
  18831. int getTop() const throw() { return top; }
  18832. /** Returns the gap that should be left at the top of the region. */
  18833. int getLeft() const throw() { return left; }
  18834. /** Returns the gap that should be left at the top of the region. */
  18835. int getBottom() const throw() { return bottom; }
  18836. /** Returns the gap that should be left at the top of the region. */
  18837. int getRight() const throw() { return right; }
  18838. /** Returns the sum of the top and bottom gaps. */
  18839. int getTopAndBottom() const throw() { return top + bottom; }
  18840. /** Returns the sum of the left and right gaps. */
  18841. int getLeftAndRight() const throw() { return left + right; }
  18842. /** Changes the top gap. */
  18843. void setTop (int newTopGap) throw();
  18844. /** Changes the left gap. */
  18845. void setLeft (int newLeftGap) throw();
  18846. /** Changes the bottom gap. */
  18847. void setBottom (int newBottomGap) throw();
  18848. /** Changes the right gap. */
  18849. void setRight (int newRightGap) throw();
  18850. /** Returns a rectangle with these borders removed from it. */
  18851. const Rectangle<int> subtractedFrom (const Rectangle<int>& original) const throw();
  18852. /** Removes this border from a given rectangle. */
  18853. void subtractFrom (Rectangle<int>& rectangle) const throw();
  18854. /** Returns a rectangle with these borders added around it. */
  18855. const Rectangle<int> addedTo (const Rectangle<int>& original) const throw();
  18856. /** Adds this border around a given rectangle. */
  18857. void addTo (Rectangle<int>& original) const throw();
  18858. bool operator== (const BorderSize& other) const throw();
  18859. bool operator!= (const BorderSize& other) const throw();
  18860. juce_UseDebuggingNewOperator
  18861. private:
  18862. int top, left, bottom, right;
  18863. };
  18864. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  18865. /*** End of inlined file: juce_BorderSize.h ***/
  18866. class LookAndFeel;
  18867. class MouseInputSource;
  18868. class MouseInputSourceInternal;
  18869. class ComponentPeer;
  18870. /**
  18871. The base class for all JUCE user-interface objects.
  18872. */
  18873. class JUCE_API Component : public MouseListener,
  18874. public MessageListener
  18875. {
  18876. public:
  18877. /** Creates a component.
  18878. To get it to actually appear, you'll also need to:
  18879. - Either add it to a parent component or use the addToDesktop() method to
  18880. make it a desktop window
  18881. - Set its size and position to something sensible
  18882. - Use setVisible() to make it visible
  18883. And for it to serve any useful purpose, you'll need to write a
  18884. subclass of Component or use one of the other types of component from
  18885. the library.
  18886. */
  18887. Component();
  18888. /** Destructor.
  18889. Note that when a component is deleted, any child components it might
  18890. contain are NOT deleted unless you explicitly call deleteAllChildren() first.
  18891. */
  18892. virtual ~Component();
  18893. /** Creates a component, setting its name at the same time.
  18894. @see getName, setName
  18895. */
  18896. explicit Component (const String& componentName);
  18897. /** Returns the name of this component.
  18898. @see setName
  18899. */
  18900. const String& getName() const throw() { return componentName_; }
  18901. /** Sets the name of this component.
  18902. When the name changes, all registered ComponentListeners will receive a
  18903. ComponentListener::componentNameChanged() callback.
  18904. @see getName
  18905. */
  18906. virtual void setName (const String& newName);
  18907. /** Checks whether this Component object has been deleted.
  18908. This will check whether this object is still a valid component, or whether
  18909. it's been deleted.
  18910. It's safe to call this on null or dangling pointers, but note that there is a
  18911. small risk if another new (but different) component has been created at the
  18912. same memory address which this one occupied, this methods can return a
  18913. false positive.
  18914. */
  18915. bool isValidComponent() const;
  18916. /** Makes the component visible or invisible.
  18917. This method will show or hide the component.
  18918. Note that components default to being non-visible when first created.
  18919. Also note that visible components won't be seen unless all their parent components
  18920. are also visible.
  18921. This method will call visibilityChanged() and also componentVisibilityChanged()
  18922. for any component listeners that are interested in this component.
  18923. @param shouldBeVisible whether to show or hide the component
  18924. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  18925. */
  18926. virtual void setVisible (bool shouldBeVisible);
  18927. /** Tests whether the component is visible or not.
  18928. this doesn't necessarily tell you whether this comp is actually on the screen
  18929. because this depends on whether all the parent components are also visible - use
  18930. isShowing() to find this out.
  18931. @see isShowing, setVisible
  18932. */
  18933. bool isVisible() const throw() { return flags.visibleFlag; }
  18934. /** Called when this component's visiblility changes.
  18935. @see setVisible, isVisible
  18936. */
  18937. virtual void visibilityChanged();
  18938. /** Tests whether this component and all its parents are visible.
  18939. @returns true only if this component and all its parents are visible.
  18940. @see isVisible
  18941. */
  18942. bool isShowing() const;
  18943. /** Makes a component invisible using a groovy fade-out and animated zoom effect.
  18944. To do this, this function will cunningly:
  18945. - take a snapshot of the component as it currently looks
  18946. - call setVisible(false) on the component
  18947. - replace it with a special component that will continue drawing the
  18948. snapshot, animating it and gradually making it more transparent
  18949. - when it's gone, the special component will also be deleted
  18950. As soon as this method returns, the component can be safely removed and deleted
  18951. leaving the proxy to do the fade-out, so it's even ok to call this in a
  18952. component's destructor.
  18953. Passing non-zero x and y values will cause the ghostly component image to
  18954. also whizz off by this distance while fading out. If the scale factor is
  18955. not 1.0, it will also zoom from the component's current size to this new size.
  18956. One thing to be careful about is that the parent component must be able to cope
  18957. with this unknown component type being added to it.
  18958. */
  18959. void fadeOutComponent (int lengthOfFadeOutInMilliseconds,
  18960. int deltaXToMove = 0,
  18961. int deltaYToMove = 0,
  18962. float scaleFactorAtEnd = 1.0f);
  18963. /** Makes this component appear as a window on the desktop.
  18964. Note that before calling this, you should make sure that the component's opacity is
  18965. set correctly using setOpaque(). If the component is non-opaque, the windowing
  18966. system will try to create a special transparent window for it, which will generally take
  18967. a lot more CPU to operate (and might not even be possible on some platforms).
  18968. If the component is inside a parent component at the time this method is called, it
  18969. will be first be removed from that parent. Likewise if a component on the desktop
  18970. is subsequently added to another component, it'll be removed from the desktop.
  18971. @param windowStyleFlags a combination of the flags specified in the
  18972. ComponentPeer::StyleFlags enum, which define the
  18973. window's characteristics.
  18974. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  18975. in which the juce component should place itself. On Windows,
  18976. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  18977. supported on all platforms, and best left as 0 unless you know
  18978. what you're doing
  18979. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  18980. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  18981. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  18982. */
  18983. virtual void addToDesktop (int windowStyleFlags,
  18984. void* nativeWindowToAttachTo = 0);
  18985. /** If the component is currently showing on the desktop, this will hide it.
  18986. You can also use setVisible() to hide a desktop window temporarily, but
  18987. removeFromDesktop() will free any system resources that are being used up.
  18988. @see addToDesktop, isOnDesktop
  18989. */
  18990. void removeFromDesktop();
  18991. /** Returns true if this component is currently showing on the desktop.
  18992. @see addToDesktop, removeFromDesktop
  18993. */
  18994. bool isOnDesktop() const throw();
  18995. /** Returns the heavyweight window that contains this component.
  18996. If this component is itself on the desktop, this will return the window
  18997. object that it is using. Otherwise, it will return the window of
  18998. its top-level parent component.
  18999. This may return 0 if there isn't a desktop component.
  19000. @see addToDesktop, isOnDesktop
  19001. */
  19002. ComponentPeer* getPeer() const;
  19003. /** For components on the desktop, this is called if the system wants to close the window.
  19004. This is a signal that either the user or the system wants the window to close. The
  19005. default implementation of this method will trigger an assertion to warn you that your
  19006. component should do something about it, but you can override this to ignore the event
  19007. if you want.
  19008. */
  19009. virtual void userTriedToCloseWindow();
  19010. /** Called for a desktop component which has just been minimised or un-minimised.
  19011. This will only be called for components on the desktop.
  19012. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  19013. */
  19014. virtual void minimisationStateChanged (bool isNowMinimised);
  19015. /** Brings the component to the front of its siblings.
  19016. If some of the component's siblings have had their 'always-on-top' flag set,
  19017. then they will still be kept in front of this one (unless of course this
  19018. one is also 'always-on-top').
  19019. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  19020. to the component (see grabKeyboardFocus() for more details)
  19021. @see toBack, toBehind, setAlwaysOnTop
  19022. */
  19023. void toFront (bool shouldAlsoGainFocus);
  19024. /** Changes this component's z-order to be at the back of all its siblings.
  19025. If the component is set to be 'always-on-top', it will only be moved to the
  19026. back of the other other 'always-on-top' components.
  19027. @see toFront, toBehind, setAlwaysOnTop
  19028. */
  19029. void toBack();
  19030. /** Changes this component's z-order so that it's just behind another component.
  19031. @see toFront, toBack
  19032. */
  19033. void toBehind (Component* other);
  19034. /** Sets whether the component should always be kept at the front of its siblings.
  19035. @see isAlwaysOnTop
  19036. */
  19037. void setAlwaysOnTop (bool shouldStayOnTop);
  19038. /** Returns true if this component is set to always stay in front of its siblings.
  19039. @see setAlwaysOnTop
  19040. */
  19041. bool isAlwaysOnTop() const throw();
  19042. /** Returns the x co-ordinate of the component's left edge.
  19043. This is a distance in pixels from the left edge of the component's parent.
  19044. @see getScreenX
  19045. */
  19046. inline int getX() const throw() { return bounds_.getX(); }
  19047. /** Returns the y co-ordinate of the top of this component.
  19048. This is a distance in pixels from the top edge of the component's parent.
  19049. @see getScreenY
  19050. */
  19051. inline int getY() const throw() { return bounds_.getY(); }
  19052. /** Returns the component's width in pixels. */
  19053. inline int getWidth() const throw() { return bounds_.getWidth(); }
  19054. /** Returns the component's height in pixels. */
  19055. inline int getHeight() const throw() { return bounds_.getHeight(); }
  19056. /** Returns the x co-ordinate of the component's right-hand edge.
  19057. This is a distance in pixels from the left edge of the component's parent.
  19058. */
  19059. int getRight() const throw() { return bounds_.getRight(); }
  19060. /** Returns the component's top-left position as a Point. */
  19061. const Point<int> getPosition() const throw() { return bounds_.getPosition(); }
  19062. /** Returns the y co-ordinate of the bottom edge of this component.
  19063. This is a distance in pixels from the top edge of the component's parent.
  19064. */
  19065. int getBottom() const throw() { return bounds_.getBottom(); }
  19066. /** Returns this component's bounding box.
  19067. The rectangle returned is relative to the top-left of the component's parent.
  19068. */
  19069. const Rectangle<int>& getBounds() const throw() { return bounds_; }
  19070. /** Returns the component's bounds, relative to its own origin.
  19071. This is like getBounds(), but returns the rectangle in local co-ordinates, In practice, it'll
  19072. return a rectangle with position (0, 0), and the same size as this component.
  19073. */
  19074. const Rectangle<int> getLocalBounds() const throw();
  19075. /** Returns the region of this component that's not obscured by other, opaque components.
  19076. The RectangleList that is returned represents the area of this component
  19077. which isn't covered by opaque child components.
  19078. If includeSiblings is true, it will also take into account any siblings
  19079. that may be overlapping the component.
  19080. */
  19081. void getVisibleArea (RectangleList& result,
  19082. bool includeSiblings) const;
  19083. /** Returns this component's x co-ordinate relative the the screen's top-left origin.
  19084. @see getX, relativePositionToGlobal
  19085. */
  19086. int getScreenX() const;
  19087. /** Returns this component's y co-ordinate relative the the screen's top-left origin.
  19088. @see getY, relativePositionToGlobal
  19089. */
  19090. int getScreenY() const;
  19091. /** Returns the position of this component's top-left corner relative to the screen's top-left.
  19092. @see getScreenBounds
  19093. */
  19094. const Point<int> getScreenPosition() const;
  19095. /** Returns the bounds of this component, relative to the screen's top-left.
  19096. @see getScreenPosition
  19097. */
  19098. const Rectangle<int> getScreenBounds() const;
  19099. /** Converts a position relative to this component's top-left into a screen co-ordinate.
  19100. @see globalPositionToRelative, relativePositionToOtherComponent
  19101. */
  19102. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition) const;
  19103. /** Converts a screen co-ordinate into a position relative to this component's top-left.
  19104. @see relativePositionToGlobal, relativePositionToOtherComponent
  19105. */
  19106. const Point<int> globalPositionToRelative (const Point<int>& screenPosition) const;
  19107. /** Converts a position relative to this component's top-left into a position
  19108. relative to another component's top-left.
  19109. @see relativePositionToGlobal, globalPositionToRelative
  19110. */
  19111. const Point<int> relativePositionToOtherComponent (const Component* targetComponent,
  19112. const Point<int>& positionRelativeToThis) const;
  19113. /** Moves the component to a new position.
  19114. Changes the component's top-left position (without changing its size).
  19115. The position is relative to the top-left of the component's parent.
  19116. If the component actually moves, this method will make a synchronous call to moved().
  19117. @see setBounds, ComponentListener::componentMovedOrResized
  19118. */
  19119. void setTopLeftPosition (int x, int y);
  19120. /** Moves the component to a new position.
  19121. Changes the position of the component's top-right corner (keeping it the same size).
  19122. The position is relative to the top-left of the component's parent.
  19123. If the component actually moves, this method will make a synchronous call to moved().
  19124. */
  19125. void setTopRightPosition (int x, int y);
  19126. /** Changes the size of the component.
  19127. A synchronous call to resized() will be occur if the size actually changes.
  19128. */
  19129. void setSize (int newWidth, int newHeight);
  19130. /** Changes the component's position and size.
  19131. The co-ordinates are relative to the top-left of the component's parent, or relative
  19132. to the origin of the screen is the component is on the desktop.
  19133. If this method changes the component's top-left position, it will make a synchronous
  19134. call to moved(). If it changes the size, it will also make a call to resized().
  19135. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  19136. */
  19137. void setBounds (int x, int y, int width, int height);
  19138. /** Changes the component's position and size.
  19139. @see setBounds
  19140. */
  19141. void setBounds (const Rectangle<int>& newBounds);
  19142. /** Changes the component's position and size in terms of fractions of its parent's size.
  19143. The values are factors of the parent's size, so for example
  19144. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  19145. width and height of the parent, with its top-left position 20% of
  19146. the way across and down the parent.
  19147. */
  19148. void setBoundsRelative (float proportionalX, float proportionalY,
  19149. float proportionalWidth, float proportionalHeight);
  19150. /** Changes the component's position and size based on the amount of space to leave around it.
  19151. This will position the component within its parent, leaving the specified number of
  19152. pixels around each edge.
  19153. */
  19154. void setBoundsInset (const BorderSize& borders);
  19155. /** Positions the component within a given rectangle, keeping its proportions
  19156. unchanged.
  19157. If onlyReduceInSize is false, the component will be resized to fill as much of the
  19158. rectangle as possible without changing its aspect ratio (the component's
  19159. current size is used to determine its aspect ratio, so a zero-size component
  19160. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  19161. too big to fit inside the rectangle.
  19162. It will then be positioned within the rectangle according to the justification flags
  19163. specified.
  19164. */
  19165. void setBoundsToFit (int x, int y, int width, int height,
  19166. const Justification& justification,
  19167. bool onlyReduceInSize);
  19168. /** Changes the position of the component's centre.
  19169. Leaves the component's size unchanged, but sets the position of its centre
  19170. relative to its parent's top-left.
  19171. */
  19172. void setCentrePosition (int x, int y);
  19173. /** Changes the position of the component's centre.
  19174. Leaves the position unchanged, but positions its centre relative to its
  19175. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  19176. its parent.
  19177. */
  19178. void setCentreRelative (float x, float y);
  19179. /** Changes the component's size and centres it within its parent.
  19180. After changing the size, the component will be moved so that it's
  19181. centred within its parent.
  19182. */
  19183. void centreWithSize (int width, int height);
  19184. /** Returns a proportion of the component's width.
  19185. This is a handy equivalent of (getWidth() * proportion).
  19186. */
  19187. int proportionOfWidth (float proportion) const throw();
  19188. /** Returns a proportion of the component's height.
  19189. This is a handy equivalent of (getHeight() * proportion).
  19190. */
  19191. int proportionOfHeight (float proportion) const throw();
  19192. /** Returns the width of the component's parent.
  19193. If the component has no parent (i.e. if it's on the desktop), this will return
  19194. the width of the screen.
  19195. */
  19196. int getParentWidth() const throw();
  19197. /** Returns the height of the component's parent.
  19198. If the component has no parent (i.e. if it's on the desktop), this will return
  19199. the height of the screen.
  19200. */
  19201. int getParentHeight() const throw();
  19202. /** Returns the screen co-ordinates of the monitor that contains this component.
  19203. If there's only one monitor, this will return its size - if there are multiple
  19204. monitors, it will return the area of the monitor that contains the component's
  19205. centre.
  19206. */
  19207. const Rectangle<int> getParentMonitorArea() const;
  19208. /** Returns the number of child components that this component contains.
  19209. @see getChildComponent, getIndexOfChildComponent
  19210. */
  19211. int getNumChildComponents() const throw();
  19212. /** Returns one of this component's child components, by it index.
  19213. The component with index 0 is at the back of the z-order, the one at the
  19214. front will have index (getNumChildComponents() - 1).
  19215. If the index is out-of-range, this will return a null pointer.
  19216. @see getNumChildComponents, getIndexOfChildComponent
  19217. */
  19218. Component* getChildComponent (int index) const throw();
  19219. /** Returns the index of this component in the list of child components.
  19220. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  19221. values are further towards the front.
  19222. Returns -1 if the component passed-in is not a child of this component.
  19223. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  19224. */
  19225. int getIndexOfChildComponent (const Component* child) const throw();
  19226. /** Adds a child component to this one.
  19227. @param child the new component to add. If the component passed-in is already
  19228. the child of another component, it'll first be removed from that.
  19229. @param zOrder The index in the child-list at which this component should be inserted.
  19230. A value of -1 will insert it in front of the others, 0 is the back.
  19231. @see removeChildComponent, addAndMakeVisible, getChild,
  19232. ComponentListener::componentChildrenChanged
  19233. */
  19234. void addChildComponent (Component* child, int zOrder = -1);
  19235. /** Adds a child component to this one, and also makes the child visible if it isn't.
  19236. Quite a useful function, this is just the same as calling addChildComponent()
  19237. followed by setVisible (true) on the child.
  19238. */
  19239. void addAndMakeVisible (Component* child, int zOrder = -1);
  19240. /** Removes one of this component's child-components.
  19241. If the child passed-in isn't actually a child of this component (either because
  19242. it's invalid or is the child of a different parent), then nothing is done.
  19243. Note that removing a child will not delete it!
  19244. @see addChildComponent, ComponentListener::componentChildrenChanged
  19245. */
  19246. void removeChildComponent (Component* childToRemove);
  19247. /** Removes one of this component's child-components by index.
  19248. This will return a pointer to the component that was removed, or null if
  19249. the index was out-of-range.
  19250. Note that removing a child will not delete it!
  19251. @see addChildComponent, ComponentListener::componentChildrenChanged
  19252. */
  19253. Component* removeChildComponent (int childIndexToRemove);
  19254. /** Removes all this component's children.
  19255. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  19256. */
  19257. void removeAllChildren();
  19258. /** Removes all this component's children, and deletes them.
  19259. @see removeAllChildren
  19260. */
  19261. void deleteAllChildren();
  19262. /** Returns the component which this component is inside.
  19263. If this is the highest-level component or hasn't yet been added to
  19264. a parent, this will return null.
  19265. */
  19266. Component* getParentComponent() const throw() { return parentComponent_; }
  19267. /** Searches the parent components for a component of a specified class.
  19268. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  19269. component that can be dynamically cast to a MyComp, or will return 0 if none
  19270. of the parents are suitable.
  19271. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  19272. */
  19273. template <class TargetClass>
  19274. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  19275. {
  19276. (void) dummyParameter;
  19277. Component* p = parentComponent_;
  19278. while (p != 0)
  19279. {
  19280. TargetClass* target = dynamic_cast <TargetClass*> (p);
  19281. if (target != 0)
  19282. return target;
  19283. p = p->parentComponent_;
  19284. }
  19285. return 0;
  19286. }
  19287. /** Returns the highest-level component which contains this one or its parents.
  19288. This will search upwards in the parent-hierarchy from this component, until it
  19289. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  19290. not yet added to a parent), and will return that.
  19291. */
  19292. Component* getTopLevelComponent() const throw();
  19293. /** Checks whether a component is anywhere inside this component or its children.
  19294. This will recursively check through this components children to see if the
  19295. given component is anywhere inside.
  19296. */
  19297. bool isParentOf (const Component* possibleChild) const throw();
  19298. /** Called to indicate that the component's parents have changed.
  19299. When a component is added or removed from its parent, this method will
  19300. be called on all of its children (recursively - so all children of its
  19301. children will also be called as well).
  19302. Subclasses can override this if they need to react to this in some way.
  19303. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  19304. */
  19305. virtual void parentHierarchyChanged();
  19306. /** Subclasses can use this callback to be told when children are added or removed.
  19307. @see parentHierarchyChanged
  19308. */
  19309. virtual void childrenChanged();
  19310. /** Tests whether a given point inside the component.
  19311. Overriding this method allows you to create components which only intercept
  19312. mouse-clicks within a user-defined area.
  19313. This is called to find out whether a particular x, y co-ordinate is
  19314. considered to be inside the component or not, and is used by methods such
  19315. as contains() and getComponentAt() to work out which component
  19316. the mouse is clicked on.
  19317. Components with custom shapes will probably want to override it to perform
  19318. some more complex hit-testing.
  19319. The default implementation of this method returns either true or false,
  19320. depending on the value that was set by calling setInterceptsMouseClicks() (true
  19321. is the default return value).
  19322. Note that the hit-test region is not related to the opacity with which
  19323. areas of a component are painted.
  19324. Applications should never call hitTest() directly - instead use the
  19325. contains() method, because this will also test for occlusion by the
  19326. component's parent.
  19327. Note that for components on the desktop, this method will be ignored, because it's
  19328. not always possible to implement this behaviour on all platforms.
  19329. @param x the x co-ordinate to test, relative to the left hand edge of this
  19330. component. This value is guaranteed to be greater than or equal to
  19331. zero, and less than the component's width
  19332. @param y the y co-ordinate to test, relative to the top edge of this
  19333. component. This value is guaranteed to be greater than or equal to
  19334. zero, and less than the component's height
  19335. @returns true if the click is considered to be inside the component
  19336. @see setInterceptsMouseClicks, contains
  19337. */
  19338. virtual bool hitTest (int x, int y);
  19339. /** Changes the default return value for the hitTest() method.
  19340. Setting this to false is an easy way to make a component pass its mouse-clicks
  19341. through to the components behind it.
  19342. When a component is created, the default setting for this is true.
  19343. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  19344. return false (or true for child components if allowClicksOnChildComponents
  19345. is true)
  19346. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  19347. components can be clicked on as normal but clicks on this component pass
  19348. straight through; if this is false and allowClicksOnThisComponent
  19349. is false, then neither this component nor any child components can
  19350. be clicked on
  19351. @see hitTest, getInterceptsMouseClicks
  19352. */
  19353. void setInterceptsMouseClicks (bool allowClicksOnThisComponent,
  19354. bool allowClicksOnChildComponents) throw();
  19355. /** Retrieves the current state of the mouse-click interception flags.
  19356. On return, the two parameters are set to the state used in the last call to
  19357. setInterceptsMouseClicks().
  19358. @see setInterceptsMouseClicks
  19359. */
  19360. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  19361. bool& allowsClicksOnChildComponents) const throw();
  19362. /** Returns true if a given point lies within this component or one of its children.
  19363. Never override this method! Use hitTest to create custom hit regions.
  19364. @param x the x co-ordinate to test, relative to this component's left hand edge.
  19365. @param y the y co-ordinate to test, relative to this component's top edge.
  19366. @returns true if the point is within the component's hit-test area, but only if
  19367. that part of the component isn't clipped by its parent component. Note
  19368. that this won't take into account any overlapping sibling components
  19369. which might be in the way - for that, see reallyContains()
  19370. @see hitTest, reallyContains, getComponentAt
  19371. */
  19372. virtual bool contains (int x, int y);
  19373. /** Returns true if a given point lies in this component, taking any overlapping
  19374. siblings into account.
  19375. @param x the x co-ordinate to test, relative to this component's left hand edge.
  19376. @param y the y co-ordinate to test, relative to this component's top edge.
  19377. @param returnTrueIfWithinAChild if the point actually lies within a child of this
  19378. component, this determines the value that will
  19379. be returned.
  19380. @see contains, getComponentAt
  19381. */
  19382. bool reallyContains (int x, int y, bool returnTrueIfWithinAChild);
  19383. /** Returns the component at a certain point within this one.
  19384. @param x the x co-ordinate to test, relative to this component's left hand edge.
  19385. @param y the y co-ordinate to test, relative to this component's top edge.
  19386. @returns the component that is at this position - which may be 0, this component,
  19387. or one of its children. Note that overlapping siblings that might actually
  19388. be in the way are not taken into account by this method - to account for these,
  19389. instead call getComponentAt on the top-level parent of this component.
  19390. @see hitTest, contains, reallyContains
  19391. */
  19392. Component* getComponentAt (int x, int y);
  19393. /** Returns the component at a certain point within this one.
  19394. @param position the co-ordinates to test, relative to this component's top-left.
  19395. @returns the component that is at this position - which may be 0, this component,
  19396. or one of its children. Note that overlapping siblings that might actually
  19397. be in the way are not taken into account by this method - to account for these,
  19398. instead call getComponentAt on the top-level parent of this component.
  19399. @see hitTest, contains, reallyContains
  19400. */
  19401. Component* getComponentAt (const Point<int>& position);
  19402. /** Marks the whole component as needing to be redrawn.
  19403. Calling this will not do any repainting immediately, but will mark the component
  19404. as 'dirty'. At some point in the near future the operating system will send a paint
  19405. message, which will redraw all the dirty regions of all components.
  19406. There's no guarantee about how soon after calling repaint() the redraw will actually
  19407. happen, and other queued events may be delivered before a redraw is done.
  19408. If the setBufferedToImage() method has been used to cause this component
  19409. to use a buffer, the repaint() call will invalidate the component's buffer.
  19410. To redraw just a subsection of the component rather than the whole thing,
  19411. use the repaint (int, int, int, int) method.
  19412. @see paint
  19413. */
  19414. void repaint();
  19415. /** Marks a subsection of this component as needing to be redrawn.
  19416. Calling this will not do any repainting immediately, but will mark the given region
  19417. of the component as 'dirty'. At some point in the near future the operating system
  19418. will send a paint message, which will redraw all the dirty regions of all components.
  19419. There's no guarantee about how soon after calling repaint() the redraw will actually
  19420. happen, and other queued events may be delivered before a redraw is done.
  19421. The region that is passed in will be clipped to keep it within the bounds of this
  19422. component.
  19423. @see repaint()
  19424. */
  19425. void repaint (int x, int y, int width, int height);
  19426. /** Marks a subsection of this component as needing to be redrawn.
  19427. Calling this will not do any repainting immediately, but will mark the given region
  19428. of the component as 'dirty'. At some point in the near future the operating system
  19429. will send a paint message, which will redraw all the dirty regions of all components.
  19430. There's no guarantee about how soon after calling repaint() the redraw will actually
  19431. happen, and other queued events may be delivered before a redraw is done.
  19432. The region that is passed in will be clipped to keep it within the bounds of this
  19433. component.
  19434. @see repaint()
  19435. */
  19436. void repaint (const Rectangle<int>& area);
  19437. /** Makes the component use an internal buffer to optimise its redrawing.
  19438. Setting this flag to true will cause the component to allocate an
  19439. internal buffer into which it paints itself, so that when asked to
  19440. redraw itself, it can use this buffer rather than actually calling the
  19441. paint() method.
  19442. The buffer is kept until the repaint() method is called directly on
  19443. this component (or until it is resized), when the image is invalidated
  19444. and then redrawn the next time the component is painted.
  19445. Note that only the drawing that happens within the component's paint()
  19446. method is drawn into the buffer, it's child components are not buffered, and
  19447. nor is the paintOverChildren() method.
  19448. @see repaint, paint, createComponentSnapshot
  19449. */
  19450. void setBufferedToImage (bool shouldBeBuffered);
  19451. /** Generates a snapshot of part of this component.
  19452. This will return a new Image, the size of the rectangle specified,
  19453. containing a snapshot of the specified area of the component and all
  19454. its children.
  19455. The image may or may not have an alpha-channel, depending on whether the
  19456. image is opaque or not.
  19457. If the clipImageToComponentBounds parameter is true and the area is greater than
  19458. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  19459. then parts of the component beyond its bounds can be drawn.
  19460. @see paintEntireComponent
  19461. */
  19462. const Image createComponentSnapshot (const Rectangle<int>& areaToGrab,
  19463. bool clipImageToComponentBounds = true);
  19464. /** Draws this component and all its subcomponents onto the specified graphics
  19465. context.
  19466. You should very rarely have to use this method, it's simply there in case you need
  19467. to draw a component with a custom graphics context for some reason, e.g. for
  19468. creating a snapshot of the component.
  19469. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  19470. on its children in order to render the entire tree.
  19471. The graphics context may be left in an undefined state after this method returns,
  19472. so you may need to reset it if you're going to use it again.
  19473. */
  19474. void paintEntireComponent (Graphics& context);
  19475. /** Adds an effect filter to alter the component's appearance.
  19476. When a component has an effect filter set, then this is applied to the
  19477. results of its paint() method. There are a few preset effects, such as
  19478. a drop-shadow or glow, but they can be user-defined as well.
  19479. The effect that is passed in will not be deleted by the component - the
  19480. caller must take care of deleting it.
  19481. To remove an effect from a component, pass a null pointer in as the parameter.
  19482. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  19483. */
  19484. void setComponentEffect (ImageEffectFilter* newEffect);
  19485. /** Returns the current component effect.
  19486. @see setComponentEffect
  19487. */
  19488. ImageEffectFilter* getComponentEffect() const throw() { return effect_; }
  19489. /** Finds the appropriate look-and-feel to use for this component.
  19490. If the component hasn't had a look-and-feel explicitly set, this will
  19491. return the parent's look-and-feel, or just the default one if there's no
  19492. parent.
  19493. @see setLookAndFeel, lookAndFeelChanged
  19494. */
  19495. LookAndFeel& getLookAndFeel() const throw();
  19496. /** Sets the look and feel to use for this component.
  19497. This will also change the look and feel for any child components that haven't
  19498. had their look set explicitly.
  19499. The object passed in will not be deleted by the component, so it's the caller's
  19500. responsibility to manage it. It may be used at any time until this component
  19501. has been deleted.
  19502. Calling this method will also invoke the sendLookAndFeelChange() method.
  19503. @see getLookAndFeel, lookAndFeelChanged
  19504. */
  19505. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  19506. /** Called to let the component react to a change in the look-and-feel setting.
  19507. When the look-and-feel is changed for a component, this will be called in
  19508. all its child components, recursively.
  19509. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  19510. an application uses a LookAndFeel class that might have changed internally.
  19511. @see sendLookAndFeelChange, getLookAndFeel
  19512. */
  19513. virtual void lookAndFeelChanged();
  19514. /** Calls the lookAndFeelChanged() method in this component and all its children.
  19515. This will recurse through the children and their children, calling lookAndFeelChanged()
  19516. on them all.
  19517. @see lookAndFeelChanged
  19518. */
  19519. void sendLookAndFeelChange();
  19520. /** Indicates whether any parts of the component might be transparent.
  19521. Components that always paint all of their contents with solid colour and
  19522. thus completely cover any components behind them should use this method
  19523. to tell the repaint system that they are opaque.
  19524. This information is used to optimise drawing, because it means that
  19525. objects underneath opaque windows don't need to be painted.
  19526. By default, components are considered transparent, unless this is used to
  19527. make it otherwise.
  19528. @see isOpaque, getVisibleArea
  19529. */
  19530. void setOpaque (bool shouldBeOpaque);
  19531. /** Returns true if no parts of this component are transparent.
  19532. @returns the value that was set by setOpaque, (the default being false)
  19533. @see setOpaque
  19534. */
  19535. bool isOpaque() const throw();
  19536. /** Indicates whether the component should be brought to the front when clicked.
  19537. Setting this flag to true will cause the component to be brought to the front
  19538. when the mouse is clicked somewhere inside it or its child components.
  19539. Note that a top-level desktop window might still be brought to the front by the
  19540. operating system when it's clicked, depending on how the OS works.
  19541. By default this is set to false.
  19542. @see setMouseClickGrabsKeyboardFocus
  19543. */
  19544. void setBroughtToFrontOnMouseClick (bool shouldBeBroughtToFront) throw();
  19545. /** Indicates whether the component should be brought to the front when clicked-on.
  19546. @see setBroughtToFrontOnMouseClick
  19547. */
  19548. bool isBroughtToFrontOnMouseClick() const throw();
  19549. // Keyboard focus methods
  19550. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  19551. By default components aren't actually interested in gaining the
  19552. focus, but this method can be used to turn this on.
  19553. See the grabKeyboardFocus() method for details about the way a component
  19554. is chosen to receive the focus.
  19555. @see grabKeyboardFocus, getWantsKeyboardFocus
  19556. */
  19557. void setWantsKeyboardFocus (bool wantsFocus) throw();
  19558. /** Returns true if the component is interested in getting keyboard focus.
  19559. This returns the flag set by setWantsKeyboardFocus(). The default
  19560. setting is false.
  19561. @see setWantsKeyboardFocus
  19562. */
  19563. bool getWantsKeyboardFocus() const throw();
  19564. /** Chooses whether a click on this component automatically grabs the focus.
  19565. By default this is set to true, but you might want a component which can
  19566. be focused, but where you don't want the user to be able to affect it directly
  19567. by clicking.
  19568. */
  19569. void setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus);
  19570. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  19571. See setMouseClickGrabsKeyboardFocus() for more info.
  19572. */
  19573. bool getMouseClickGrabsKeyboardFocus() const throw();
  19574. /** Tries to give keyboard focus to this component.
  19575. When the user clicks on a component or its grabKeyboardFocus()
  19576. method is called, the following procedure is used to work out which
  19577. component should get it:
  19578. - if the component that was clicked on actually wants focus (as indicated
  19579. by calling getWantsKeyboardFocus), it gets it.
  19580. - if the component itself doesn't want focus, it will try to pass it
  19581. on to whichever of its children is the default component, as determined by
  19582. KeyboardFocusTraverser::getDefaultComponent()
  19583. - if none of its children want focus at all, it will pass it up to its
  19584. parent instead, unless it's a top-level component without a parent,
  19585. in which case it just takes the focus itself.
  19586. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  19587. getCurrentlyFocusedComponent, focusGained, focusLost,
  19588. keyPressed, keyStateChanged
  19589. */
  19590. void grabKeyboardFocus();
  19591. /** Returns true if this component currently has the keyboard focus.
  19592. @param trueIfChildIsFocused if this is true, then the method returns true if
  19593. either this component or any of its children (recursively)
  19594. have the focus. If false, the method only returns true if
  19595. this component has the focus.
  19596. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  19597. focusGained, focusLost
  19598. */
  19599. bool hasKeyboardFocus (bool trueIfChildIsFocused) const;
  19600. /** Returns the component that currently has the keyboard focus.
  19601. @returns the focused component, or null if nothing is focused.
  19602. */
  19603. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  19604. /** Tries to move the keyboard focus to one of this component's siblings.
  19605. This will try to move focus to either the next or previous component. (This
  19606. is the method that is used when shifting focus by pressing the tab key).
  19607. Components for which getWantsKeyboardFocus() returns false are not looked at.
  19608. @param moveToNext if true, the focus will move forwards; if false, it will
  19609. move backwards
  19610. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  19611. */
  19612. void moveKeyboardFocusToSibling (bool moveToNext);
  19613. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  19614. which focus should be passed from this component.
  19615. The default implementation of this method will return a default
  19616. KeyboardFocusTraverser if this component is a focus container (as determined
  19617. by the setFocusContainer() method). If the component isn't a focus
  19618. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  19619. If you overrride this to return a custom KeyboardFocusTraverser, then
  19620. this component and all its sub-components will use the new object to
  19621. make their focusing decisions.
  19622. The method should return a new object, which the caller is required to
  19623. delete when no longer needed.
  19624. */
  19625. virtual KeyboardFocusTraverser* createFocusTraverser();
  19626. /** Returns the focus order of this component, if one has been specified.
  19627. By default components don't have a focus order - in that case, this
  19628. will return 0. Lower numbers indicate that the component will be
  19629. earlier in the focus traversal order.
  19630. To change the order, call setExplicitFocusOrder().
  19631. The focus order may be used by the KeyboardFocusTraverser class as part of
  19632. its algorithm for deciding the order in which components should be traversed.
  19633. See the KeyboardFocusTraverser class for more details on this.
  19634. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  19635. */
  19636. int getExplicitFocusOrder() const;
  19637. /** Sets the index used in determining the order in which focusable components
  19638. should be traversed.
  19639. A value of 0 or less is taken to mean that no explicit order is wanted, and
  19640. that traversal should use other factors, like the component's position.
  19641. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  19642. */
  19643. void setExplicitFocusOrder (int newFocusOrderIndex);
  19644. /** Indicates whether this component is a parent for components that can have
  19645. their focus traversed.
  19646. This flag is used by the default implementation of the createFocusTraverser()
  19647. method, which uses the flag to find the first parent component (of the currently
  19648. focused one) which wants to be a focus container.
  19649. So using this method to set the flag to 'true' causes this component to
  19650. act as the top level within which focus is passed around.
  19651. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  19652. */
  19653. void setFocusContainer (bool shouldBeFocusContainer) throw();
  19654. /** Returns true if this component has been marked as a focus container.
  19655. See setFocusContainer() for more details.
  19656. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  19657. */
  19658. bool isFocusContainer() const throw();
  19659. /** Returns true if the component (and all its parents) are enabled.
  19660. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  19661. what difference this makes to the component depends on the type. E.g. buttons
  19662. and sliders will choose to draw themselves differently, etc.
  19663. Note that if one of this component's parents is disabled, this will always
  19664. return false, even if this component itself is enabled.
  19665. @see setEnabled, enablementChanged
  19666. */
  19667. bool isEnabled() const throw();
  19668. /** Enables or disables this component.
  19669. Disabling a component will also cause all of its child components to become
  19670. disabled.
  19671. Similarly, enabling a component which is inside a disabled parent
  19672. component won't make any difference until the parent is re-enabled.
  19673. @see isEnabled, enablementChanged
  19674. */
  19675. void setEnabled (bool shouldBeEnabled);
  19676. /** Callback to indicate that this component has been enabled or disabled.
  19677. This can be triggered by one of the component's parent components
  19678. being enabled or disabled, as well as changes to the component itself.
  19679. The default implementation of this method does nothing; your class may
  19680. wish to repaint itself or something when this happens.
  19681. @see setEnabled, isEnabled
  19682. */
  19683. virtual void enablementChanged();
  19684. /** Changes the mouse cursor shape to use when the mouse is over this component.
  19685. Note that the cursor set by this method can be overridden by the getMouseCursor
  19686. method.
  19687. @see MouseCursor
  19688. */
  19689. void setMouseCursor (const MouseCursor& cursorType);
  19690. /** Returns the mouse cursor shape to use when the mouse is over this component.
  19691. The default implementation will return the cursor that was set by setCursor()
  19692. but can be overridden for more specialised purposes, e.g. returning different
  19693. cursors depending on the mouse position.
  19694. @see MouseCursor
  19695. */
  19696. virtual const MouseCursor getMouseCursor();
  19697. /** Forces the current mouse cursor to be updated.
  19698. If you're overriding the getMouseCursor() method to control which cursor is
  19699. displayed, then this will only be checked each time the user moves the mouse. So
  19700. if you want to force the system to check that the cursor being displayed is
  19701. up-to-date (even if the mouse is just sitting there), call this method.
  19702. This isn't needed if you're only using setMouseCursor().
  19703. */
  19704. void updateMouseCursor() const;
  19705. /** Components can override this method to draw their content.
  19706. The paint() method gets called when a region of a component needs redrawing,
  19707. either because the component's repaint() method has been called, or because
  19708. something has happened on the screen that means a section of a window needs
  19709. to be redrawn.
  19710. Any child components will draw themselves over whatever this method draws. If
  19711. you need to paint over the top of your child components, you can also implement
  19712. the paintOverChildren() method to do this.
  19713. If you want to cause a component to redraw itself, this is done asynchronously -
  19714. calling the repaint() method marks a region of the component as "dirty", and the
  19715. paint() method will automatically be called sometime later, by the message thread,
  19716. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  19717. you never redraw something synchronously.
  19718. You should never need to call this method directly - to take a snapshot of the
  19719. component you could use createComponentSnapshot() or paintEntireComponent().
  19720. @param g the graphics context that must be used to do the drawing operations.
  19721. @see repaint, paintOverChildren, Graphics
  19722. */
  19723. virtual void paint (Graphics& g);
  19724. /** Components can override this method to draw over the top of their children.
  19725. For most drawing operations, it's better to use the normal paint() method,
  19726. but if you need to overlay something on top of the children, this can be
  19727. used.
  19728. @see paint, Graphics
  19729. */
  19730. virtual void paintOverChildren (Graphics& g);
  19731. /** Called when the mouse moves inside this component.
  19732. If the mouse button isn't pressed and the mouse moves over a component,
  19733. this will be called to let the component react to this.
  19734. A component will always get a mouseEnter callback before a mouseMove.
  19735. @param e details about the position and status of the mouse event
  19736. @see mouseEnter, mouseExit, mouseDrag, contains
  19737. */
  19738. virtual void mouseMove (const MouseEvent& e);
  19739. /** Called when the mouse first enters this component.
  19740. If the mouse button isn't pressed and the mouse moves into a component,
  19741. this will be called to let the component react to this.
  19742. When the mouse button is pressed and held down while being moved in
  19743. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  19744. mouseDrag messages are sent to the component that the mouse was originally
  19745. clicked on, until the button is released.
  19746. If you're writing a component that needs to repaint itself when the mouse
  19747. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  19748. method.
  19749. @param e details about the position and status of the mouse event
  19750. @see mouseExit, mouseDrag, mouseMove, contains
  19751. */
  19752. virtual void mouseEnter (const MouseEvent& e);
  19753. /** Called when the mouse moves out of this component.
  19754. This will be called when the mouse moves off the edge of this
  19755. component.
  19756. If the mouse button was pressed, and it was then dragged off the
  19757. edge of the component and released, then this callback will happen
  19758. when the button is released, after the mouseUp callback.
  19759. If you're writing a component that needs to repaint itself when the mouse
  19760. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  19761. method.
  19762. @param e details about the position and status of the mouse event
  19763. @see mouseEnter, mouseDrag, mouseMove, contains
  19764. */
  19765. virtual void mouseExit (const MouseEvent& e);
  19766. /** Called when a mouse button is pressed while it's over this component.
  19767. The MouseEvent object passed in contains lots of methods for finding out
  19768. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  19769. were held down at the time.
  19770. Once a button is held down, the mouseDrag method will be called when the
  19771. mouse moves, until the button is released.
  19772. @param e details about the position and status of the mouse event
  19773. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  19774. */
  19775. virtual void mouseDown (const MouseEvent& e);
  19776. /** Called when the mouse is moved while a button is held down.
  19777. When a mouse button is pressed inside a component, that component
  19778. receives mouseDrag callbacks each time the mouse moves, even if the
  19779. mouse strays outside the component's bounds.
  19780. If you want to be able to drag things off the edge of a component
  19781. and have the component scroll when you get to the edges, the
  19782. beginDragAutoRepeat() method might be useful.
  19783. @param e details about the position and status of the mouse event
  19784. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  19785. */
  19786. virtual void mouseDrag (const MouseEvent& e);
  19787. /** Called when a mouse button is released.
  19788. A mouseUp callback is sent to the component in which a button was pressed
  19789. even if the mouse is actually over a different component when the
  19790. button is released.
  19791. The MouseEvent object passed in contains lots of methods for finding out
  19792. which buttons were down just before they were released.
  19793. @param e details about the position and status of the mouse event
  19794. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  19795. */
  19796. virtual void mouseUp (const MouseEvent& e);
  19797. /** Called when a mouse button has been double-clicked in this component.
  19798. The MouseEvent object passed in contains lots of methods for finding out
  19799. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  19800. were held down at the time.
  19801. For altering the time limit used to detect double-clicks,
  19802. see MouseEvent::setDoubleClickTimeout.
  19803. @param e details about the position and status of the mouse event
  19804. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  19805. MouseEvent::getDoubleClickTimeout
  19806. */
  19807. virtual void mouseDoubleClick (const MouseEvent& e);
  19808. /** Called when the mouse-wheel is moved.
  19809. This callback is sent to the component that the mouse is over when the
  19810. wheel is moved.
  19811. If not overridden, the component will forward this message to its parent, so
  19812. that parent components can collect mouse-wheel messages that happen to
  19813. child components which aren't interested in them.
  19814. @param e details about the position and status of the mouse event
  19815. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  19816. value means the wheel has been pushed to the right, negative means it
  19817. was pushed to the left
  19818. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  19819. value means the wheel has been pushed upwards, negative means it
  19820. was pushed downwards
  19821. */
  19822. virtual void mouseWheelMove (const MouseEvent& e,
  19823. float wheelIncrementX,
  19824. float wheelIncrementY);
  19825. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  19826. next mouse-drag operation.
  19827. This allows you to make sure that mouseDrag() events sent continuously, even
  19828. when the mouse isn't moving. This can be useful for things like auto-scrolling
  19829. components when the mouse is near an edge.
  19830. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  19831. minimum interval between consecutive mouse drag callbacks. The callbacks
  19832. will continue until the mouse is released, and then the interval will be reset,
  19833. so you need to make sure it's called every time you begin a drag event. If it
  19834. is called when the mouse isn't actually being pressed, it will apply to the next
  19835. mouse-drag operation that happens.
  19836. Passing an interval of 0 or less will cancel the auto-repeat.
  19837. @see mouseDrag
  19838. */
  19839. static void beginDragAutoRepeat (int millisecondIntervalBetweenCallbacks);
  19840. /** Causes automatic repaints when the mouse enters or exits this component.
  19841. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  19842. on the component, it will trigger a repaint.
  19843. This is handy for things like buttons that need to draw themselves differently when
  19844. the mouse moves over them, and it avoids having to override all the different mouse
  19845. callbacks and call repaint().
  19846. @see mouseEnter, mouseExit, mouseDown, mouseUp
  19847. */
  19848. void setRepaintsOnMouseActivity (bool shouldRepaint) throw();
  19849. /** Registers a listener to be told when mouse events occur in this component.
  19850. If you need to get informed about mouse events in a component but can't or
  19851. don't want to override its methods, you can attach any number of listeners
  19852. to the component, and these will get told about the events in addition to
  19853. the component's own callbacks being called.
  19854. Note that a MouseListener can also be attached to more than one component.
  19855. @param newListener the listener to register
  19856. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  19857. for events that happen to any child component
  19858. within this component, including deeply-nested
  19859. child components. If false, it will only be
  19860. told about events that this component handles.
  19861. @see MouseListener, removeMouseListener
  19862. */
  19863. void addMouseListener (MouseListener* newListener,
  19864. bool wantsEventsForAllNestedChildComponents);
  19865. /** Deregisters a mouse listener.
  19866. @see addMouseListener, MouseListener
  19867. */
  19868. void removeMouseListener (MouseListener* listenerToRemove);
  19869. /** Adds a listener that wants to hear about keypresses that this component receives.
  19870. The listeners that are registered with a component are called by its keyPressed() or
  19871. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  19872. If you add an object as a key listener, be careful to remove it when the object
  19873. is deleted, or the component will be left with a dangling pointer.
  19874. @see keyPressed, keyStateChanged, removeKeyListener
  19875. */
  19876. void addKeyListener (KeyListener* newListener);
  19877. /** Removes a previously-registered key listener.
  19878. @see addKeyListener
  19879. */
  19880. void removeKeyListener (KeyListener* listenerToRemove);
  19881. /** Called when a key is pressed.
  19882. When a key is pressed, the component that has the keyboard focus will have this
  19883. method called. Remember that a component will only be given the focus if its
  19884. setWantsKeyboardFocus() method has been used to enable this.
  19885. If your implementation returns true, the event will be consumed and not passed
  19886. on to any other listeners. If it returns false, the key will be passed to any
  19887. KeyListeners that have been registered with this component. As soon as one of these
  19888. returns true, the process will stop, but if they all return false, the event will
  19889. be passed upwards to this component's parent, and so on.
  19890. The default implementation of this method does nothing and returns false.
  19891. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  19892. */
  19893. virtual bool keyPressed (const KeyPress& key);
  19894. /** Called when a key is pressed or released.
  19895. Whenever a key on the keyboard is pressed or released (including modifier keys
  19896. like shift and ctrl), this method will be called on the component that currently
  19897. has the keyboard focus. Remember that a component will only be given the focus if
  19898. its setWantsKeyboardFocus() method has been used to enable this.
  19899. If your implementation returns true, the event will be consumed and not passed
  19900. on to any other listeners. If it returns false, then any KeyListeners that have
  19901. been registered with this component will have their keyStateChanged methods called.
  19902. As soon as one of these returns true, the process will stop, but if they all return
  19903. false, the event will be passed upwards to this component's parent, and so on.
  19904. The default implementation of this method does nothing and returns false.
  19905. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  19906. method.
  19907. @param isKeyDown true if a key has been pressed; false if it has been released
  19908. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  19909. */
  19910. virtual bool keyStateChanged (bool isKeyDown);
  19911. /** Called when a modifier key is pressed or released.
  19912. Whenever the shift, control, alt or command keys are pressed or released,
  19913. this method will be called on the component that currently has the keyboard focus.
  19914. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  19915. method has been used to enable this.
  19916. The default implementation of this method actually calls its parent's modifierKeysChanged
  19917. method, so that focused components which aren't interested in this will give their
  19918. parents a chance to act on the event instead.
  19919. @see keyStateChanged, ModifierKeys
  19920. */
  19921. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  19922. /** Enumeration used by the focusChanged() and focusLost() methods. */
  19923. enum FocusChangeType
  19924. {
  19925. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  19926. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  19927. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  19928. };
  19929. /** Called to indicate that this component has just acquired the keyboard focus.
  19930. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  19931. */
  19932. virtual void focusGained (FocusChangeType cause);
  19933. /** Called to indicate that this component has just lost the keyboard focus.
  19934. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  19935. */
  19936. virtual void focusLost (FocusChangeType cause);
  19937. /** Called to indicate that one of this component's children has been focused or unfocused.
  19938. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  19939. changed. It happens when focus moves from one of this component's children (at any depth)
  19940. to a component that isn't contained in this one, (or vice-versa).
  19941. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  19942. */
  19943. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  19944. /** Returns true if the mouse is currently over this component.
  19945. If the mouse isn't over the component, this will return false, even if the
  19946. mouse is currently being dragged - so you can use this in your mouseDrag
  19947. method to find out whether it's really over the component or not.
  19948. Note that when the mouse button is being held down, then the only component
  19949. for which this method will return true is the one that was originally
  19950. clicked on.
  19951. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  19952. */
  19953. bool isMouseOver() const throw();
  19954. /** Returns true if the mouse button is currently held down in this component.
  19955. Note that this is a test to see whether the mouse is being pressed in this
  19956. component, so it'll return false if called on component A when the mouse
  19957. is actually being dragged in component B.
  19958. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  19959. */
  19960. bool isMouseButtonDown() const throw();
  19961. /** True if the mouse is over this component, or if it's being dragged in this component.
  19962. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  19963. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  19964. */
  19965. bool isMouseOverOrDragging() const throw();
  19966. /** Returns true if a mouse button is currently down.
  19967. Unlike isMouseButtonDown, this will test the current state of the
  19968. buttons without regard to which component (if any) it has been
  19969. pressed in.
  19970. @see isMouseButtonDown, ModifierKeys
  19971. */
  19972. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  19973. /** Returns the mouse's current position, relative to this component.
  19974. The co-ordinates are relative to the component's top-left corner.
  19975. */
  19976. const Point<int> getMouseXYRelative() const;
  19977. /** Called when this component's size has been changed.
  19978. A component can implement this method to do things such as laying out its
  19979. child components when its width or height changes.
  19980. The method is called synchronously as a result of the setBounds or setSize
  19981. methods, so repeatedly changing a components size will repeatedly call its
  19982. resized method (unlike things like repainting, where multiple calls to repaint
  19983. are coalesced together).
  19984. If the component is a top-level window on the desktop, its size could also
  19985. be changed by operating-system factors beyond the application's control.
  19986. @see moved, setSize
  19987. */
  19988. virtual void resized();
  19989. /** Called when this component's position has been changed.
  19990. This is called when the position relative to its parent changes, not when
  19991. its absolute position on the screen changes (so it won't be called for
  19992. all child components when a parent component is moved).
  19993. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  19994. or any of the other repositioning methods, and like resized(), it will be
  19995. called each time those methods are called.
  19996. If the component is a top-level window on the desktop, its position could also
  19997. be changed by operating-system factors beyond the application's control.
  19998. @see resized, setBounds
  19999. */
  20000. virtual void moved();
  20001. /** Called when one of this component's children is moved or resized.
  20002. If the parent wants to know about changes to its immediate children (not
  20003. to children of its children), this is the method to override.
  20004. @see moved, resized, parentSizeChanged
  20005. */
  20006. virtual void childBoundsChanged (Component* child);
  20007. /** Called when this component's immediate parent has been resized.
  20008. If the component is a top-level window, this indicates that the screen size
  20009. has changed.
  20010. @see childBoundsChanged, moved, resized
  20011. */
  20012. virtual void parentSizeChanged();
  20013. /** Called when this component has been moved to the front of its siblings.
  20014. The component may have been brought to the front by the toFront() method, or
  20015. by the operating system if it's a top-level window.
  20016. @see toFront
  20017. */
  20018. virtual void broughtToFront();
  20019. /** Adds a listener to be told about changes to the component hierarchy or position.
  20020. Component listeners get called when this component's size, position or children
  20021. change - see the ComponentListener class for more details.
  20022. @param newListener the listener to register - if this is already registered, it
  20023. will be ignored.
  20024. @see ComponentListener, removeComponentListener
  20025. */
  20026. void addComponentListener (ComponentListener* newListener);
  20027. /** Removes a component listener.
  20028. @see addComponentListener
  20029. */
  20030. void removeComponentListener (ComponentListener* listenerToRemove);
  20031. /** Dispatches a numbered message to this component.
  20032. This is a quick and cheap way of allowing simple asynchronous messages to
  20033. be sent to components. It's also safe, because if the component that you
  20034. send the message to is a null or dangling pointer, this won't cause an error.
  20035. The command ID is later delivered to the component's handleCommandMessage() method by
  20036. the application's message queue.
  20037. @see handleCommandMessage
  20038. */
  20039. void postCommandMessage (int commandId);
  20040. /** Called to handle a command that was sent by postCommandMessage().
  20041. This is called by the message thread when a command message arrives, and
  20042. the component can override this method to process it in any way it needs to.
  20043. @see postCommandMessage
  20044. */
  20045. virtual void handleCommandMessage (int commandId);
  20046. /** Runs a component modally, waiting until the loop terminates.
  20047. This method first makes the component visible, brings it to the front and
  20048. gives it the keyboard focus.
  20049. It then runs a loop, dispatching messages from the system message queue, but
  20050. blocking all mouse or keyboard messages from reaching any components other
  20051. than this one and its children.
  20052. This loop continues until the component's exitModalState() method is called (or
  20053. the component is deleted), and then this method returns, returning the value
  20054. passed into exitModalState().
  20055. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  20056. isCurrentlyBlockedByAnotherModalComponent, MessageManager::dispatchNextMessage
  20057. */
  20058. int runModalLoop();
  20059. /** Puts the component into a modal state.
  20060. This makes the component modal, so that messages are blocked from reaching
  20061. any components other than this one and its children, but unlike runModalLoop(),
  20062. this method returns immediately.
  20063. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  20064. get the focus, which is usually what you'll want it to do. If not, it will leave
  20065. the focus unchanged.
  20066. @see exitModalState, runModalLoop
  20067. */
  20068. void enterModalState (bool takeKeyboardFocus = true);
  20069. /** Ends a component's modal state.
  20070. If this component is currently modal, this will turn of its modalness, and return
  20071. a value to the runModalLoop() method that might have be running its modal loop.
  20072. @see runModalLoop, enterModalState, isCurrentlyModal
  20073. */
  20074. void exitModalState (int returnValue);
  20075. /** Returns true if this component is the modal one.
  20076. It's possible to have nested modal components, e.g. a pop-up dialog box
  20077. that launches another pop-up, but this will only return true for
  20078. the one at the top of the stack.
  20079. @see getCurrentlyModalComponent
  20080. */
  20081. bool isCurrentlyModal() const throw();
  20082. /** Returns the number of components that are currently in a modal state.
  20083. @see getCurrentlyModalComponent
  20084. */
  20085. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() throw();
  20086. /** Returns one of the components that are currently modal.
  20087. The index specifies which of the possible modal components to return. The order
  20088. of the components in this list is the reverse of the order in which they became
  20089. modal - so the component at index 0 is always the active component, and the others
  20090. are progressively earlier ones that are themselves now blocked by later ones.
  20091. @returns the modal component, or null if no components are modal (or if the
  20092. index is out of range)
  20093. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  20094. */
  20095. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) throw();
  20096. /** Checks whether there's a modal component somewhere that's stopping this one
  20097. from receiving messages.
  20098. If there is a modal component, its canModalEventBeSentToComponent() method
  20099. will be called to see if it will still allow this component to receive events.
  20100. @see runModalLoop, getCurrentlyModalComponent
  20101. */
  20102. bool isCurrentlyBlockedByAnotherModalComponent() const;
  20103. /** When a component is modal, this callback allows it to choose which other
  20104. components can still receive events.
  20105. When a modal component is active and the user clicks on a non-modal component,
  20106. this method is called on the modal component, and if it returns true, the
  20107. event is allowed to reach its target. If it returns false, the event is blocked
  20108. and the inputAttemptWhenModal() callback is made.
  20109. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  20110. implementation just returns false in all cases.
  20111. */
  20112. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  20113. /** Called when the user tries to click on a component that is blocked by another
  20114. modal component.
  20115. When a component is modal and the user clicks on one of the other components,
  20116. the modal component will receive this callback.
  20117. The default implementation of this method will play a beep, and bring the currently
  20118. modal component to the front, but it can be overridden to do other tasks.
  20119. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  20120. */
  20121. virtual void inputAttemptWhenModal();
  20122. /** Returns the set of properties that belong to this component.
  20123. Each component has a NamedValueSet object which you can use to attach arbitrary
  20124. items of data to it.
  20125. */
  20126. NamedValueSet& getProperties() throw() { return properties; }
  20127. /** Returns the set of properties that belong to this component.
  20128. Each component has a NamedValueSet object which you can use to attach arbitrary
  20129. items of data to it.
  20130. */
  20131. const NamedValueSet& getProperties() const throw() { return properties; }
  20132. /** Looks for a colour that has been registered with the given colour ID number.
  20133. If a colour has been set for this ID number using setColour(), then it is
  20134. returned. If none has been set, the method will try calling the component's
  20135. LookAndFeel class's findColour() method. If none has been registered with the
  20136. look-and-feel either, it will just return black.
  20137. The colour IDs for various purposes are stored as enums in the components that
  20138. they are relevent to - for an example, see Slider::ColourIds,
  20139. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  20140. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  20141. */
  20142. const Colour findColour (int colourId, bool inheritFromParent = false) const;
  20143. /** Registers a colour to be used for a particular purpose.
  20144. Changing a colour will cause a synchronous callback to the colourChanged()
  20145. method, which your component can override if it needs to do something when
  20146. colours are altered.
  20147. For more details about colour IDs, see the comments for findColour().
  20148. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  20149. */
  20150. void setColour (int colourId, const Colour& colour);
  20151. /** If a colour has been set with setColour(), this will remove it.
  20152. This allows you to make a colour revert to its default state.
  20153. */
  20154. void removeColour (int colourId);
  20155. /** Returns true if the specified colour ID has been explicitly set for this
  20156. component using the setColour() method.
  20157. */
  20158. bool isColourSpecified (int colourId) const;
  20159. /** This looks for any colours that have been specified for this component,
  20160. and copies them to the specified target component.
  20161. */
  20162. void copyAllExplicitColoursTo (Component& target) const;
  20163. /** This method is called when a colour is changed by the setColour() method.
  20164. @see setColour, findColour
  20165. */
  20166. virtual void colourChanged();
  20167. /** Returns the underlying native window handle for this component.
  20168. This is platform-dependent and strictly for power-users only!
  20169. */
  20170. void* getWindowHandle() const;
  20171. /** When created, each component is given a number to uniquely identify it.
  20172. The number is incremented each time a new component is created, so it's a more
  20173. unique way of identifying a component than using its memory location (which
  20174. may be reused after the component is deleted, of course).
  20175. */
  20176. uint32 getComponentUID() const throw() { return componentUID; }
  20177. /** Holds a pointer to some type of Component, which automatically becomes null if
  20178. the component is deleted.
  20179. If you're using a component which may be deleted by another event that's outside
  20180. of your control, use a SafePointer instead of a normal pointer to refer to it,
  20181. and you can test whether it's null before using it to see if something has deleted
  20182. it.
  20183. The ComponentType typedef must be Component, or some subclass of Component.
  20184. Note that this class isn't thread-safe, and assumes that all the code that uses
  20185. it is running on the message thread.
  20186. */
  20187. template <class ComponentType>
  20188. class SafePointer : private ComponentListener
  20189. {
  20190. public:
  20191. /** Creates a null SafePointer. */
  20192. SafePointer() : comp (0) {}
  20193. /** Creates a SafePointer that points at the given component. */
  20194. SafePointer (ComponentType* const component) : comp (component) { attach(); }
  20195. /** Creates a copy of another SafePointer. */
  20196. SafePointer (const SafePointer& other) : comp (other.comp) { attach(); }
  20197. /** Destructor. */
  20198. ~SafePointer() { detach(); }
  20199. /** Copies another pointer to this one. */
  20200. SafePointer& operator= (const SafePointer& other) { return operator= (other.comp); }
  20201. /** Copies another pointer to this one. */
  20202. SafePointer& operator= (ComponentType* const newComponent)
  20203. {
  20204. detach();
  20205. comp = newComponent;
  20206. attach();
  20207. return *this;
  20208. }
  20209. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20210. operator ComponentType*() const throw() { return comp; }
  20211. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20212. ComponentType* getComponent() const throw() { return comp; }
  20213. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20214. ComponentType* operator->() throw() { jassert (comp != 0); return comp; }
  20215. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20216. const ComponentType* operator->() const throw() { jassert (comp != 0); return comp; }
  20217. juce_UseDebuggingNewOperator
  20218. private:
  20219. ComponentType* comp;
  20220. void attach() { if (comp != 0) comp->addComponentListener (this); }
  20221. void detach() { if (comp != 0) comp->removeComponentListener (this); }
  20222. void componentBeingDeleted (Component&) { comp = 0; }
  20223. };
  20224. /** A class to keep an eye on one or two components and check for them being deleted.
  20225. This is designed for use with the ListenerList::callChecked() methods, to allow
  20226. the list iterator to stop cleanly if the component is deleted by a listener callback
  20227. while the list is still being iterated.
  20228. */
  20229. class BailOutChecker
  20230. {
  20231. public:
  20232. /** Creates a checker that watches either one or two components.
  20233. component1 must be a valid component; component2 can be null if you only need
  20234. to check on one component.
  20235. */
  20236. BailOutChecker (Component* component1,
  20237. Component* component2 = 0);
  20238. /** Returns true if either of the two components have been deleted since this
  20239. object was created. */
  20240. bool shouldBailOut() const throw();
  20241. private:
  20242. typedef SafePointer<Component> SafeComponentPtr;
  20243. SafeComponentPtr safePointer1, safePointer2;
  20244. Component* const component2;
  20245. BailOutChecker (const BailOutChecker&);
  20246. BailOutChecker& operator= (const BailOutChecker&);
  20247. };
  20248. juce_UseDebuggingNewOperator
  20249. private:
  20250. friend class ComponentPeer;
  20251. friend class InternalDragRepeater;
  20252. friend class MouseInputSource;
  20253. friend class MouseInputSourceInternal;
  20254. static Component* currentlyFocusedComponent;
  20255. String componentName_;
  20256. Component* parentComponent_;
  20257. uint32 componentUID;
  20258. Rectangle<int> bounds_;
  20259. int numDeepMouseListeners;
  20260. Array <Component*> childComponentList_;
  20261. LookAndFeel* lookAndFeel_;
  20262. MouseCursor cursor_;
  20263. ImageEffectFilter* effect_;
  20264. Image bufferedImage_;
  20265. Array <MouseListener*>* mouseListeners_;
  20266. Array <KeyListener*>* keyListeners_;
  20267. ListenerList <ComponentListener> componentListeners;
  20268. NamedValueSet properties;
  20269. struct ComponentFlags
  20270. {
  20271. bool hasHeavyweightPeerFlag : 1;
  20272. bool visibleFlag : 1;
  20273. bool opaqueFlag : 1;
  20274. bool ignoresMouseClicksFlag : 1;
  20275. bool allowChildMouseClicksFlag : 1;
  20276. bool wantsFocusFlag : 1;
  20277. bool isFocusContainerFlag : 1;
  20278. bool dontFocusOnMouseClickFlag : 1;
  20279. bool alwaysOnTopFlag : 1;
  20280. bool bufferToImageFlag : 1;
  20281. bool bringToFrontOnClickFlag : 1;
  20282. bool repaintOnMouseActivityFlag : 1;
  20283. bool draggingFlag : 1;
  20284. bool mouseOverFlag : 1;
  20285. bool mouseInsideFlag : 1;
  20286. bool currentlyModalFlag : 1;
  20287. bool isDisabledFlag : 1;
  20288. bool childCompFocusedFlag : 1;
  20289. #if JUCE_DEBUG
  20290. bool isInsidePaintCall : 1;
  20291. #endif
  20292. };
  20293. union
  20294. {
  20295. uint32 componentFlags_;
  20296. ComponentFlags flags;
  20297. };
  20298. void internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20299. void internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20300. void internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20301. void internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers);
  20302. void internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20303. void internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20304. void internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos, const Time& time, float amountX, float amountY);
  20305. void internalBroughtToFront();
  20306. void internalFocusGain (const FocusChangeType cause);
  20307. void internalFocusLoss (const FocusChangeType cause);
  20308. void internalChildFocusChange (FocusChangeType cause);
  20309. void internalModalInputAttempt();
  20310. void internalModifierKeysChanged();
  20311. void internalChildrenChanged();
  20312. void internalHierarchyChanged();
  20313. void renderComponent (Graphics& context);
  20314. void sendMovedResizedMessages (bool wasMoved, bool wasResized);
  20315. void repaintParent();
  20316. void sendFakeMouseMove() const;
  20317. void takeKeyboardFocus (const FocusChangeType cause);
  20318. void grabFocusInternal (const FocusChangeType cause, bool canTryParent = true);
  20319. static void giveAwayFocus();
  20320. void sendEnablementChangeMessage();
  20321. static void* runModalLoopCallback (void*);
  20322. static void bringModalComponentToFront();
  20323. void subtractObscuredRegions (RectangleList& result, const Point<int>& delta,
  20324. const Rectangle<int>& clipRect,
  20325. const Component* const compToAvoid) const;
  20326. void clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  20327. int deltaX, int deltaY) const;
  20328. // how much of the component is not off the edges of its parents
  20329. const Rectangle<int> getUnclippedArea() const;
  20330. void sendVisibilityChangeMessage();
  20331. // This is included here just to cause a compile error if your code is still handling
  20332. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  20333. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  20334. // implement its methods instead of this Component method).
  20335. virtual void filesDropped (const StringArray&, int, int) {}
  20336. // components aren't allowed to have copy constructors, as this would mess up parent
  20337. // hierarchies. You might need to give your subclasses a private dummy constructor like
  20338. // this one to avoid compiler warnings.
  20339. Component (const Component&);
  20340. Component& operator= (const Component&);
  20341. protected:
  20342. /** @internal */
  20343. virtual void internalRepaint (int x, int y, int w, int h);
  20344. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  20345. /** Overridden from the MessageListener parent class.
  20346. You can override this if you really need to, but be sure to pass your unwanted messages up
  20347. to this base class implementation, as the Component class needs to send itself messages
  20348. to work properly.
  20349. */
  20350. void handleMessage (const Message&);
  20351. };
  20352. #endif // __JUCE_COMPONENT_JUCEHEADER__
  20353. /*** End of inlined file: juce_Component.h ***/
  20354. /*** Start of inlined file: juce_ApplicationCommandInfo.h ***/
  20355. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20356. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20357. /*** Start of inlined file: juce_ApplicationCommandID.h ***/
  20358. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20359. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20360. /** A type used to hold the unique ID for an application command.
  20361. This is a numeric type, so it can be stored as an integer.
  20362. @see ApplicationCommandInfo, ApplicationCommandManager,
  20363. ApplicationCommandTarget, KeyPressMappingSet
  20364. */
  20365. typedef int CommandID;
  20366. /** A set of general-purpose application command IDs.
  20367. Because these commands are likely to be used in most apps, they're defined
  20368. here to help different apps to use the same numeric values for them.
  20369. Of course you don't have to use these, but some of them are used internally by
  20370. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  20371. @see ApplicationCommandInfo, ApplicationCommandManager,
  20372. ApplicationCommandTarget, KeyPressMappingSet
  20373. */
  20374. namespace StandardApplicationCommandIDs
  20375. {
  20376. /** This command ID should be used to send a "Quit the App" command.
  20377. This command is recognised by the JUCEApplication class, so if it is invoked
  20378. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  20379. object will catch it and call JUCEApplication::systemRequestedQuit().
  20380. */
  20381. static const CommandID quit = 0x1001;
  20382. /** The command ID that should be used to send a "Delete" command. */
  20383. static const CommandID del = 0x1002;
  20384. /** The command ID that should be used to send a "Cut" command. */
  20385. static const CommandID cut = 0x1003;
  20386. /** The command ID that should be used to send a "Copy to clipboard" command. */
  20387. static const CommandID copy = 0x1004;
  20388. /** The command ID that should be used to send a "Paste from clipboard" command. */
  20389. static const CommandID paste = 0x1005;
  20390. /** The command ID that should be used to send a "Select all" command. */
  20391. static const CommandID selectAll = 0x1006;
  20392. /** The command ID that should be used to send a "Deselect all" command. */
  20393. static const CommandID deselectAll = 0x1007;
  20394. }
  20395. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20396. /*** End of inlined file: juce_ApplicationCommandID.h ***/
  20397. /**
  20398. Holds information describing an application command.
  20399. This object is used to pass information about a particular command, such as its
  20400. name, description and other usage flags.
  20401. When an ApplicationCommandTarget is asked to provide information about the commands
  20402. it can perform, this is the structure gets filled-in to describe each one.
  20403. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  20404. ApplicationCommandManager
  20405. */
  20406. struct JUCE_API ApplicationCommandInfo
  20407. {
  20408. explicit ApplicationCommandInfo (CommandID commandID) throw();
  20409. /** Sets a number of the structures values at once.
  20410. The meanings of each of the parameters is described below, in the appropriate
  20411. member variable's description.
  20412. */
  20413. void setInfo (const String& shortName,
  20414. const String& description,
  20415. const String& categoryName,
  20416. int flags) throw();
  20417. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  20418. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  20419. is false, the bit is set.
  20420. */
  20421. void setActive (bool isActive) throw();
  20422. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  20423. */
  20424. void setTicked (bool isTicked) throw();
  20425. /** Handy method for adding a keypress to the defaultKeypresses array.
  20426. This is just so you can write things like:
  20427. @code
  20428. myinfo.addDefaultKeypress ('s', ModifierKeys::commandModifier);
  20429. @endcode
  20430. instead of
  20431. @code
  20432. myinfo.defaultKeypresses.add (KeyPress ('s', ModifierKeys::commandModifier));
  20433. @endcode
  20434. */
  20435. void addDefaultKeypress (int keyCode,
  20436. const ModifierKeys& modifiers) throw();
  20437. /** The command's unique ID number.
  20438. */
  20439. CommandID commandID;
  20440. /** A short name to describe the command.
  20441. This should be suitable for use in menus, on buttons that trigger the command, etc.
  20442. You can use the setInfo() method to quickly set this and some of the command's
  20443. other properties.
  20444. */
  20445. String shortName;
  20446. /** A longer description of the command.
  20447. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  20448. pop-up tooltip describing what the command does.
  20449. You can use the setInfo() method to quickly set this and some of the command's
  20450. other properties.
  20451. */
  20452. String description;
  20453. /** A named category that the command fits into.
  20454. You can give your commands any category you like, and these will be displayed in
  20455. contexts such as the KeyMappingEditorComponent, where the category is used to group
  20456. commands together.
  20457. You can use the setInfo() method to quickly set this and some of the command's
  20458. other properties.
  20459. */
  20460. String categoryName;
  20461. /** A list of zero or more keypresses that should be used as the default keys for
  20462. this command.
  20463. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  20464. this list to initialise the default set of key-to-command mappings.
  20465. @see addDefaultKeypress
  20466. */
  20467. Array <KeyPress> defaultKeypresses;
  20468. /** Flags describing the ways in which this command should be used.
  20469. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  20470. variable.
  20471. */
  20472. enum CommandFlags
  20473. {
  20474. /** Indicates that the command can't currently be performed.
  20475. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  20476. not currently permissable to perform the command. If the flag is set, then
  20477. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  20478. command or show themselves as not being enabled.
  20479. @see ApplicationCommandInfo::setActive
  20480. */
  20481. isDisabled = 1 << 0,
  20482. /** Indicates that the command should have a tick next to it on a menu.
  20483. If your command is shown on a menu and this is set, it'll show a tick next to
  20484. it. Other components such as buttons may also use this flag to indicate that it
  20485. is a value that can be toggled, and is currently in the 'on' state.
  20486. @see ApplicationCommandInfo::setTicked
  20487. */
  20488. isTicked = 1 << 1,
  20489. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  20490. it will call the command twice, once on key-down and again on key-up.
  20491. @see ApplicationCommandTarget::InvocationInfo
  20492. */
  20493. wantsKeyUpDownCallbacks = 1 << 2,
  20494. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  20495. command in its list.
  20496. */
  20497. hiddenFromKeyEditor = 1 << 3,
  20498. /** If this flag is present, then a KeyMappingEditorComponent will display the
  20499. command in its list, but won't allow the assigned keypress to be changed.
  20500. */
  20501. readOnlyInKeyEditor = 1 << 4,
  20502. /** If this flag is present and the command is invoked from a keypress, then any
  20503. buttons or menus that are also connected to the command will not flash to
  20504. indicate that they've been triggered.
  20505. */
  20506. dontTriggerVisualFeedback = 1 << 5
  20507. };
  20508. /** A bitwise-OR of the values specified in the CommandFlags enum.
  20509. You can use the setInfo() method to quickly set this and some of the command's
  20510. other properties.
  20511. */
  20512. int flags;
  20513. };
  20514. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20515. /*** End of inlined file: juce_ApplicationCommandInfo.h ***/
  20516. /**
  20517. A command target publishes a list of command IDs that it can perform.
  20518. An ApplicationCommandManager despatches commands to targets, which must be
  20519. able to provide information about what commands they can handle.
  20520. To create a target, you'll need to inherit from this class, implementing all of
  20521. its pure virtual methods.
  20522. For info about how a target is chosen to receive a command, see
  20523. ApplicationCommandManager::getFirstCommandTarget().
  20524. @see ApplicationCommandManager, ApplicationCommandInfo
  20525. */
  20526. class JUCE_API ApplicationCommandTarget
  20527. {
  20528. public:
  20529. /** Creates a command target. */
  20530. ApplicationCommandTarget();
  20531. /** Destructor. */
  20532. virtual ~ApplicationCommandTarget();
  20533. /**
  20534. */
  20535. struct JUCE_API InvocationInfo
  20536. {
  20537. InvocationInfo (const CommandID commandID) throw();
  20538. /** The UID of the command that should be performed. */
  20539. CommandID commandID;
  20540. /** The command's flags.
  20541. See ApplicationCommandInfo for a description of these flag values.
  20542. */
  20543. int commandFlags;
  20544. /** The types of context in which the command might be called. */
  20545. enum InvocationMethod
  20546. {
  20547. direct = 0, /**< The command is being invoked directly by a piece of code. */
  20548. fromKeyPress, /**< The command is being invoked by a key-press. */
  20549. fromMenu, /**< The command is being invoked by a menu selection. */
  20550. fromButton /**< The command is being invoked by a button click. */
  20551. };
  20552. /** The type of event that triggered this command. */
  20553. InvocationMethod invocationMethod;
  20554. /** If triggered by a keypress or menu, this will be the component that had the
  20555. keyboard focus at the time.
  20556. If triggered by a button, it may be set to that component, or it may be null.
  20557. */
  20558. Component* originatingComponent;
  20559. /** The keypress that was used to invoke it.
  20560. Note that this will be an invalid keypress if the command was invoked
  20561. by some other means than a keyboard shortcut.
  20562. */
  20563. KeyPress keyPress;
  20564. /** True if the callback is being invoked when the key is pressed,
  20565. false if the key is being released.
  20566. @see KeyPressMappingSet::addCommand()
  20567. */
  20568. bool isKeyDown;
  20569. /** If the key is being released, this indicates how long it had been held
  20570. down for.
  20571. (Only relevant if isKeyDown is false.)
  20572. */
  20573. int millisecsSinceKeyPressed;
  20574. };
  20575. /** This must return the next target to try after this one.
  20576. When a command is being sent, and the first target can't handle
  20577. that command, this method is used to determine the next target that should
  20578. be tried.
  20579. It may return 0 if it doesn't know of another target.
  20580. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  20581. method to return a parent component that might want to handle it.
  20582. @see invoke
  20583. */
  20584. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  20585. /** This must return a complete list of commands that this target can handle.
  20586. Your target should add all the command IDs that it handles to the array that is
  20587. passed-in.
  20588. */
  20589. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  20590. /** This must provide details about one of the commands that this target can perform.
  20591. This will be called with one of the command IDs that the target provided in its
  20592. getAllCommands() methods.
  20593. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  20594. suitable information about the command. (The commandID field will already have been filled-in
  20595. by the caller).
  20596. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  20597. set all the fields at once.
  20598. If the command is currently inactive for some reason, this method must use
  20599. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  20600. bit of the ApplicationCommandInfo::flags field).
  20601. Any default key-presses for the command should be appended to the
  20602. ApplicationCommandInfo::defaultKeypresses field.
  20603. Note that if you change something that affects the status of the commands
  20604. that would be returned by this method (e.g. something that makes some commands
  20605. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  20606. to cause the manager to refresh its status.
  20607. */
  20608. virtual void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) = 0;
  20609. /** This must actually perform the specified command.
  20610. If this target is able to perform the command specified by the commandID field of the
  20611. InvocationInfo structure, then it should do so, and must return true.
  20612. If it can't handle this command, it should return false, which tells the caller to pass
  20613. the command on to the next target in line.
  20614. @see invoke, ApplicationCommandManager::invoke
  20615. */
  20616. virtual bool perform (const InvocationInfo& info) = 0;
  20617. /** Makes this target invoke a command.
  20618. Your code can call this method to invoke a command on this target, but normally
  20619. you'd call it indirectly via ApplicationCommandManager::invoke() or
  20620. ApplicationCommandManager::invokeDirectly().
  20621. If this target can perform the given command, it will call its perform() method to
  20622. do so. If not, then getNextCommandTarget() will be used to determine the next target
  20623. to try, and the command will be passed along to it.
  20624. @param invocationInfo this must be correctly filled-in, describing the context for
  20625. the invocation.
  20626. @param asynchronously if false, the command will be performed before this method returns.
  20627. If true, a message will be posted so that the command will be performed
  20628. later on the message thread, and this method will return immediately.
  20629. @see perform, ApplicationCommandManager::invoke
  20630. */
  20631. bool invoke (const InvocationInfo& invocationInfo,
  20632. const bool asynchronously);
  20633. /** Invokes a given command directly on this target.
  20634. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  20635. structure.
  20636. */
  20637. bool invokeDirectly (const CommandID commandID,
  20638. const bool asynchronously);
  20639. /** Searches this target and all subsequent ones for the first one that can handle
  20640. the specified command.
  20641. This will use getNextCommandTarget() to determine the chain of targets to try
  20642. after this one.
  20643. */
  20644. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  20645. /** Checks whether this command can currently be performed by this target.
  20646. This will return true only if a call to getCommandInfo() doesn't set the
  20647. isDisabled flag to indicate that the command is inactive.
  20648. */
  20649. bool isCommandActive (const CommandID commandID);
  20650. /** If this object is a Component, this method will seach upwards in its current
  20651. UI hierarchy for the next parent component that implements the
  20652. ApplicationCommandTarget class.
  20653. If your target is a Component, this is a very handy method to use in your
  20654. getNextCommandTarget() implementation.
  20655. */
  20656. ApplicationCommandTarget* findFirstTargetParentComponent();
  20657. juce_UseDebuggingNewOperator
  20658. private:
  20659. // (for async invocation of commands)
  20660. class CommandTargetMessageInvoker : public MessageListener
  20661. {
  20662. public:
  20663. CommandTargetMessageInvoker (ApplicationCommandTarget* const owner);
  20664. ~CommandTargetMessageInvoker();
  20665. void handleMessage (const Message& message);
  20666. private:
  20667. ApplicationCommandTarget* const owner;
  20668. CommandTargetMessageInvoker (const CommandTargetMessageInvoker&);
  20669. CommandTargetMessageInvoker& operator= (const CommandTargetMessageInvoker&);
  20670. };
  20671. ScopedPointer <CommandTargetMessageInvoker> messageInvoker;
  20672. friend class CommandTargetMessageInvoker;
  20673. bool tryToInvoke (const InvocationInfo& info, const bool async);
  20674. ApplicationCommandTarget (const ApplicationCommandTarget&);
  20675. ApplicationCommandTarget& operator= (const ApplicationCommandTarget&);
  20676. };
  20677. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  20678. /*** End of inlined file: juce_ApplicationCommandTarget.h ***/
  20679. /*** Start of inlined file: juce_ActionListener.h ***/
  20680. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  20681. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  20682. /**
  20683. Receives callbacks to indicate that some kind of event has occurred.
  20684. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  20685. about something that's happened.
  20686. @see ActionListenerList, ActionBroadcaster, ChangeListener
  20687. */
  20688. class JUCE_API ActionListener
  20689. {
  20690. public:
  20691. /** Destructor. */
  20692. virtual ~ActionListener() {}
  20693. /** Overridden by your subclass to receive the callback.
  20694. @param message the string that was specified when the event was triggered
  20695. by a call to ActionListenerList::sendActionMessage()
  20696. */
  20697. virtual void actionListenerCallback (const String& message) = 0;
  20698. };
  20699. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  20700. /*** End of inlined file: juce_ActionListener.h ***/
  20701. /**
  20702. An instance of this class is used to specify initialisation and shutdown
  20703. code for the application.
  20704. An application that wants to run in the JUCE framework needs to declare a
  20705. subclass of JUCEApplication and implement its various pure virtual methods.
  20706. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  20707. to declare an instance of this class and generate a suitable platform-specific
  20708. main() function.
  20709. e.g. @code
  20710. class MyJUCEApp : public JUCEApplication
  20711. {
  20712. // NEVER put objects inside a JUCEApplication class - only use pointers to
  20713. // objects, which you must create in the initialise() method.
  20714. MyApplicationWindow* myMainWindow;
  20715. public:
  20716. MyJUCEApp()
  20717. : myMainWindow (0)
  20718. {
  20719. // never create any Juce objects in the constructor - do all your initialisation
  20720. // in the initialise() method.
  20721. }
  20722. ~MyJUCEApp()
  20723. {
  20724. // all your shutdown code must have already been done in the shutdown() method -
  20725. // nothing should happen in this destructor.
  20726. }
  20727. void initialise (const String& commandLine)
  20728. {
  20729. myMainWindow = new MyApplicationWindow();
  20730. myMainWindow->setBounds (100, 100, 400, 500);
  20731. myMainWindow->setVisible (true);
  20732. }
  20733. void shutdown()
  20734. {
  20735. delete myMainWindow;
  20736. }
  20737. const String getApplicationName()
  20738. {
  20739. return "Super JUCE-o-matic";
  20740. }
  20741. const String getApplicationVersion()
  20742. {
  20743. return "1.0";
  20744. }
  20745. };
  20746. // this creates wrapper code to actually launch the app properly.
  20747. START_JUCE_APPLICATION (MyJUCEApp)
  20748. @endcode
  20749. Because this object will be created before Juce has properly initialised, you must
  20750. NEVER add any member variable objects that will be automatically constructed. Likewise
  20751. don't put ANY code in the constructor that could call Juce functions. Any objects that
  20752. you want to add to the class must be pointers, which you should instantiate during the
  20753. initialise() method, and delete in the shutdown() method.
  20754. @see MessageManager, DeletedAtShutdown
  20755. */
  20756. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  20757. private ActionListener
  20758. {
  20759. protected:
  20760. /** Constructs a JUCE app object.
  20761. If subclasses implement a constructor or destructor, they shouldn't call any
  20762. JUCE code in there - put your startup/shutdown code in initialise() and
  20763. shutdown() instead.
  20764. */
  20765. JUCEApplication();
  20766. public:
  20767. /** Destructor.
  20768. If subclasses implement a constructor or destructor, they shouldn't call any
  20769. JUCE code in there - put your startup/shutdown code in initialise() and
  20770. shutdown() instead.
  20771. */
  20772. virtual ~JUCEApplication();
  20773. /** Returns the global instance of the application object being run. */
  20774. static JUCEApplication* getInstance() throw();
  20775. /** Called when the application starts.
  20776. This will be called once to let the application do whatever initialisation
  20777. it needs, create its windows, etc.
  20778. After the method returns, the normal event-dispatch loop will be run,
  20779. until the quit() method is called, at which point the shutdown()
  20780. method will be called to let the application clear up anything it needs
  20781. to delete.
  20782. If during the initialise() method, the application decides not to start-up
  20783. after all, it can just call the quit() method and the event loop won't be run.
  20784. @param commandLineParameters the line passed in does not include the
  20785. name of the executable, just the parameter list.
  20786. @see shutdown, quit
  20787. */
  20788. virtual void initialise (const String& commandLineParameters) = 0;
  20789. /** Returns true if the application hasn't yet completed its initialise() method
  20790. and entered the main event loop.
  20791. This is handy for things like splash screens to know when the app's up-and-running
  20792. properly.
  20793. */
  20794. bool isInitialising() const throw();
  20795. /* Called to allow the application to clear up before exiting.
  20796. After JUCEApplication::quit() has been called, the event-dispatch loop will
  20797. terminate, and this method will get called to allow the app to sort itself
  20798. out.
  20799. Be careful that nothing happens in this method that might rely on messages
  20800. being sent, or any kind of window activity, because the message loop is no
  20801. longer running at this point.
  20802. @see DeletedAtShutdown
  20803. */
  20804. virtual void shutdown() = 0;
  20805. /** Returns the application's name.
  20806. An application must implement this to name itself.
  20807. */
  20808. virtual const String getApplicationName() = 0;
  20809. /** Returns the application's version number.
  20810. An application can implement this to give itself a version.
  20811. (The default implementation of this just returns an empty string).
  20812. */
  20813. virtual const String getApplicationVersion();
  20814. /** Checks whether multiple instances of the app are allowed.
  20815. If you application class returns true for this, more than one instance is
  20816. permitted to run (except on the Mac where this isn't possible).
  20817. If it's false, the second instance won't start, but it you will still get a
  20818. callback to anotherInstanceStarted() to tell you about this - which
  20819. gives you a chance to react to what the user was trying to do.
  20820. */
  20821. virtual bool moreThanOneInstanceAllowed();
  20822. /** Indicates that the user has tried to start up another instance of the app.
  20823. This will get called even if moreThanOneInstanceAllowed() is false.
  20824. */
  20825. virtual void anotherInstanceStarted (const String& commandLine);
  20826. /** Called when the operating system is trying to close the application.
  20827. The default implementation of this method is to call quit(), but it may
  20828. be overloaded to ignore the request or do some other special behaviour
  20829. instead. For example, you might want to offer the user the chance to save
  20830. their changes before quitting, and give them the chance to cancel.
  20831. If you want to send a quit signal to your app, this is the correct method
  20832. to call, because it means that requests that come from the system get handled
  20833. in the same way as those from your own application code. So e.g. you'd
  20834. call this method from a "quit" item on a menu bar.
  20835. */
  20836. virtual void systemRequestedQuit();
  20837. /** If any unhandled exceptions make it through to the message dispatch loop, this
  20838. callback will be triggered, in case you want to log them or do some other
  20839. type of error-handling.
  20840. If the type of exception is derived from the std::exception class, the pointer
  20841. passed-in will be valid. If the exception is of unknown type, this pointer
  20842. will be null.
  20843. */
  20844. virtual void unhandledException (const std::exception* e,
  20845. const String& sourceFilename,
  20846. int lineNumber);
  20847. /** Signals that the main message loop should stop and the application should terminate.
  20848. This isn't synchronous, it just posts a quit message to the main queue, and
  20849. when this message arrives, the message loop will stop, the shutdown() method
  20850. will be called, and the app will exit.
  20851. Note that this will cause an unconditional quit to happen, so if you need an
  20852. extra level before this, e.g. to give the user the chance to save their work
  20853. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  20854. method - see that method's help for more info.
  20855. @see MessageManager, DeletedAtShutdown
  20856. */
  20857. static void quit();
  20858. /** Sets the value that should be returned as the application's exit code when the
  20859. app quits.
  20860. This is the value that's returned by the main() function. Normally you'd leave this
  20861. as 0 unless you want to indicate an error code.
  20862. @see getApplicationReturnValue
  20863. */
  20864. void setApplicationReturnValue (int newReturnValue) throw();
  20865. /** Returns the value that has been set as the application's exit code.
  20866. @see setApplicationReturnValue
  20867. */
  20868. int getApplicationReturnValue() const throw() { return appReturnValue; }
  20869. /** Returns the application's command line params.
  20870. */
  20871. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  20872. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  20873. /** @internal */
  20874. static int main (String& commandLine, JUCEApplication* newApp);
  20875. /** @internal */
  20876. static int main (int argc, const char* argv[], JUCEApplication* newApp);
  20877. /** @internal */
  20878. static void sendUnhandledException (const std::exception* e,
  20879. const char* sourceFile,
  20880. int lineNumber);
  20881. /** @internal */
  20882. ApplicationCommandTarget* getNextCommandTarget();
  20883. /** @internal */
  20884. void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result);
  20885. /** @internal */
  20886. void getAllCommands (Array <CommandID>& commands);
  20887. /** @internal */
  20888. bool perform (const InvocationInfo& info);
  20889. /** @internal */
  20890. void actionListenerCallback (const String& message);
  20891. private:
  20892. String commandLineParameters;
  20893. int appReturnValue;
  20894. bool stillInitialising;
  20895. ScopedPointer<InterProcessLock> appLock;
  20896. JUCEApplication (const JUCEApplication&);
  20897. JUCEApplication& operator= (const JUCEApplication&);
  20898. public:
  20899. /** @internal */
  20900. bool initialiseApp (String& commandLine);
  20901. /** @internal */
  20902. static int shutdownAppAndClearUp();
  20903. };
  20904. #endif // __JUCE_APPLICATION_JUCEHEADER__
  20905. /*** End of inlined file: juce_Application.h ***/
  20906. #endif
  20907. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20908. #endif
  20909. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20910. #endif
  20911. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  20912. /*** Start of inlined file: juce_ApplicationCommandManager.h ***/
  20913. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  20914. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  20915. /*** Start of inlined file: juce_Desktop.h ***/
  20916. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  20917. #define __JUCE_DESKTOP_JUCEHEADER__
  20918. /*** Start of inlined file: juce_DeletedAtShutdown.h ***/
  20919. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  20920. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  20921. /**
  20922. Classes derived from this will be automatically deleted when the application exits.
  20923. After JUCEApplication::shutdown() has been called, any objects derived from
  20924. DeletedAtShutdown which are still in existence will be deleted in the reverse
  20925. order to that in which they were created.
  20926. So if you've got a singleton and don't want to have to explicitly delete it, just
  20927. inherit from this and it'll be taken care of.
  20928. */
  20929. class JUCE_API DeletedAtShutdown
  20930. {
  20931. protected:
  20932. /** Creates a DeletedAtShutdown object. */
  20933. DeletedAtShutdown();
  20934. /** Destructor.
  20935. It's ok to delete these objects explicitly - it's only the ones left
  20936. dangling at the end that will be deleted automatically.
  20937. */
  20938. virtual ~DeletedAtShutdown();
  20939. public:
  20940. /** Deletes all extant objects.
  20941. This shouldn't be used by applications, as it's called automatically
  20942. in the shutdown code of the JUCEApplication class.
  20943. */
  20944. static void deleteAll();
  20945. private:
  20946. DeletedAtShutdown (const DeletedAtShutdown&);
  20947. DeletedAtShutdown& operator= (const DeletedAtShutdown&);
  20948. static CriticalSection& getLock();
  20949. static Array <DeletedAtShutdown*>& getObjects();
  20950. };
  20951. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  20952. /*** End of inlined file: juce_DeletedAtShutdown.h ***/
  20953. /*** Start of inlined file: juce_Timer.h ***/
  20954. #ifndef __JUCE_TIMER_JUCEHEADER__
  20955. #define __JUCE_TIMER_JUCEHEADER__
  20956. class InternalTimerThread;
  20957. /**
  20958. Repeatedly calls a user-defined method at a specified time interval.
  20959. A Timer's timerCallback() method will be repeatedly called at a given
  20960. interval. Initially when a Timer object is created, they will do nothing
  20961. until the startTimer() method is called, then the message thread will
  20962. start calling it back until stopTimer() is called.
  20963. The time interval isn't guaranteed to be precise to any more than maybe
  20964. 10-20ms, and the intervals may end up being much longer than requested if the
  20965. system is busy. Because it's the message thread that is doing the callbacks,
  20966. any messages that take a significant amount of time to process will block
  20967. all the timers for that period.
  20968. If you need to have a single callback that is shared by multiple timers with
  20969. different frequencies, then the MultiTimer class allows you to do that - its
  20970. structure is very similar to the Timer class, but contains multiple timers
  20971. internally, each one identified by an ID number.
  20972. @see MultiTimer
  20973. */
  20974. class JUCE_API Timer
  20975. {
  20976. protected:
  20977. /** Creates a Timer.
  20978. When created, the timer is stopped, so use startTimer() to get it going.
  20979. */
  20980. Timer() throw();
  20981. /** Creates a copy of another timer.
  20982. Note that this timer won't be started, even if the one you're copying
  20983. is running.
  20984. */
  20985. Timer (const Timer& other) throw();
  20986. public:
  20987. /** Destructor. */
  20988. virtual ~Timer();
  20989. /** The user-defined callback routine that actually gets called periodically.
  20990. It's perfectly ok to call startTimer() or stopTimer() from within this
  20991. callback to change the subsequent intervals.
  20992. */
  20993. virtual void timerCallback() = 0;
  20994. /** Starts the timer and sets the length of interval required.
  20995. If the timer is already started, this will reset it, so the
  20996. time between calling this method and the next timer callback
  20997. will not be less than the interval length passed in.
  20998. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  20999. rounded up to 1)
  21000. */
  21001. void startTimer (int intervalInMilliseconds) throw();
  21002. /** Stops the timer.
  21003. No more callbacks will be made after this method returns.
  21004. If this is called from a different thread, any callbacks that may
  21005. be currently executing may be allowed to finish before the method
  21006. returns.
  21007. */
  21008. void stopTimer() throw();
  21009. /** Checks if the timer has been started.
  21010. @returns true if the timer is running.
  21011. */
  21012. bool isTimerRunning() const throw() { return periodMs > 0; }
  21013. /** Returns the timer's interval.
  21014. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  21015. */
  21016. int getTimerInterval() const throw() { return periodMs; }
  21017. private:
  21018. friend class InternalTimerThread;
  21019. int countdownMs, periodMs;
  21020. Timer* previous;
  21021. Timer* next;
  21022. Timer& operator= (const Timer&);
  21023. };
  21024. #endif // __JUCE_TIMER_JUCEHEADER__
  21025. /*** End of inlined file: juce_Timer.h ***/
  21026. class MouseInputSource;
  21027. class MouseInputSourceInternal;
  21028. class MouseListener;
  21029. /**
  21030. Classes can implement this interface and register themselves with the Desktop class
  21031. to receive callbacks when the currently focused component changes.
  21032. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  21033. */
  21034. class JUCE_API FocusChangeListener
  21035. {
  21036. public:
  21037. /** Destructor. */
  21038. virtual ~FocusChangeListener() {}
  21039. /** Callback to indicate that the currently focused component has changed. */
  21040. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  21041. };
  21042. /**
  21043. Describes and controls aspects of the computer's desktop.
  21044. */
  21045. class JUCE_API Desktop : private DeletedAtShutdown,
  21046. private Timer,
  21047. private AsyncUpdater
  21048. {
  21049. public:
  21050. /** There's only one dektop object, and this method will return it.
  21051. */
  21052. static Desktop& JUCE_CALLTYPE getInstance();
  21053. /** Returns a list of the positions of all the monitors available.
  21054. The first rectangle in the list will be the main monitor area.
  21055. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  21056. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  21057. */
  21058. const RectangleList getAllMonitorDisplayAreas (bool clippedToWorkArea = true) const throw();
  21059. /** Returns the position and size of the main monitor.
  21060. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  21061. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  21062. */
  21063. const Rectangle<int> getMainMonitorArea (bool clippedToWorkArea = true) const throw();
  21064. /** Returns the position and size of the monitor which contains this co-ordinate.
  21065. If none of the monitors contains the point, this will just return the
  21066. main monitor.
  21067. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  21068. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  21069. */
  21070. const Rectangle<int> getMonitorAreaContaining (const Point<int>& position, bool clippedToWorkArea = true) const;
  21071. /** Returns the mouse position.
  21072. The co-ordinates are relative to the top-left of the main monitor.
  21073. */
  21074. static const Point<int> getMousePosition();
  21075. /** Makes the mouse pointer jump to a given location.
  21076. The co-ordinates are relative to the top-left of the main monitor.
  21077. */
  21078. static void setMousePosition (const Point<int>& newPosition);
  21079. /** Returns the last position at which a mouse button was pressed.
  21080. */
  21081. static const Point<int> getLastMouseDownPosition() throw();
  21082. /** Returns the number of times the mouse button has been clicked since the
  21083. app started.
  21084. Each mouse-down event increments this number by 1.
  21085. */
  21086. static int getMouseButtonClickCounter() throw();
  21087. /** This lets you prevent the screensaver from becoming active.
  21088. Handy if you're running some sort of presentation app where having a screensaver
  21089. appear would be annoying.
  21090. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  21091. won't enable a screensaver unless the user has actually set one up).
  21092. The disablement will only happen while the Juce application is the foreground
  21093. process - if another task is running in front of it, then the screensaver will
  21094. be unaffected.
  21095. @see isScreenSaverEnabled
  21096. */
  21097. static void setScreenSaverEnabled (bool isEnabled);
  21098. /** Returns true if the screensaver has not been turned off.
  21099. This will return the last value passed into setScreenSaverEnabled(). Note that
  21100. it won't tell you whether the user is actually using a screen saver, just
  21101. whether this app is deliberately preventing one from running.
  21102. @see setScreenSaverEnabled
  21103. */
  21104. static bool isScreenSaverEnabled();
  21105. /** Registers a MouseListener that will receive all mouse events that occur on
  21106. any component.
  21107. @see removeGlobalMouseListener
  21108. */
  21109. void addGlobalMouseListener (MouseListener* listener);
  21110. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  21111. method.
  21112. @see addGlobalMouseListener
  21113. */
  21114. void removeGlobalMouseListener (MouseListener* listener);
  21115. /** Registers a MouseListener that will receive a callback whenever the focused
  21116. component changes.
  21117. */
  21118. void addFocusChangeListener (FocusChangeListener* listener);
  21119. /** Unregisters a listener that was added with addFocusChangeListener(). */
  21120. void removeFocusChangeListener (FocusChangeListener* listener);
  21121. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  21122. The component must already be on the desktop for this method to work. It will
  21123. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  21124. etc will be hidden.
  21125. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  21126. the component that's currently being used will be resized back to the size
  21127. and position it was in before being put into this mode.
  21128. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  21129. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  21130. to hide as much on-screen paraphenalia as possible.
  21131. */
  21132. void setKioskModeComponent (Component* componentToUse,
  21133. bool allowMenusAndBars = true);
  21134. /** Returns the component that is currently being used in kiosk-mode.
  21135. This is the component that was last set by setKioskModeComponent(). If none
  21136. has been set, this returns 0.
  21137. */
  21138. Component* getKioskModeComponent() const throw() { return kioskModeComponent; }
  21139. /** Returns the number of components that are currently active as top-level
  21140. desktop windows.
  21141. @see getComponent, Component::addToDesktop
  21142. */
  21143. int getNumComponents() const throw();
  21144. /** Returns one of the top-level desktop window components.
  21145. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  21146. index is out-of-range.
  21147. @see getNumComponents, Component::addToDesktop
  21148. */
  21149. Component* getComponent (int index) const throw();
  21150. /** Finds the component at a given screen location.
  21151. This will drill down into top-level windows to find the child component at
  21152. the given position.
  21153. Returns 0 if the co-ordinates are inside a non-Juce window.
  21154. */
  21155. Component* findComponentAt (const Point<int>& screenPosition) const;
  21156. /** Returns the number of MouseInputSource objects the system has at its disposal.
  21157. In a traditional single-mouse system, there might be only one object. On a multi-touch
  21158. system, there could be one input source per potential finger.
  21159. To find out how many mouse events are currently happening, use getNumDraggingMouseSources().
  21160. @see getMouseSource
  21161. */
  21162. int getNumMouseSources() const throw() { return mouseSources.size(); }
  21163. /** Returns one of the system's MouseInputSource objects.
  21164. The index should be from 0 to getNumMouseSources() - 1. Out-of-range indexes will return
  21165. a null pointer.
  21166. In a traditional single-mouse system, there might be only one object. On a multi-touch
  21167. system, there could be one input source per potential finger.
  21168. */
  21169. MouseInputSource* getMouseSource (int index) const throw() { return mouseSources [index]; }
  21170. /** Returns the main mouse input device that the system is using.
  21171. @see getNumMouseSources()
  21172. */
  21173. MouseInputSource& getMainMouseSource() const throw() { return *mouseSources.getUnchecked(0); }
  21174. /** Returns the number of mouse-sources that are currently being dragged.
  21175. In a traditional single-mouse system, this will be 0 or 1, depending on whether a
  21176. juce component has the button down on it. In a multi-touch system, this could
  21177. be any number from 0 to the number of simultaneous touches that can be detected.
  21178. */
  21179. int getNumDraggingMouseSources() const throw();
  21180. /** Returns one of the mouse sources that's currently being dragged.
  21181. The index should be between 0 and getNumDraggingMouseSources() - 1. If the index is
  21182. out of range, or if no mice or fingers are down, this will return a null pointer.
  21183. */
  21184. MouseInputSource* getDraggingMouseSource (int index) const throw();
  21185. juce_UseDebuggingNewOperator
  21186. /** Tells this object to refresh its idea of what the screen resolution is.
  21187. (Called internally by the native code).
  21188. */
  21189. void refreshMonitorSizes();
  21190. /** True if the OS supports semitransparent windows */
  21191. static bool canUseSemiTransparentWindows() throw();
  21192. private:
  21193. static Desktop* instance;
  21194. friend class Component;
  21195. friend class ComponentPeer;
  21196. friend class MouseInputSource;
  21197. friend class MouseInputSourceInternal;
  21198. friend class DeletedAtShutdown;
  21199. friend class TopLevelWindowManager;
  21200. OwnedArray <MouseInputSource> mouseSources;
  21201. void createMouseInputSources();
  21202. ListenerList <MouseListener> mouseListeners;
  21203. ListenerList <FocusChangeListener> focusListeners;
  21204. Array <Component*> desktopComponents;
  21205. Array <Rectangle<int> > monitorCoordsClipped, monitorCoordsUnclipped;
  21206. Point<int> lastFakeMouseMove;
  21207. void sendMouseMove();
  21208. int mouseClickCounter;
  21209. void incrementMouseClickCounter() throw();
  21210. Component* kioskModeComponent;
  21211. Rectangle<int> kioskComponentOriginalBounds;
  21212. void timerCallback();
  21213. void resetTimer();
  21214. int getNumDisplayMonitors() const throw();
  21215. const Rectangle<int> getDisplayMonitorCoordinates (int index, bool clippedToWorkArea) const throw();
  21216. void addDesktopComponent (Component* c);
  21217. void removeDesktopComponent (Component* c);
  21218. void componentBroughtToFront (Component* c);
  21219. void triggerFocusCallback();
  21220. void handleAsyncUpdate();
  21221. Desktop();
  21222. ~Desktop();
  21223. Desktop (const Desktop&);
  21224. Desktop& operator= (const Desktop&);
  21225. };
  21226. #endif // __JUCE_DESKTOP_JUCEHEADER__
  21227. /*** End of inlined file: juce_Desktop.h ***/
  21228. class KeyPressMappingSet;
  21229. class ApplicationCommandManagerListener;
  21230. /**
  21231. One of these objects holds a list of all the commands your app can perform,
  21232. and despatches these commands when needed.
  21233. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  21234. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  21235. to invoke automatically, which means you don't have to handle the result of a menu
  21236. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  21237. which can choose which events they want to handle.
  21238. This architecture also allows for nested ApplicationCommandTargets, so that for example
  21239. you could have two different objects, one inside the other, both of which can respond to
  21240. a "delete" command. Depending on which one has focus, the command will be sent to the
  21241. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  21242. method.
  21243. To set up your app to use commands, you'll need to do the following:
  21244. - Create a global ApplicationCommandManager to hold the list of all possible
  21245. commands. (This will also manage a set of key-mappings for them).
  21246. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  21247. This allows the object to provide a list of commands that it can perform, and
  21248. to handle them.
  21249. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  21250. or ApplicationCommandManager::registerCommand().
  21251. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  21252. method to access the key-mapper object, which you will need to register as a key-listener
  21253. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  21254. about setting this up.
  21255. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  21256. cause these commands to be invoked automatically.
  21257. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  21258. When a command is invoked, the ApplicationCommandManager will try to choose the best
  21259. ApplicationCommandTarget to receive the specified command. To do this it will use the
  21260. current keyboard focus to see which component might be interested, and will search the
  21261. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  21262. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  21263. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  21264. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  21265. point if the command still hasn't been performed, it will be passed to the current
  21266. JUCEApplication object (which is itself an ApplicationCommandTarget).
  21267. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  21268. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  21269. the object yourself.
  21270. @see ApplicationCommandTarget, ApplicationCommandInfo
  21271. */
  21272. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  21273. private FocusChangeListener
  21274. {
  21275. public:
  21276. /** Creates an ApplicationCommandManager.
  21277. Once created, you'll need to register all your app's commands with it, using
  21278. ApplicationCommandManager::registerAllCommandsForTarget() or
  21279. ApplicationCommandManager::registerCommand().
  21280. */
  21281. ApplicationCommandManager();
  21282. /** Destructor.
  21283. Make sure that you don't delete this if pointers to it are still being used by
  21284. objects such as PopupMenus or Buttons.
  21285. */
  21286. virtual ~ApplicationCommandManager();
  21287. /** Clears the current list of all commands.
  21288. Note that this will also clear the contents of the KeyPressMappingSet.
  21289. */
  21290. void clearCommands();
  21291. /** Adds a command to the list of registered commands.
  21292. @see registerAllCommandsForTarget
  21293. */
  21294. void registerCommand (const ApplicationCommandInfo& newCommand);
  21295. /** Adds all the commands that this target publishes to the manager's list.
  21296. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  21297. to get details about all the commands that this target can do, and will call
  21298. registerCommand() to add each one to the manger's list.
  21299. @see registerCommand
  21300. */
  21301. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  21302. /** Removes the command with a specified ID.
  21303. Note that this will also remove any key mappings that are mapped to the command.
  21304. */
  21305. void removeCommand (CommandID commandID);
  21306. /** This should be called to tell the manager that one of its registered commands may have changed
  21307. its active status.
  21308. Because the command manager only finds out whether a command is active or inactive by querying
  21309. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  21310. allows things like buttons to update their enablement, etc.
  21311. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  21312. for any registered listeners.
  21313. */
  21314. void commandStatusChanged();
  21315. /** Returns the number of commands that have been registered.
  21316. @see registerCommand
  21317. */
  21318. int getNumCommands() const throw() { return commands.size(); }
  21319. /** Returns the details about one of the registered commands.
  21320. The index is between 0 and (getNumCommands() - 1).
  21321. */
  21322. const ApplicationCommandInfo* getCommandForIndex (int index) const throw() { return commands [index]; }
  21323. /** Returns the details about a given command ID.
  21324. This will search the list of registered commands for one with the given command
  21325. ID number, and return its associated info. If no matching command is found, this
  21326. will return 0.
  21327. */
  21328. const ApplicationCommandInfo* getCommandForID (CommandID commandID) const throw();
  21329. /** Returns the name field for a command.
  21330. An empty string is returned if no command with this ID has been registered.
  21331. @see getDescriptionOfCommand
  21332. */
  21333. const String getNameOfCommand (CommandID commandID) const throw();
  21334. /** Returns the description field for a command.
  21335. An empty string is returned if no command with this ID has been registered. If the
  21336. command has no description, this will return its short name field instead.
  21337. @see getNameOfCommand
  21338. */
  21339. const String getDescriptionOfCommand (CommandID commandID) const throw();
  21340. /** Returns the list of categories.
  21341. This will go through all registered commands, and return a list of all the distict
  21342. categoryName values from their ApplicationCommandInfo structure.
  21343. @see getCommandsInCategory()
  21344. */
  21345. const StringArray getCommandCategories() const throw();
  21346. /** Returns a list of all the command UIDs in a particular category.
  21347. @see getCommandCategories()
  21348. */
  21349. const Array <CommandID> getCommandsInCategory (const String& categoryName) const throw();
  21350. /** Returns the manager's internal set of key mappings.
  21351. This object can be used to edit the keypresses. To actually link this object up
  21352. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  21353. class.
  21354. @see KeyPressMappingSet
  21355. */
  21356. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  21357. /** Invokes the given command directly, sending it to the default target.
  21358. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  21359. structure.
  21360. */
  21361. bool invokeDirectly (CommandID commandID, bool asynchronously);
  21362. /** Sends a command to the default target.
  21363. This will choose a target using getFirstCommandTarget(), and send the specified command
  21364. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  21365. first target can't handle the command, it will be passed on to targets further down the
  21366. chain (see ApplicationCommandTarget::invoke() for more info).
  21367. @param invocationInfo this must be correctly filled-in, describing the context for
  21368. the invocation.
  21369. @param asynchronously if false, the command will be performed before this method returns.
  21370. If true, a message will be posted so that the command will be performed
  21371. later on the message thread, and this method will return immediately.
  21372. @see ApplicationCommandTarget::invoke
  21373. */
  21374. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  21375. bool asynchronously);
  21376. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  21377. Whenever the manager needs to know which target a command should be sent to, it calls
  21378. this method to determine the first one to try.
  21379. By default, this method will return the target that was set by calling setFirstCommandTarget().
  21380. If no target is set, it will return the result of findDefaultComponentTarget().
  21381. If you need to make sure all commands go via your own custom target, then you can
  21382. either use setFirstCommandTarget() to specify a single target, or override this method
  21383. if you need more complex logic to choose one.
  21384. It may return 0 if no targets are available.
  21385. @see getTargetForCommand, invoke, invokeDirectly
  21386. */
  21387. virtual ApplicationCommandTarget* getFirstCommandTarget (CommandID commandID);
  21388. /** Sets a target to be returned by getFirstCommandTarget().
  21389. If this is set to 0, then getFirstCommandTarget() will by default return the
  21390. result of findDefaultComponentTarget().
  21391. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  21392. deleting the target object.
  21393. */
  21394. void setFirstCommandTarget (ApplicationCommandTarget* newTarget) throw();
  21395. /** Tries to find the best target to use to perform a given command.
  21396. This will call getFirstCommandTarget() to find the preferred target, and will
  21397. check whether that target can handle the given command. If it can't, then it'll use
  21398. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  21399. so on until no more are available.
  21400. If no targets are found that can perform the command, this method will return 0.
  21401. If a target is found, then it will get the target to fill-in the upToDateInfo
  21402. structure with the latest info about that command, so that the caller can see
  21403. whether the command is disabled, ticked, etc.
  21404. */
  21405. ApplicationCommandTarget* getTargetForCommand (CommandID commandID,
  21406. ApplicationCommandInfo& upToDateInfo);
  21407. /** Registers a listener that will be called when various events occur. */
  21408. void addListener (ApplicationCommandManagerListener* listener) throw();
  21409. /** Deregisters a previously-added listener. */
  21410. void removeListener (ApplicationCommandManagerListener* listener) throw();
  21411. /** Looks for a suitable command target based on which Components have the keyboard focus.
  21412. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  21413. but is exposed here in case it's useful.
  21414. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  21415. windows, etc., and using the findTargetForComponent() method.
  21416. */
  21417. static ApplicationCommandTarget* findDefaultComponentTarget();
  21418. /** Examines this component and all its parents in turn, looking for the first one
  21419. which is a ApplicationCommandTarget.
  21420. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  21421. that class.
  21422. */
  21423. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  21424. juce_UseDebuggingNewOperator
  21425. private:
  21426. OwnedArray <ApplicationCommandInfo> commands;
  21427. ListenerList <ApplicationCommandManagerListener> listeners;
  21428. ScopedPointer <KeyPressMappingSet> keyMappings;
  21429. ApplicationCommandTarget* firstTarget;
  21430. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info);
  21431. void handleAsyncUpdate();
  21432. void globalFocusChanged (Component*);
  21433. // xxx this is just here to cause a compile error in old code that hasn't been changed to use the new
  21434. // version of this method.
  21435. virtual short getFirstCommandTarget() { return 0; }
  21436. ApplicationCommandManager (const ApplicationCommandManager&);
  21437. ApplicationCommandManager& operator= (const ApplicationCommandManager&);
  21438. };
  21439. /**
  21440. A listener that receives callbacks from an ApplicationCommandManager when
  21441. commands are invoked or the command list is changed.
  21442. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  21443. */
  21444. class JUCE_API ApplicationCommandManagerListener
  21445. {
  21446. public:
  21447. /** Destructor. */
  21448. virtual ~ApplicationCommandManagerListener() {}
  21449. /** Called when an app command is about to be invoked. */
  21450. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  21451. /** Called when commands are registered or deregistered from the
  21452. command manager, or when commands are made active or inactive.
  21453. Note that if you're using this to watch for changes to whether a command is disabled,
  21454. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  21455. whenever the status of your command might have changed.
  21456. */
  21457. virtual void applicationCommandListChanged() = 0;
  21458. };
  21459. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  21460. /*** End of inlined file: juce_ApplicationCommandManager.h ***/
  21461. #endif
  21462. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  21463. #endif
  21464. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21465. /*** Start of inlined file: juce_ApplicationProperties.h ***/
  21466. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21467. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21468. /*** Start of inlined file: juce_PropertiesFile.h ***/
  21469. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  21470. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  21471. /** Wrapper on a file that stores a list of key/value data pairs.
  21472. Useful for storing application settings, etc. See the PropertySet class for
  21473. the interfaces that read and write values.
  21474. Not designed for very large amounts of data, as it keeps all the values in
  21475. memory and writes them out to disk lazily when they are changed.
  21476. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  21477. with it, and these will be signalled when a value changes.
  21478. @see PropertySet
  21479. */
  21480. class JUCE_API PropertiesFile : public PropertySet,
  21481. public ChangeBroadcaster,
  21482. private Timer
  21483. {
  21484. public:
  21485. enum FileFormatOptions
  21486. {
  21487. ignoreCaseOfKeyNames = 1,
  21488. storeAsBinary = 2,
  21489. storeAsCompressedBinary = 4,
  21490. storeAsXML = 8
  21491. };
  21492. /**
  21493. Creates a PropertiesFile object.
  21494. @param file the file to use
  21495. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  21496. is changed, the object will wait for this amount
  21497. of time and then save the file. If zero, the file
  21498. will be written to disk immediately on being changed
  21499. (which might be slow, as it'll re-write synchronously
  21500. each time a value-change method is called). If it is
  21501. less than zero, the file won't be saved until
  21502. save() or saveIfNeeded() are explicitly called.
  21503. @param optionFlags a combination of the flags in the FileFormatOptions
  21504. enum, which specify the type of file to save, and other
  21505. options.
  21506. @param processLock an optional InterprocessLock object that will be used to
  21507. prevent multiple threads or processes from writing to the file
  21508. at the same time. The PropertiesFile will keep a pointer to
  21509. this object but will not take ownership of it - the caller is
  21510. responsible for making sure that the lock doesn't get deleted
  21511. before the PropertiesFile has been deleted.
  21512. */
  21513. PropertiesFile (const File& file,
  21514. int millisecondsBeforeSaving,
  21515. int optionFlags,
  21516. InterProcessLock* processLock = 0);
  21517. /** Destructor.
  21518. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  21519. */
  21520. ~PropertiesFile();
  21521. /** Returns true if this file was created from a valid (or non-existent) file.
  21522. If the file failed to load correctly because it was corrupt or had insufficient
  21523. access, this will be false.
  21524. */
  21525. bool isValidFile() const throw() { return loadedOk; }
  21526. /** This will flush all the values to disk if they've changed since the last
  21527. time they were saved.
  21528. Returns false if it fails to write to the file for some reason (maybe because
  21529. it's read-only or the directory doesn't exist or something).
  21530. @see save
  21531. */
  21532. bool saveIfNeeded();
  21533. /** This will force a write-to-disk of the current values, regardless of whether
  21534. anything has changed since the last save.
  21535. Returns false if it fails to write to the file for some reason (maybe because
  21536. it's read-only or the directory doesn't exist or something).
  21537. @see saveIfNeeded
  21538. */
  21539. bool save();
  21540. /** Returns true if the properties have been altered since the last time they were saved.
  21541. The file is flagged as needing to be saved when you change a value, but you can
  21542. explicitly set this flag with setNeedsToBeSaved().
  21543. */
  21544. bool needsToBeSaved() const;
  21545. /** Explicitly sets the flag to indicate whether the file needs saving or not.
  21546. @see needsToBeSaved
  21547. */
  21548. void setNeedsToBeSaved (bool needsToBeSaved);
  21549. /** Returns the file that's being used. */
  21550. const File getFile() const { return file; }
  21551. /** Handy utility to create a properties file in whatever the standard OS-specific
  21552. location is for these things.
  21553. This uses getDefaultAppSettingsFile() to decide what file to create, then
  21554. creates a PropertiesFile object with the specified properties. See
  21555. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  21556. what the parameters do.
  21557. @see getDefaultAppSettingsFile
  21558. */
  21559. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  21560. const String& fileNameSuffix,
  21561. const String& folderName,
  21562. bool commonToAllUsers,
  21563. int millisecondsBeforeSaving,
  21564. int propertiesFileOptions,
  21565. InterProcessLock* processLock = 0);
  21566. /** Handy utility to choose a file in the standard OS-dependent location for application
  21567. settings files.
  21568. So on a Mac, this will return a file called:
  21569. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  21570. On Windows it'll return something like:
  21571. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  21572. On Linux it'll return
  21573. ~/.[folderName]/[applicationName].[fileNameSuffix]
  21574. If you pass an empty string as the folder name, it'll use the app name for this (or
  21575. omit the folder name on the Mac).
  21576. If commonToAllUsers is true, then this will return the same file for all users of the
  21577. computer, regardless of the current user. If it is false, the file will be specific to
  21578. only the current user. Use this to choose whether you're saving settings that are common
  21579. or user-specific.
  21580. */
  21581. static const File getDefaultAppSettingsFile (const String& applicationName,
  21582. const String& fileNameSuffix,
  21583. const String& folderName,
  21584. bool commonToAllUsers);
  21585. juce_UseDebuggingNewOperator
  21586. protected:
  21587. virtual void propertyChanged();
  21588. private:
  21589. File file;
  21590. int timerInterval;
  21591. const int options;
  21592. bool loadedOk, needsWriting;
  21593. InterProcessLock* processLock;
  21594. typedef const ScopedPointer<InterProcessLock::ScopedLockType> ProcessScopedLock;
  21595. InterProcessLock::ScopedLockType* createProcessLock() const;
  21596. void timerCallback();
  21597. PropertiesFile (const PropertiesFile&);
  21598. PropertiesFile& operator= (const PropertiesFile&);
  21599. };
  21600. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  21601. /*** End of inlined file: juce_PropertiesFile.h ***/
  21602. /**
  21603. Manages a collection of properties.
  21604. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  21605. as a singleton.
  21606. It holds two different PropertiesFile objects internally, one for user-specific
  21607. settings (stored in your user directory), and one for settings that are common to
  21608. all users (stored in a folder accessible to all users).
  21609. The class manages the creation of these files on-demand, allowing access via the
  21610. getUserSettings() and getCommonSettings() methods. It also has a few handy
  21611. methods like testWriteAccess() to check that the files can be saved.
  21612. If you're using one of these as a singleton, then your app's start-up code should
  21613. first of all call setStorageParameters() to tell it the parameters to use to create
  21614. the properties files.
  21615. @see PropertiesFile
  21616. */
  21617. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  21618. {
  21619. public:
  21620. /**
  21621. Creates an ApplicationProperties object.
  21622. Before using it, you must call setStorageParameters() to give it the info
  21623. it needs to create the property files.
  21624. */
  21625. ApplicationProperties() throw();
  21626. /** Destructor.
  21627. */
  21628. ~ApplicationProperties();
  21629. juce_DeclareSingleton (ApplicationProperties, false)
  21630. /** Gives the object the information it needs to create the appropriate properties files.
  21631. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  21632. info about how these parameters are used.
  21633. */
  21634. void setStorageParameters (const String& applicationName,
  21635. const String& fileNameSuffix,
  21636. const String& folderName,
  21637. int millisecondsBeforeSaving,
  21638. int propertiesFileOptions) throw();
  21639. /** Tests whether the files can be successfully written to, and can show
  21640. an error message if not.
  21641. Returns true if none of the tests fail.
  21642. @param testUserSettings if true, the user settings file will be tested
  21643. @param testCommonSettings if true, the common settings file will be tested
  21644. @param showWarningDialogOnFailure if true, the method will show a helpful error
  21645. message box if either of the tests fail
  21646. */
  21647. bool testWriteAccess (bool testUserSettings,
  21648. bool testCommonSettings,
  21649. bool showWarningDialogOnFailure);
  21650. /** Returns the user settings file.
  21651. The first time this is called, it will create and load the properties file.
  21652. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  21653. the common settings are used as a second-chance place to look. This is done via the
  21654. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  21655. to the fallback for the user settings.
  21656. @see getCommonSettings
  21657. */
  21658. PropertiesFile* getUserSettings() throw();
  21659. /** Returns the common settings file.
  21660. The first time this is called, it will create and load the properties file.
  21661. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  21662. read-only (e.g. because the user doesn't have permission to write
  21663. to shared files), then this will return the user settings instead,
  21664. (like getUserSettings() would do). This is handy if you'd like to
  21665. write a value to the common settings, but if that's no possible,
  21666. then you'd rather write to the user settings than none at all.
  21667. If returnUserPropsIfReadOnly is false, this method will always return
  21668. the common settings, even if any changes to them can't be saved.
  21669. @see getUserSettings
  21670. */
  21671. PropertiesFile* getCommonSettings (bool returnUserPropsIfReadOnly) throw();
  21672. /** Saves both files if they need to be saved.
  21673. @see PropertiesFile::saveIfNeeded
  21674. */
  21675. bool saveIfNeeded();
  21676. /** Flushes and closes both files if they are open.
  21677. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  21678. and closes both files. They will then be re-opened the next time getUserSettings()
  21679. or getCommonSettings() is called.
  21680. */
  21681. void closeFiles();
  21682. juce_UseDebuggingNewOperator
  21683. private:
  21684. ScopedPointer <PropertiesFile> userProps, commonProps;
  21685. String appName, fileSuffix, folderName;
  21686. int msBeforeSaving, options;
  21687. int commonSettingsAreReadOnly;
  21688. ApplicationProperties (const ApplicationProperties&);
  21689. ApplicationProperties& operator= (const ApplicationProperties&);
  21690. void openFiles() throw();
  21691. };
  21692. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21693. /*** End of inlined file: juce_ApplicationProperties.h ***/
  21694. #endif
  21695. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  21696. /*** Start of inlined file: juce_AiffAudioFormat.h ***/
  21697. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  21698. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  21699. /*** Start of inlined file: juce_AudioFormat.h ***/
  21700. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  21701. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  21702. /*** Start of inlined file: juce_AudioFormatReader.h ***/
  21703. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  21704. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  21705. class AudioFormat;
  21706. /**
  21707. Reads samples from an audio file stream.
  21708. A subclass that reads a specific type of audio format will be created by
  21709. an AudioFormat object.
  21710. @see AudioFormat, AudioFormatWriter
  21711. */
  21712. class JUCE_API AudioFormatReader
  21713. {
  21714. protected:
  21715. /** Creates an AudioFormatReader object.
  21716. @param sourceStream the stream to read from - this will be deleted
  21717. by this object when it is no longer needed. (Some
  21718. specialised readers might not use this parameter and
  21719. can leave it as 0).
  21720. @param formatName the description that will be returned by the getFormatName()
  21721. method
  21722. */
  21723. AudioFormatReader (InputStream* sourceStream,
  21724. const String& formatName);
  21725. public:
  21726. /** Destructor. */
  21727. virtual ~AudioFormatReader();
  21728. /** Returns a description of what type of format this is.
  21729. E.g. "AIFF"
  21730. */
  21731. const String getFormatName() const throw() { return formatName; }
  21732. /** Reads samples from the stream.
  21733. @param destSamples an array of buffers into which the sample data for each
  21734. channel will be written.
  21735. If the format is fixed-point, each channel will be written
  21736. as an array of 32-bit signed integers using the full
  21737. range -0x80000000 to 0x7fffffff, regardless of the source's
  21738. bit-depth. If it is a floating-point format, you should cast
  21739. the resulting array to a (float**) to get the values (in the
  21740. range -1.0 to 1.0 or beyond)
  21741. If the format is stereo, then destSamples[0] is the left channel
  21742. data, and destSamples[1] is the right channel.
  21743. The numDestChannels parameter indicates how many pointers this array
  21744. contains, but some of these pointers can be null if you don't want to
  21745. read data for some of the channels
  21746. @param numDestChannels the number of array elements in the destChannels array
  21747. @param startSampleInSource the position in the audio file or stream at which the samples
  21748. should be read, as a number of samples from the start of the
  21749. stream. It's ok for this to be beyond the start or end of the
  21750. available data - any samples that are out-of-range will be returned
  21751. as zeros.
  21752. @param numSamplesToRead the number of samples to read. If this is greater than the number
  21753. of samples that the file or stream contains. the result will be padded
  21754. with zeros
  21755. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  21756. for some of the channels that you pass in, then they should be filled with
  21757. copies of valid source channels.
  21758. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  21759. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  21760. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  21761. was false, then only the first channel would be filled with the file's contents, and
  21762. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  21763. from a stereo file, then the last 3 would all end up with copies of the same data.
  21764. @returns true if the operation succeeded, false if there was an error. Note
  21765. that reading sections of data beyond the extent of the stream isn't an
  21766. error - the reader should just return zeros for these regions
  21767. @see readMaxLevels
  21768. */
  21769. bool read (int** destSamples,
  21770. int numDestChannels,
  21771. int64 startSampleInSource,
  21772. int numSamplesToRead,
  21773. bool fillLeftoverChannelsWithCopies);
  21774. /** Finds the highest and lowest sample levels from a section of the audio stream.
  21775. This will read a block of samples from the stream, and measure the
  21776. highest and lowest sample levels from the channels in that section, returning
  21777. these as normalised floating-point levels.
  21778. @param startSample the offset into the audio stream to start reading from. It's
  21779. ok for this to be beyond the start or end of the stream.
  21780. @param numSamples how many samples to read
  21781. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  21782. @param highestLeft on return, this is the highest absolute sample from the left channel
  21783. @param lowestRight on return, this is the lowest absolute sample from the right
  21784. channel (if there is one)
  21785. @param highestRight on return, this is the highest absolute sample from the right
  21786. channel (if there is one)
  21787. @see read
  21788. */
  21789. virtual void readMaxLevels (int64 startSample,
  21790. int64 numSamples,
  21791. float& lowestLeft,
  21792. float& highestLeft,
  21793. float& lowestRight,
  21794. float& highestRight);
  21795. /** Scans the source looking for a sample whose magnitude is in a specified range.
  21796. This will read from the source, either forwards or backwards between two sample
  21797. positions, until it finds a sample whose magnitude lies between two specified levels.
  21798. If it finds a suitable sample, it returns its position; if not, it will return -1.
  21799. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  21800. points when you're searching for a continuous range of samples
  21801. @param startSample the first sample to look at
  21802. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  21803. the search will go backwards
  21804. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  21805. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  21806. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  21807. of this many consecutive samples, all of which lie
  21808. within the target range. When it finds such a sequence,
  21809. it returns the position of the first in-range sample
  21810. it found (i.e. the earliest one if scanning forwards, the
  21811. latest one if scanning backwards)
  21812. */
  21813. int64 searchForLevel (int64 startSample,
  21814. int64 numSamplesToSearch,
  21815. double magnitudeRangeMinimum,
  21816. double magnitudeRangeMaximum,
  21817. int minimumConsecutiveSamples);
  21818. /** The sample-rate of the stream. */
  21819. double sampleRate;
  21820. /** The number of bits per sample, e.g. 16, 24, 32. */
  21821. unsigned int bitsPerSample;
  21822. /** The total number of samples in the audio stream. */
  21823. int64 lengthInSamples;
  21824. /** The total number of channels in the audio stream. */
  21825. unsigned int numChannels;
  21826. /** Indicates whether the data is floating-point or fixed. */
  21827. bool usesFloatingPointData;
  21828. /** A set of metadata values that the reader has pulled out of the stream.
  21829. Exactly what these values are depends on the format, so you can
  21830. check out the format implementation code to see what kind of stuff
  21831. they understand.
  21832. */
  21833. StringPairArray metadataValues;
  21834. /** The input stream, for use by subclasses. */
  21835. InputStream* input;
  21836. /** Subclasses must implement this method to perform the low-level read operation.
  21837. Callers should use read() instead of calling this directly.
  21838. @param destSamples the array of destination buffers to fill. Some of these
  21839. pointers may be null
  21840. @param numDestChannels the number of items in the destSamples array. This
  21841. value is guaranteed not to be greater than the number of
  21842. channels that this reader object contains
  21843. @param startOffsetInDestBuffer the number of samples from the start of the
  21844. dest data at which to begin writing
  21845. @param startSampleInFile the number of samples into the source data at which
  21846. to begin reading. This value is guaranteed to be >= 0.
  21847. @param numSamples the number of samples to read
  21848. */
  21849. virtual bool readSamples (int** destSamples,
  21850. int numDestChannels,
  21851. int startOffsetInDestBuffer,
  21852. int64 startSampleInFile,
  21853. int numSamples) = 0;
  21854. juce_UseDebuggingNewOperator
  21855. private:
  21856. String formatName;
  21857. AudioFormatReader (const AudioFormatReader&);
  21858. AudioFormatReader& operator= (const AudioFormatReader&);
  21859. };
  21860. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  21861. /*** End of inlined file: juce_AudioFormatReader.h ***/
  21862. /*** Start of inlined file: juce_AudioFormatWriter.h ***/
  21863. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  21864. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  21865. /*** Start of inlined file: juce_AudioSource.h ***/
  21866. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  21867. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  21868. /*** Start of inlined file: juce_AudioSampleBuffer.h ***/
  21869. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  21870. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  21871. class AudioFormatReader;
  21872. class AudioFormatWriter;
  21873. /**
  21874. A multi-channel buffer of 32-bit floating point audio samples.
  21875. */
  21876. class JUCE_API AudioSampleBuffer
  21877. {
  21878. public:
  21879. /** Creates a buffer with a specified number of channels and samples.
  21880. The contents of the buffer will initially be undefined, so use clear() to
  21881. set all the samples to zero.
  21882. The buffer will allocate its memory internally, and this will be released
  21883. when the buffer is deleted.
  21884. */
  21885. AudioSampleBuffer (int numChannels,
  21886. int numSamples) throw();
  21887. /** Creates a buffer using a pre-allocated block of memory.
  21888. Note that if the buffer is resized or its number of channels is changed, it
  21889. will re-allocate memory internally and copy the existing data to this new area,
  21890. so it will then stop directly addressing this memory.
  21891. @param dataToReferTo a pre-allocated array containing pointers to the data
  21892. for each channel that should be used by this buffer. The
  21893. buffer will only refer to this memory, it won't try to delete
  21894. it when the buffer is deleted or resized.
  21895. @param numChannels the number of channels to use - this must correspond to the
  21896. number of elements in the array passed in
  21897. @param numSamples the number of samples to use - this must correspond to the
  21898. size of the arrays passed in
  21899. */
  21900. AudioSampleBuffer (float** dataToReferTo,
  21901. int numChannels,
  21902. int numSamples) throw();
  21903. /** Copies another buffer.
  21904. This buffer will make its own copy of the other's data, unless the buffer was created
  21905. using an external data buffer, in which case boths buffers will just point to the same
  21906. shared block of data.
  21907. */
  21908. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  21909. /** Copies another buffer onto this one.
  21910. This buffer's size will be changed to that of the other buffer.
  21911. */
  21912. AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  21913. /** Destructor.
  21914. This will free any memory allocated by the buffer.
  21915. */
  21916. virtual ~AudioSampleBuffer() throw();
  21917. /** Returns the number of channels of audio data that this buffer contains.
  21918. @see getSampleData
  21919. */
  21920. int getNumChannels() const throw() { return numChannels; }
  21921. /** Returns the number of samples allocated in each of the buffer's channels.
  21922. @see getSampleData
  21923. */
  21924. int getNumSamples() const throw() { return size; }
  21925. /** Returns a pointer one of the buffer's channels.
  21926. For speed, this doesn't check whether the channel number is out of range,
  21927. so be careful when using it!
  21928. */
  21929. float* getSampleData (const int channelNumber) const throw()
  21930. {
  21931. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  21932. return channels [channelNumber];
  21933. }
  21934. /** Returns a pointer to a sample in one of the buffer's channels.
  21935. For speed, this doesn't check whether the channel and sample number
  21936. are out-of-range, so be careful when using it!
  21937. */
  21938. float* getSampleData (const int channelNumber,
  21939. const int sampleOffset) const throw()
  21940. {
  21941. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  21942. jassert (((unsigned int) sampleOffset) < (unsigned int) size);
  21943. return channels [channelNumber] + sampleOffset;
  21944. }
  21945. /** Returns an array of pointers to the channels in the buffer.
  21946. Don't modify any of the pointers that are returned, and bear in mind that
  21947. these will become invalid if the buffer is resized.
  21948. */
  21949. float** getArrayOfChannels() const throw() { return channels; }
  21950. /** Chages the buffer's size or number of channels.
  21951. This can expand or contract the buffer's length, and add or remove channels.
  21952. If keepExistingContent is true, it will try to preserve as much of the
  21953. old data as it can in the new buffer.
  21954. If clearExtraSpace is true, then any extra channels or space that is
  21955. allocated will be also be cleared. If false, then this space is left
  21956. uninitialised.
  21957. If avoidReallocating is true, then changing the buffer's size won't reduce the
  21958. amount of memory that is currently allocated (but it will still increase it if
  21959. the new size is bigger than the amount it currently has). If this is false, then
  21960. a new allocation will be done so that the buffer uses takes up the minimum amount
  21961. of memory that it needs.
  21962. */
  21963. void setSize (int newNumChannels,
  21964. int newNumSamples,
  21965. bool keepExistingContent = false,
  21966. bool clearExtraSpace = false,
  21967. bool avoidReallocating = false) throw();
  21968. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  21969. There's also a constructor that lets you specify arrays like this, but this
  21970. lets you change the channels dynamically.
  21971. Note that if the buffer is resized or its number of channels is changed, it
  21972. will re-allocate memory internally and copy the existing data to this new area,
  21973. so it will then stop directly addressing this memory.
  21974. @param dataToReferTo a pre-allocated array containing pointers to the data
  21975. for each channel that should be used by this buffer. The
  21976. buffer will only refer to this memory, it won't try to delete
  21977. it when the buffer is deleted or resized.
  21978. @param numChannels the number of channels to use - this must correspond to the
  21979. number of elements in the array passed in
  21980. @param numSamples the number of samples to use - this must correspond to the
  21981. size of the arrays passed in
  21982. */
  21983. void setDataToReferTo (float** dataToReferTo,
  21984. int numChannels,
  21985. int numSamples) throw();
  21986. /** Clears all the samples in all channels. */
  21987. void clear() throw();
  21988. /** Clears a specified region of all the channels.
  21989. For speed, this doesn't check whether the channel and sample number
  21990. are in-range, so be careful!
  21991. */
  21992. void clear (int startSample,
  21993. int numSamples) throw();
  21994. /** Clears a specified region of just one channel.
  21995. For speed, this doesn't check whether the channel and sample number
  21996. are in-range, so be careful!
  21997. */
  21998. void clear (int channel,
  21999. int startSample,
  22000. int numSamples) throw();
  22001. /** Applies a gain multiple to a region of one channel.
  22002. For speed, this doesn't check whether the channel and sample number
  22003. are in-range, so be careful!
  22004. */
  22005. void applyGain (int channel,
  22006. int startSample,
  22007. int numSamples,
  22008. float gain) throw();
  22009. /** Applies a gain multiple to a region of all the channels.
  22010. For speed, this doesn't check whether the sample numbers
  22011. are in-range, so be careful!
  22012. */
  22013. void applyGain (int startSample,
  22014. int numSamples,
  22015. float gain) throw();
  22016. /** Applies a range of gains to a region of a channel.
  22017. The gain that is applied to each sample will vary from
  22018. startGain on the first sample to endGain on the last Sample,
  22019. so it can be used to do basic fades.
  22020. For speed, this doesn't check whether the sample numbers
  22021. are in-range, so be careful!
  22022. */
  22023. void applyGainRamp (int channel,
  22024. int startSample,
  22025. int numSamples,
  22026. float startGain,
  22027. float endGain) throw();
  22028. /** Adds samples from another buffer to this one.
  22029. @param destChannel the channel within this buffer to add the samples to
  22030. @param destStartSample the start sample within this buffer's channel
  22031. @param source the source buffer to add from
  22032. @param sourceChannel the channel within the source buffer to read from
  22033. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  22034. @param numSamples the number of samples to process
  22035. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  22036. added to this buffer's samples
  22037. @see copyFrom
  22038. */
  22039. void addFrom (int destChannel,
  22040. int destStartSample,
  22041. const AudioSampleBuffer& source,
  22042. int sourceChannel,
  22043. int sourceStartSample,
  22044. int numSamples,
  22045. float gainToApplyToSource = 1.0f) throw();
  22046. /** Adds samples from an array of floats to one of the channels.
  22047. @param destChannel the channel within this buffer to add the samples to
  22048. @param destStartSample the start sample within this buffer's channel
  22049. @param source the source data to use
  22050. @param numSamples the number of samples to process
  22051. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  22052. added to this buffer's samples
  22053. @see copyFrom
  22054. */
  22055. void addFrom (int destChannel,
  22056. int destStartSample,
  22057. const float* source,
  22058. int numSamples,
  22059. float gainToApplyToSource = 1.0f) throw();
  22060. /** Adds samples from an array of floats, applying a gain ramp to them.
  22061. @param destChannel the channel within this buffer to add the samples to
  22062. @param destStartSample the start sample within this buffer's channel
  22063. @param source the source data to use
  22064. @param numSamples the number of samples to process
  22065. @param startGain the gain to apply to the first sample (this is multiplied with
  22066. the source samples before they are added to this buffer)
  22067. @param endGain the gain to apply to the final sample. The gain is linearly
  22068. interpolated between the first and last samples.
  22069. */
  22070. void addFromWithRamp (int destChannel,
  22071. int destStartSample,
  22072. const float* source,
  22073. int numSamples,
  22074. float startGain,
  22075. float endGain) throw();
  22076. /** Copies samples from another buffer to this one.
  22077. @param destChannel the channel within this buffer to copy the samples to
  22078. @param destStartSample the start sample within this buffer's channel
  22079. @param source the source buffer to read from
  22080. @param sourceChannel the channel within the source buffer to read from
  22081. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  22082. @param numSamples the number of samples to process
  22083. @see addFrom
  22084. */
  22085. void copyFrom (int destChannel,
  22086. int destStartSample,
  22087. const AudioSampleBuffer& source,
  22088. int sourceChannel,
  22089. int sourceStartSample,
  22090. int numSamples) throw();
  22091. /** Copies samples from an array of floats into one of the channels.
  22092. @param destChannel the channel within this buffer to copy the samples to
  22093. @param destStartSample the start sample within this buffer's channel
  22094. @param source the source buffer to read from
  22095. @param numSamples the number of samples to process
  22096. @see addFrom
  22097. */
  22098. void copyFrom (int destChannel,
  22099. int destStartSample,
  22100. const float* source,
  22101. int numSamples) throw();
  22102. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  22103. @param destChannel the channel within this buffer to copy the samples to
  22104. @param destStartSample the start sample within this buffer's channel
  22105. @param source the source buffer to read from
  22106. @param numSamples the number of samples to process
  22107. @param gain the gain to apply
  22108. @see addFrom
  22109. */
  22110. void copyFrom (int destChannel,
  22111. int destStartSample,
  22112. const float* source,
  22113. int numSamples,
  22114. float gain) throw();
  22115. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  22116. @param destChannel the channel within this buffer to copy the samples to
  22117. @param destStartSample the start sample within this buffer's channel
  22118. @param source the source buffer to read from
  22119. @param numSamples the number of samples to process
  22120. @param startGain the gain to apply to the first sample (this is multiplied with
  22121. the source samples before they are copied to this buffer)
  22122. @param endGain the gain to apply to the final sample. The gain is linearly
  22123. interpolated between the first and last samples.
  22124. @see addFrom
  22125. */
  22126. void copyFromWithRamp (int destChannel,
  22127. int destStartSample,
  22128. const float* source,
  22129. int numSamples,
  22130. float startGain,
  22131. float endGain) throw();
  22132. /** Finds the highest and lowest sample values in a given range.
  22133. @param channel the channel to read from
  22134. @param startSample the start sample within the channel
  22135. @param numSamples the number of samples to check
  22136. @param minVal on return, the lowest value that was found
  22137. @param maxVal on return, the highest value that was found
  22138. */
  22139. void findMinMax (int channel,
  22140. int startSample,
  22141. int numSamples,
  22142. float& minVal,
  22143. float& maxVal) const throw();
  22144. /** Finds the highest absolute sample value within a region of a channel.
  22145. */
  22146. float getMagnitude (int channel,
  22147. int startSample,
  22148. int numSamples) const throw();
  22149. /** Finds the highest absolute sample value within a region on all channels.
  22150. */
  22151. float getMagnitude (int startSample,
  22152. int numSamples) const throw();
  22153. /** Returns the root mean squared level for a region of a channel.
  22154. */
  22155. float getRMSLevel (int channel,
  22156. int startSample,
  22157. int numSamples) const throw();
  22158. /** Fills a section of the buffer using an AudioReader as its source.
  22159. This will convert the reader's fixed- or floating-point data to
  22160. the buffer's floating-point format, and will try to intelligently
  22161. cope with mismatches between the number of channels in the reader
  22162. and the buffer.
  22163. @see writeToAudioWriter
  22164. */
  22165. void readFromAudioReader (AudioFormatReader* reader,
  22166. int startSample,
  22167. int numSamples,
  22168. int readerStartSample,
  22169. bool useReaderLeftChan,
  22170. bool useReaderRightChan) throw();
  22171. /** Writes a section of this buffer to an audio writer.
  22172. This saves you having to mess about with channels or floating/fixed
  22173. point conversion.
  22174. @see readFromAudioReader
  22175. */
  22176. void writeToAudioWriter (AudioFormatWriter* writer,
  22177. int startSample,
  22178. int numSamples) const throw();
  22179. juce_UseDebuggingNewOperator
  22180. private:
  22181. int numChannels, size;
  22182. size_t allocatedBytes;
  22183. float** channels;
  22184. HeapBlock <char> allocatedData;
  22185. float* preallocatedChannelSpace [32];
  22186. void allocateData();
  22187. void allocateChannels (float** dataToReferTo);
  22188. };
  22189. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  22190. /*** End of inlined file: juce_AudioSampleBuffer.h ***/
  22191. /**
  22192. Used by AudioSource::getNextAudioBlock().
  22193. */
  22194. struct JUCE_API AudioSourceChannelInfo
  22195. {
  22196. /** The destination buffer to fill with audio data.
  22197. When the AudioSource::getNextAudioBlock() method is called, the active section
  22198. of this buffer should be filled with whatever output the source produces.
  22199. Only the samples specified by the startSample and numSamples members of this structure
  22200. should be affected by the call.
  22201. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  22202. method can be treated as the input if the source is performing some kind of filter operation,
  22203. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  22204. a handy way of doing this.
  22205. The number of channels in the buffer could be anything, so the AudioSource
  22206. must cope with this in whatever way is appropriate for its function.
  22207. */
  22208. AudioSampleBuffer* buffer;
  22209. /** The first sample in the buffer from which the callback is expected
  22210. to write data. */
  22211. int startSample;
  22212. /** The number of samples in the buffer which the callback is expected to
  22213. fill with data. */
  22214. int numSamples;
  22215. /** Convenient method to clear the buffer if the source is not producing any data. */
  22216. void clearActiveBufferRegion() const
  22217. {
  22218. if (buffer != 0)
  22219. buffer->clear (startSample, numSamples);
  22220. }
  22221. };
  22222. /**
  22223. Base class for objects that can produce a continuous stream of audio.
  22224. @see AudioFormatReaderSource, ResamplingAudioSource
  22225. */
  22226. class JUCE_API AudioSource
  22227. {
  22228. protected:
  22229. /** Creates an AudioSource. */
  22230. AudioSource() throw() {}
  22231. public:
  22232. /** Destructor. */
  22233. virtual ~AudioSource() {}
  22234. /** Tells the source to prepare for playing.
  22235. The source can use this opportunity to initialise anything it needs to.
  22236. Note that this method could be called more than once in succession without
  22237. a matching call to releaseResources(), so make sure your code is robust and
  22238. can handle that kind of situation.
  22239. @param samplesPerBlockExpected the number of samples that the source
  22240. will be expected to supply each time its
  22241. getNextAudioBlock() method is called. This
  22242. number may vary slightly, because it will be dependent
  22243. on audio hardware callbacks, and these aren't
  22244. guaranteed to always use a constant block size, so
  22245. the source should be able to cope with small variations.
  22246. @param sampleRate the sample rate that the output will be used at - this
  22247. is needed by sources such as tone generators.
  22248. @see releaseResources, getNextAudioBlock
  22249. */
  22250. virtual void prepareToPlay (int samplesPerBlockExpected,
  22251. double sampleRate) = 0;
  22252. /** Allows the source to release anything it no longer needs after playback has stopped.
  22253. This will be called when the source is no longer going to have its getNextAudioBlock()
  22254. method called, so it should release any spare memory, etc. that it might have
  22255. allocated during the prepareToPlay() call.
  22256. Note that there's no guarantee that prepareToPlay() will actually have been called before
  22257. releaseResources(), and it may be called more than once in succession, so make sure your
  22258. code is robust and doesn't make any assumptions about when it will be called.
  22259. @see prepareToPlay, getNextAudioBlock
  22260. */
  22261. virtual void releaseResources() = 0;
  22262. /** Called repeatedly to fetch subsequent blocks of audio data.
  22263. After calling the prepareToPlay() method, this callback will be made each
  22264. time the audio playback hardware (or whatever other destination the audio
  22265. data is going to) needs another block of data.
  22266. It will generally be called on a high-priority system thread, or possibly even
  22267. an interrupt, so be careful not to do too much work here, as that will cause
  22268. audio glitches!
  22269. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  22270. */
  22271. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  22272. };
  22273. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  22274. /*** End of inlined file: juce_AudioSource.h ***/
  22275. /**
  22276. Writes samples to an audio file stream.
  22277. A subclass that writes a specific type of audio format will be created by
  22278. an AudioFormat object.
  22279. After creating one of these with the AudioFormat::createWriterFor() method
  22280. you can call its write() method to store the samples, and then delete it.
  22281. @see AudioFormat, AudioFormatReader
  22282. */
  22283. class JUCE_API AudioFormatWriter
  22284. {
  22285. protected:
  22286. /** Creates an AudioFormatWriter object.
  22287. @param destStream the stream to write to - this will be deleted
  22288. by this object when it is no longer needed
  22289. @param formatName the description that will be returned by the getFormatName()
  22290. method
  22291. @param sampleRate the sample rate to use - the base class just stores
  22292. this value, it doesn't do anything with it
  22293. @param numberOfChannels the number of channels to write - the base class just stores
  22294. this value, it doesn't do anything with it
  22295. @param bitsPerSample the bit depth of the stream - the base class just stores
  22296. this value, it doesn't do anything with it
  22297. */
  22298. AudioFormatWriter (OutputStream* destStream,
  22299. const String& formatName,
  22300. double sampleRate,
  22301. unsigned int numberOfChannels,
  22302. unsigned int bitsPerSample);
  22303. public:
  22304. /** Destructor. */
  22305. virtual ~AudioFormatWriter();
  22306. /** Returns a description of what type of format this is.
  22307. E.g. "AIFF file"
  22308. */
  22309. const String getFormatName() const throw() { return formatName; }
  22310. /** Writes a set of samples to the audio stream.
  22311. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  22312. can use AudioSampleBuffer::writeToAudioWriter().
  22313. @param samplesToWrite an array of arrays containing the sample data for
  22314. each channel to write. This is a zero-terminated
  22315. array of arrays, and can contain a different number
  22316. of channels than the actual stream uses, and the
  22317. writer should do its best to cope with this.
  22318. If the format is fixed-point, each channel will be formatted
  22319. as an array of signed integers using the full 32-bit
  22320. range -0x80000000 to 0x7fffffff, regardless of the source's
  22321. bit-depth. If it is a floating-point format, you should treat
  22322. the arrays as arrays of floats, and just cast it to an (int**)
  22323. to pass it into the method.
  22324. @param numSamples the number of samples to write
  22325. */
  22326. virtual bool write (const int** samplesToWrite,
  22327. int numSamples) = 0;
  22328. /** Reads a section of samples from an AudioFormatReader, and writes these to
  22329. the output.
  22330. This will take care of any floating-point conversion that's required to convert
  22331. between the two formats. It won't deal with sample-rate conversion, though.
  22332. If numSamplesToRead < 0, it will write the entire length of the reader.
  22333. @returns false if it can't read or write properly during the operation
  22334. */
  22335. bool writeFromAudioReader (AudioFormatReader& reader,
  22336. int64 startSample,
  22337. int64 numSamplesToRead);
  22338. /** Reads some samples from an AudioSource, and writes these to the output.
  22339. The source must already have been initialised with the AudioSource::prepareToPlay() method
  22340. @param source the source to read from
  22341. @param numSamplesToRead total number of samples to read and write
  22342. @param samplesPerBlock the maximum number of samples to fetch from the source
  22343. @returns false if it can't read or write properly during the operation
  22344. */
  22345. bool writeFromAudioSource (AudioSource& source,
  22346. int numSamplesToRead,
  22347. int samplesPerBlock = 2048);
  22348. /** Returns the sample rate being used. */
  22349. double getSampleRate() const throw() { return sampleRate; }
  22350. /** Returns the number of channels being written. */
  22351. int getNumChannels() const throw() { return numChannels; }
  22352. /** Returns the bit-depth of the data being written. */
  22353. int getBitsPerSample() const throw() { return bitsPerSample; }
  22354. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  22355. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  22356. juce_UseDebuggingNewOperator
  22357. protected:
  22358. /** The sample rate of the stream. */
  22359. double sampleRate;
  22360. /** The number of channels being written to the stream. */
  22361. unsigned int numChannels;
  22362. /** The bit depth of the file. */
  22363. unsigned int bitsPerSample;
  22364. /** True if it's a floating-point format, false if it's fixed-point. */
  22365. bool usesFloatingPointData;
  22366. /** The output stream for Use by subclasses. */
  22367. OutputStream* output;
  22368. private:
  22369. String formatName;
  22370. AudioFormatWriter (const AudioFormatWriter&);
  22371. AudioFormatWriter& operator= (const AudioFormatWriter&);
  22372. };
  22373. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  22374. /*** End of inlined file: juce_AudioFormatWriter.h ***/
  22375. /**
  22376. Subclasses of AudioFormat are used to read and write different audio
  22377. file formats.
  22378. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  22379. */
  22380. class JUCE_API AudioFormat
  22381. {
  22382. public:
  22383. /** Destructor. */
  22384. virtual ~AudioFormat();
  22385. /** Returns the name of this format.
  22386. e.g. "WAV file" or "AIFF file"
  22387. */
  22388. const String& getFormatName() const;
  22389. /** Returns all the file extensions that might apply to a file of this format.
  22390. The first item will be the one that's preferred when creating a new file.
  22391. So for a wav file this might just return ".wav"; for an AIFF file it might
  22392. return two items, ".aif" and ".aiff"
  22393. */
  22394. const StringArray& getFileExtensions() const;
  22395. /** Returns true if this the given file can be read by this format.
  22396. Subclasses shouldn't do too much work here, just check the extension or
  22397. file type. The base class implementation just checks the file's extension
  22398. against one of the ones that was registered in the constructor.
  22399. */
  22400. virtual bool canHandleFile (const File& fileToTest);
  22401. /** Returns a set of sample rates that the format can read and write. */
  22402. virtual const Array <int> getPossibleSampleRates() = 0;
  22403. /** Returns a set of bit depths that the format can read and write. */
  22404. virtual const Array <int> getPossibleBitDepths() = 0;
  22405. /** Returns true if the format can do 2-channel audio. */
  22406. virtual bool canDoStereo() = 0;
  22407. /** Returns true if the format can do 1-channel audio. */
  22408. virtual bool canDoMono() = 0;
  22409. /** Returns true if the format uses compressed data. */
  22410. virtual bool isCompressed();
  22411. /** Returns a list of different qualities that can be used when writing.
  22412. Non-compressed formats will just return an empty array, but for something
  22413. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  22414. When calling createWriterFor(), an index from this array is passed in to
  22415. tell the format which option is required.
  22416. */
  22417. virtual const StringArray getQualityOptions();
  22418. /** Tries to create an object that can read from a stream containing audio
  22419. data in this format.
  22420. The reader object that is returned can be used to read from the stream, and
  22421. should then be deleted by the caller.
  22422. @param sourceStream the stream to read from - the AudioFormatReader object
  22423. that is returned will delete this stream when it no longer
  22424. needs it.
  22425. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  22426. should delete the stream object that was passed-in. (If a valid
  22427. reader is returned, it will always be in charge of deleting the
  22428. stream, so this parameter is ignored)
  22429. @see AudioFormatReader
  22430. */
  22431. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  22432. const bool deleteStreamIfOpeningFails) = 0;
  22433. /** Tries to create an object that can write to a stream with this audio format.
  22434. The writer object that is returned can be used to write to the stream, and
  22435. should then be deleted by the caller.
  22436. If the stream can't be created for some reason (e.g. the parameters passed in
  22437. here aren't suitable), this will return 0.
  22438. @param streamToWriteTo the stream that the data will go to - this will be
  22439. deleted by the AudioFormatWriter object when it's no longer
  22440. needed. If no AudioFormatWriter can be created by this method,
  22441. the stream will NOT be deleted, so that the caller can re-use it
  22442. to try to open a different format, etc
  22443. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  22444. returned by getPossibleSampleRates()
  22445. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  22446. the choice will depend on the results of canDoMono() and
  22447. canDoStereo()
  22448. @param bitsPerSample the bits per sample to use - this must be one of the values
  22449. returned by getPossibleBitDepths()
  22450. @param metadataValues a set of metadata values that the writer should try to write
  22451. to the stream. Exactly what these are depends on the format,
  22452. and the subclass doesn't actually have to do anything with
  22453. them if it doesn't want to. Have a look at the specific format
  22454. implementation classes to see possible values that can be
  22455. used
  22456. @param qualityOptionIndex the index of one of compression qualities returned by the
  22457. getQualityOptions() method. If there aren't any quality options
  22458. for this format, just pass 0 in this parameter, as it'll be
  22459. ignored
  22460. @see AudioFormatWriter
  22461. */
  22462. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  22463. double sampleRateToUse,
  22464. unsigned int numberOfChannels,
  22465. int bitsPerSample,
  22466. const StringPairArray& metadataValues,
  22467. int qualityOptionIndex) = 0;
  22468. protected:
  22469. /** Creates an AudioFormat object.
  22470. @param formatName this sets the value that will be returned by getFormatName()
  22471. @param fileExtensions a zero-terminated list of file extensions - this is what will
  22472. be returned by getFileExtension()
  22473. */
  22474. AudioFormat (const String& formatName,
  22475. const StringArray& fileExtensions);
  22476. private:
  22477. String formatName;
  22478. StringArray fileExtensions;
  22479. };
  22480. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  22481. /*** End of inlined file: juce_AudioFormat.h ***/
  22482. /**
  22483. Reads and Writes AIFF format audio files.
  22484. @see AudioFormat
  22485. */
  22486. class JUCE_API AiffAudioFormat : public AudioFormat
  22487. {
  22488. public:
  22489. /** Creates an format object. */
  22490. AiffAudioFormat();
  22491. /** Destructor. */
  22492. ~AiffAudioFormat();
  22493. const Array <int> getPossibleSampleRates();
  22494. const Array <int> getPossibleBitDepths();
  22495. bool canDoStereo();
  22496. bool canDoMono();
  22497. #if JUCE_MAC
  22498. bool canHandleFile (const File& fileToTest);
  22499. #endif
  22500. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  22501. const bool deleteStreamIfOpeningFails);
  22502. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  22503. double sampleRateToUse,
  22504. unsigned int numberOfChannels,
  22505. int bitsPerSample,
  22506. const StringPairArray& metadataValues,
  22507. int qualityOptionIndex);
  22508. juce_UseDebuggingNewOperator
  22509. };
  22510. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  22511. /*** End of inlined file: juce_AiffAudioFormat.h ***/
  22512. #endif
  22513. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22514. /*** Start of inlined file: juce_AudioCDBurner.h ***/
  22515. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22516. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22517. #if JUCE_USE_CDBURNER || DOXYGEN
  22518. /**
  22519. */
  22520. class AudioCDBurner : public ChangeBroadcaster
  22521. {
  22522. public:
  22523. /** Returns a list of available optical drives.
  22524. Use openDevice() to open one of the items from this list.
  22525. */
  22526. static const StringArray findAvailableDevices();
  22527. /** Tries to open one of the optical drives.
  22528. The deviceIndex is an index into the array returned by findAvailableDevices().
  22529. */
  22530. static AudioCDBurner* openDevice (const int deviceIndex);
  22531. /** Destructor. */
  22532. ~AudioCDBurner();
  22533. enum DiskState
  22534. {
  22535. unknown, /**< An error condition, if the device isn't responding. */
  22536. trayOpen, /**< The drive is currently open. Note that a slot-loading drive
  22537. may seem to be permanently open. */
  22538. noDisc, /**< The drive has no disk in it. */
  22539. writableDiskPresent, /**< The drive contains a writeable disk. */
  22540. readOnlyDiskPresent /**< The drive contains a read-only disk. */
  22541. };
  22542. /** Returns the current status of the device.
  22543. To get informed when the drive's status changes, attach a ChangeListener to
  22544. the AudioCDBurner.
  22545. */
  22546. DiskState getDiskState() const;
  22547. /** Returns true if there's a writable disk in the drive. */
  22548. bool isDiskPresent() const;
  22549. /** Sends an eject signal to the drive.
  22550. The eject will happen asynchronously, so you can use getDiskState() and
  22551. waitUntilStateChange() to monitor its progress.
  22552. */
  22553. bool openTray();
  22554. /** Blocks the current thread until the drive's state changes, or until the timeout expires.
  22555. @returns the device's new state
  22556. */
  22557. DiskState waitUntilStateChange (int timeOutMilliseconds);
  22558. /** Returns the set of possible write speeds that the device can handle.
  22559. These are as a multiple of 'normal' speed, so e.g. '24x' returns 24, etc.
  22560. Note that if there's no media present in the drive, this value may be unavailable!
  22561. @see setWriteSpeed, getWriteSpeed
  22562. */
  22563. const Array<int> getAvailableWriteSpeeds() const;
  22564. /** Tries to enable or disable buffer underrun safety on devices that support it.
  22565. @returns true if it's now enabled. If the device doesn't support it, this
  22566. will always return false.
  22567. */
  22568. bool setBufferUnderrunProtection (const bool shouldBeEnabled);
  22569. /** Returns the number of free blocks on the disk.
  22570. There are 75 blocks per second, at 44100Hz.
  22571. */
  22572. int getNumAvailableAudioBlocks() const;
  22573. /** Adds a track to be written.
  22574. The source passed-in here will be kept by this object, and it will
  22575. be used and deleted at some point in the future, either during the
  22576. burn() method or when this AudioCDBurner object is deleted. Your caller
  22577. method shouldn't keep a reference to it or use it again after passing
  22578. it in here.
  22579. */
  22580. bool addAudioTrack (AudioSource* source, int numSamples);
  22581. /** Receives progress callbacks during a cd-burn operation.
  22582. @see AudioCDBurner::burn()
  22583. */
  22584. class BurnProgressListener
  22585. {
  22586. public:
  22587. BurnProgressListener() throw() {}
  22588. virtual ~BurnProgressListener() {}
  22589. /** Called at intervals to report on the progress of the AudioCDBurner.
  22590. To cancel the burn, return true from this method.
  22591. */
  22592. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  22593. };
  22594. /** Runs the burn process.
  22595. This method will block until the operation is complete.
  22596. @param listener the object to receive callbacks about progress
  22597. @param ejectDiscAfterwards whether to eject the disk after the burn completes
  22598. @param performFakeBurnForTesting if true, no data will actually be written to the disk
  22599. @param writeSpeed one of the write speeds from getAvailableWriteSpeeds(), or
  22600. 0 or less to mean the fastest speed.
  22601. */
  22602. const String burn (BurnProgressListener* listener,
  22603. bool ejectDiscAfterwards,
  22604. bool performFakeBurnForTesting,
  22605. int writeSpeed);
  22606. /** If a burn operation is currently in progress, this tells it to stop
  22607. as soon as possible.
  22608. It's also possible to stop the burn process by returning true from
  22609. BurnProgressListener::audioCDBurnProgress()
  22610. */
  22611. void abortBurn();
  22612. juce_UseDebuggingNewOperator
  22613. private:
  22614. AudioCDBurner (const int deviceIndex);
  22615. class Pimpl;
  22616. friend class ScopedPointer<Pimpl>;
  22617. ScopedPointer<Pimpl> pimpl;
  22618. };
  22619. #endif
  22620. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22621. /*** End of inlined file: juce_AudioCDBurner.h ***/
  22622. #endif
  22623. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  22624. /*** Start of inlined file: juce_AudioCDReader.h ***/
  22625. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  22626. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  22627. #if JUCE_USE_CDREADER || DOXYGEN
  22628. #if JUCE_MAC
  22629. #endif
  22630. /**
  22631. A type of AudioFormatReader that reads from an audio CD.
  22632. One of these can be used to read a CD as if it's one big audio stream. Use the
  22633. getPositionOfTrackStart() method to find where the individual tracks are
  22634. within the stream.
  22635. @see AudioFormatReader
  22636. */
  22637. class JUCE_API AudioCDReader : public AudioFormatReader
  22638. {
  22639. public:
  22640. /** Returns a list of names of Audio CDs currently available for reading.
  22641. If there's a CD drive but no CD in it, this might return an empty list, or
  22642. possibly a device that can be opened but which has no tracks, depending
  22643. on the platform.
  22644. @see createReaderForCD
  22645. */
  22646. static const StringArray getAvailableCDNames();
  22647. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  22648. @param index the index of one of the available CDs - use getAvailableCDNames()
  22649. to find out how many there are.
  22650. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  22651. caller will be responsible for deleting the object returned.
  22652. */
  22653. static AudioCDReader* createReaderForCD (const int index);
  22654. /** Destructor. */
  22655. ~AudioCDReader();
  22656. /** Implementation of the AudioFormatReader method. */
  22657. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  22658. int64 startSampleInFile, int numSamples);
  22659. /** Checks whether the CD has been removed from the drive.
  22660. */
  22661. bool isCDStillPresent() const;
  22662. /** Returns the total number of tracks (audio + data).
  22663. */
  22664. int getNumTracks() const;
  22665. /** Finds the sample offset of the start of a track.
  22666. @param trackNum the track number, where 0 is the first track.
  22667. */
  22668. int getPositionOfTrackStart (int trackNum) const;
  22669. /** Returns true if a given track is an audio track.
  22670. @param trackNum the track number, where 0 is the first track.
  22671. */
  22672. bool isTrackAudio (int trackNum) const;
  22673. /** Refreshes the object's table of contents.
  22674. If the disc has been ejected and a different one put in since this
  22675. object was created, this will cause it to update its idea of how many tracks
  22676. there are, etc.
  22677. */
  22678. void refreshTrackLengths();
  22679. /** Enables scanning for indexes within tracks.
  22680. @see getLastIndex
  22681. */
  22682. void enableIndexScanning (bool enabled);
  22683. /** Returns the index number found during the last read() call.
  22684. Index scanning is turned off by default - turn it on with enableIndexScanning().
  22685. Then when the read() method is called, if it comes across an index within that
  22686. block, the index number is stored and returned by this method.
  22687. Some devices might not support indexes, of course.
  22688. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  22689. @see enableIndexScanning
  22690. */
  22691. int getLastIndex() const;
  22692. /** Scans a track to find the position of any indexes within it.
  22693. @param trackNumber the track to look in, where 0 is the first track on the disc
  22694. @returns an array of sample positions of any index points found (not including
  22695. the index that marks the start of the track)
  22696. */
  22697. const Array <int> findIndexesInTrack (const int trackNumber);
  22698. /** Returns the CDDB id number for the CD.
  22699. It's not a great way of identifying a disc, but it's traditional.
  22700. */
  22701. int getCDDBId();
  22702. /** Tries to eject the disk.
  22703. Of course this might not be possible, if some other process is using it.
  22704. */
  22705. void ejectDisk();
  22706. juce_UseDebuggingNewOperator
  22707. private:
  22708. #if JUCE_MAC
  22709. File volumeDir;
  22710. Array<File> tracks;
  22711. Array<int> trackStartSamples;
  22712. int currentReaderTrack;
  22713. ScopedPointer <AudioFormatReader> reader;
  22714. AudioCDReader (const File& volume);
  22715. public:
  22716. static int compareElements (const File&, const File&);
  22717. private:
  22718. #elif JUCE_WINDOWS
  22719. int numTracks;
  22720. int trackStarts[100];
  22721. bool audioTracks [100];
  22722. void* handle;
  22723. bool indexingEnabled;
  22724. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  22725. MemoryBlock buffer;
  22726. AudioCDReader (void* handle);
  22727. int getIndexAt (int samplePos);
  22728. #elif JUCE_LINUX
  22729. AudioCDReader();
  22730. #endif
  22731. AudioCDReader (const AudioCDReader&);
  22732. AudioCDReader& operator= (const AudioCDReader&);
  22733. };
  22734. #endif
  22735. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  22736. /*** End of inlined file: juce_AudioCDReader.h ***/
  22737. #endif
  22738. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  22739. #endif
  22740. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  22741. /*** Start of inlined file: juce_AudioFormatManager.h ***/
  22742. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  22743. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  22744. /**
  22745. A class for keeping a list of available audio formats, and for deciding which
  22746. one to use to open a given file.
  22747. You can either use this class as a singleton object, or create instances of it
  22748. yourself. Once created, use its registerFormat() method to tell it which
  22749. formats it should use.
  22750. @see AudioFormat
  22751. */
  22752. class JUCE_API AudioFormatManager
  22753. {
  22754. public:
  22755. /** Creates an empty format manager.
  22756. Before it'll be any use, you'll need to call registerFormat() with all the
  22757. formats you want it to be able to recognise.
  22758. */
  22759. AudioFormatManager();
  22760. /** Destructor. */
  22761. ~AudioFormatManager();
  22762. juce_DeclareSingleton (AudioFormatManager, false);
  22763. /** Adds a format to the manager's list of available file types.
  22764. The object passed-in will be deleted by this object, so don't keep a pointer
  22765. to it!
  22766. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  22767. return this one when called.
  22768. */
  22769. void registerFormat (AudioFormat* newFormat,
  22770. bool makeThisTheDefaultFormat);
  22771. /** Handy method to make it easy to register the formats that come with Juce.
  22772. Currently, this will add WAV and AIFF to the list.
  22773. */
  22774. void registerBasicFormats();
  22775. /** Clears the list of known formats. */
  22776. void clearFormats();
  22777. /** Returns the number of currently registered file formats. */
  22778. int getNumKnownFormats() const;
  22779. /** Returns one of the registered file formats. */
  22780. AudioFormat* getKnownFormat (int index) const;
  22781. /** Looks for which of the known formats is listed as being for a given file
  22782. extension.
  22783. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  22784. */
  22785. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  22786. /** Returns the format which has been set as the default one.
  22787. You can set a format as being the default when it is registered. It's useful
  22788. when you want to write to a file, because the best format may change between
  22789. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  22790. If none has been set as the default, this method will just return the first
  22791. one in the list.
  22792. */
  22793. AudioFormat* getDefaultFormat() const;
  22794. /** Returns a set of wildcards for file-matching that contains the extensions for
  22795. all known formats.
  22796. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  22797. */
  22798. const String getWildcardForAllFormats() const;
  22799. /** Searches through the known formats to try to create a suitable reader for
  22800. this file.
  22801. If none of the registered formats can open the file, it'll return 0. If it
  22802. returns a reader, it's the caller's responsibility to delete the reader.
  22803. */
  22804. AudioFormatReader* createReaderFor (const File& audioFile);
  22805. /** Searches through the known formats to try to create a suitable reader for
  22806. this stream.
  22807. The stream object that is passed-in will be deleted by this method or by the
  22808. reader that is returned, so the caller should not keep any references to it.
  22809. The stream that is passed-in must be capable of being repositioned so
  22810. that all the formats can have a go at opening it.
  22811. If none of the registered formats can open the stream, it'll return 0. If it
  22812. returns a reader, it's the caller's responsibility to delete the reader.
  22813. */
  22814. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  22815. juce_UseDebuggingNewOperator
  22816. private:
  22817. OwnedArray<AudioFormat> knownFormats;
  22818. int defaultFormatIndex;
  22819. };
  22820. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  22821. /*** End of inlined file: juce_AudioFormatManager.h ***/
  22822. #endif
  22823. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  22824. #endif
  22825. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  22826. #endif
  22827. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  22828. /*** Start of inlined file: juce_AudioSubsectionReader.h ***/
  22829. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  22830. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  22831. /**
  22832. This class is used to wrap an AudioFormatReader and only read from a
  22833. subsection of the file.
  22834. So if you have a reader which can read a 1000 sample file, you could wrap it
  22835. in one of these to only access, e.g. samples 100 to 200, and any samples
  22836. outside that will come back as 0. Accessing sample 0 from this reader will
  22837. actually read the first sample from the other's subsection, which might
  22838. be at a non-zero position.
  22839. @see AudioFormatReader
  22840. */
  22841. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  22842. {
  22843. public:
  22844. /** Creates a AudioSubsectionReader for a given data source.
  22845. @param sourceReader the source reader from which we'll be taking data
  22846. @param subsectionStartSample the sample within the source reader which will be
  22847. mapped onto sample 0 for this reader.
  22848. @param subsectionLength the number of samples from the source that will
  22849. make up the subsection. If this reader is asked for
  22850. any samples beyond this region, it will return zero.
  22851. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  22852. this object is deleted.
  22853. */
  22854. AudioSubsectionReader (AudioFormatReader* sourceReader,
  22855. int64 subsectionStartSample,
  22856. int64 subsectionLength,
  22857. bool deleteSourceWhenDeleted);
  22858. /** Destructor. */
  22859. ~AudioSubsectionReader();
  22860. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  22861. int64 startSampleInFile, int numSamples);
  22862. void readMaxLevels (int64 startSample,
  22863. int64 numSamples,
  22864. float& lowestLeft,
  22865. float& highestLeft,
  22866. float& lowestRight,
  22867. float& highestRight);
  22868. juce_UseDebuggingNewOperator
  22869. private:
  22870. AudioFormatReader* const source;
  22871. int64 startSample, length;
  22872. const bool deleteSourceWhenDeleted;
  22873. AudioSubsectionReader (const AudioSubsectionReader&);
  22874. AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  22875. };
  22876. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  22877. /*** End of inlined file: juce_AudioSubsectionReader.h ***/
  22878. #endif
  22879. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  22880. /*** Start of inlined file: juce_AudioThumbnail.h ***/
  22881. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  22882. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  22883. class AudioThumbnailCache;
  22884. /**
  22885. Makes it easy to quickly draw scaled views of the waveform shape of an
  22886. audio file.
  22887. To use this class, just create an AudioThumbNail class for the file you want
  22888. to draw, call setSource to tell it which file or resource to use, then call
  22889. drawChannel() to draw it.
  22890. The class will asynchronously scan the wavefile to create its scaled-down view,
  22891. so you should make your UI repaint itself as this data comes in. To do this, the
  22892. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  22893. listeners should repaint themselves.
  22894. The thumbnail stores an internal low-res version of the wave data, and this can
  22895. be loaded and saved to avoid having to scan the file again.
  22896. @see AudioThumbnailCache
  22897. */
  22898. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  22899. public TimeSliceClient,
  22900. private Timer
  22901. {
  22902. public:
  22903. /** Creates an audio thumbnail.
  22904. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  22905. of the audio data, this is the scale at which it should be done. (This
  22906. number is the number of original samples that will be averaged for each
  22907. low-res sample)
  22908. @param formatManagerToUse the audio format manager that is used to open the file
  22909. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  22910. thread and storage that is used to by the thumbnail, and the cache
  22911. object can be shared between multiple thumbnails
  22912. */
  22913. AudioThumbnail (int sourceSamplesPerThumbnailSample,
  22914. AudioFormatManager& formatManagerToUse,
  22915. AudioThumbnailCache& cacheToUse);
  22916. /** Destructor. */
  22917. ~AudioThumbnail();
  22918. /** Specifies the file or stream that contains the audio file.
  22919. For a file, just call
  22920. @code
  22921. setSource (new FileInputSource (file))
  22922. @endcode
  22923. You can pass a zero in here to clear the thumbnail.
  22924. The source that is passed in will be deleted by this object when it is no
  22925. longer needed
  22926. */
  22927. void setSource (InputSource* newSource);
  22928. /** Reloads the low res thumbnail data from an input stream.
  22929. The thumb will automatically attempt to reload itself from its
  22930. AudioThumbnailCache.
  22931. */
  22932. void loadFrom (InputStream& input);
  22933. /** Saves the low res thumbnail data to an output stream.
  22934. The thumb will automatically attempt to save itself to its
  22935. AudioThumbnailCache after it finishes scanning the wave file.
  22936. */
  22937. void saveTo (OutputStream& output) const;
  22938. /** Returns the number of channels in the file.
  22939. */
  22940. int getNumChannels() const throw();
  22941. /** Returns the length of the audio file, in seconds.
  22942. */
  22943. double getTotalLength() const throw();
  22944. /** Renders the waveform shape for a channel.
  22945. The waveform will be drawn within the specified rectangle, where startTime
  22946. and endTime specify the times within the audio file that should be positioned
  22947. at the left and right edges of the rectangle.
  22948. The waveform will be scaled vertically so that a full-volume sample will fill
  22949. the rectangle vertically, but you can also specify an extra vertical scale factor
  22950. with the verticalZoomFactor parameter.
  22951. */
  22952. void drawChannel (Graphics& g,
  22953. int x, int y, int w, int h,
  22954. double startTimeSeconds,
  22955. double endTimeSeconds,
  22956. int channelNum,
  22957. float verticalZoomFactor);
  22958. /** Returns true if the low res preview is fully generated.
  22959. */
  22960. bool isFullyLoaded() const throw();
  22961. /** @internal */
  22962. bool useTimeSlice();
  22963. /** @internal */
  22964. void timerCallback();
  22965. juce_UseDebuggingNewOperator
  22966. private:
  22967. AudioFormatManager& formatManagerToUse;
  22968. AudioThumbnailCache& cache;
  22969. ScopedPointer <InputSource> source;
  22970. CriticalSection readerLock;
  22971. ScopedPointer <AudioFormatReader> reader;
  22972. MemoryBlock data, cachedLevels;
  22973. int orginalSamplesPerThumbnailSample;
  22974. int numChannelsCached, numSamplesCached;
  22975. double cachedStart, cachedTimePerPixel;
  22976. bool cacheNeedsRefilling;
  22977. void clear();
  22978. AudioFormatReader* createReader() const;
  22979. void generateSection (AudioFormatReader& reader, int64 startSample, int numSamples);
  22980. char* getChannelData (int channel) const;
  22981. void refillCache (int numSamples, double startTime, double timePerPixel);
  22982. friend class AudioThumbnailCache;
  22983. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  22984. bool initialiseFromAudioFile (AudioFormatReader& reader);
  22985. // returns true if more needs to be read
  22986. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  22987. };
  22988. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  22989. /*** End of inlined file: juce_AudioThumbnail.h ***/
  22990. #endif
  22991. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  22992. /*** Start of inlined file: juce_AudioThumbnailCache.h ***/
  22993. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  22994. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  22995. struct ThumbnailCacheEntry;
  22996. /**
  22997. An instance of this class is used to manage multiple AudioThumbnail objects.
  22998. The cache runs a single background thread that is shared by all the thumbnails
  22999. that need it, and it maintains a set of low-res previews in memory, to avoid
  23000. having to re-scan audio files too often.
  23001. @see AudioThumbnail
  23002. */
  23003. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  23004. {
  23005. public:
  23006. /** Creates a cache object.
  23007. The maxNumThumbsToStore parameter lets you specify how many previews should
  23008. be kept in memory at once.
  23009. */
  23010. explicit AudioThumbnailCache (int maxNumThumbsToStore);
  23011. /** Destructor. */
  23012. ~AudioThumbnailCache();
  23013. /** Clears out any stored thumbnails.
  23014. */
  23015. void clear();
  23016. /** Reloads the specified thumb if this cache contains the appropriate stored
  23017. data.
  23018. This is called automatically by the AudioThumbnail class, so you shouldn't
  23019. normally need to call it directly.
  23020. */
  23021. bool loadThumb (AudioThumbnail& thumb, int64 hashCode);
  23022. /** Stores the cachable data from the specified thumb in this cache.
  23023. This is called automatically by the AudioThumbnail class, so you shouldn't
  23024. normally need to call it directly.
  23025. */
  23026. void storeThumb (const AudioThumbnail& thumb, int64 hashCode);
  23027. juce_UseDebuggingNewOperator
  23028. private:
  23029. OwnedArray <ThumbnailCacheEntry> thumbs;
  23030. int maxNumThumbsToStore;
  23031. friend class AudioThumbnail;
  23032. void addThumbnail (AudioThumbnail* thumb);
  23033. void removeThumbnail (AudioThumbnail* thumb);
  23034. };
  23035. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  23036. /*** End of inlined file: juce_AudioThumbnailCache.h ***/
  23037. #endif
  23038. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23039. /*** Start of inlined file: juce_FlacAudioFormat.h ***/
  23040. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23041. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23042. #if JUCE_USE_FLAC || defined (DOXYGEN)
  23043. /**
  23044. Reads and writes the lossless-compression FLAC audio format.
  23045. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  23046. and make sure your include search path and library search path are set up to find
  23047. the FLAC header files and static libraries.
  23048. @see AudioFormat
  23049. */
  23050. class JUCE_API FlacAudioFormat : public AudioFormat
  23051. {
  23052. public:
  23053. FlacAudioFormat();
  23054. ~FlacAudioFormat();
  23055. const Array <int> getPossibleSampleRates();
  23056. const Array <int> getPossibleBitDepths();
  23057. bool canDoStereo();
  23058. bool canDoMono();
  23059. bool isCompressed();
  23060. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23061. const bool deleteStreamIfOpeningFails);
  23062. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23063. double sampleRateToUse,
  23064. unsigned int numberOfChannels,
  23065. int bitsPerSample,
  23066. const StringPairArray& metadataValues,
  23067. int qualityOptionIndex);
  23068. juce_UseDebuggingNewOperator
  23069. };
  23070. #endif
  23071. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23072. /*** End of inlined file: juce_FlacAudioFormat.h ***/
  23073. #endif
  23074. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23075. /*** Start of inlined file: juce_OggVorbisAudioFormat.h ***/
  23076. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23077. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23078. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  23079. /**
  23080. Reads and writes the Ogg-Vorbis audio format.
  23081. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  23082. and make sure your include search path and library search path are set up to find
  23083. the Vorbis and Ogg header files and static libraries.
  23084. @see AudioFormat,
  23085. */
  23086. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  23087. {
  23088. public:
  23089. OggVorbisAudioFormat();
  23090. ~OggVorbisAudioFormat();
  23091. const Array <int> getPossibleSampleRates();
  23092. const Array <int> getPossibleBitDepths();
  23093. bool canDoStereo();
  23094. bool canDoMono();
  23095. bool isCompressed();
  23096. const StringArray getQualityOptions();
  23097. /** Tries to estimate the quality level of an ogg file based on its size.
  23098. If it can't read the file for some reason, this will just return 1 (medium quality),
  23099. otherwise it will return the approximate quality setting that would have been used
  23100. to create the file.
  23101. @see getQualityOptions
  23102. */
  23103. int estimateOggFileQuality (const File& source);
  23104. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23105. const bool deleteStreamIfOpeningFails);
  23106. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23107. double sampleRateToUse,
  23108. unsigned int numberOfChannels,
  23109. int bitsPerSample,
  23110. const StringPairArray& metadataValues,
  23111. int qualityOptionIndex);
  23112. juce_UseDebuggingNewOperator
  23113. };
  23114. #endif
  23115. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23116. /*** End of inlined file: juce_OggVorbisAudioFormat.h ***/
  23117. #endif
  23118. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23119. /*** Start of inlined file: juce_QuickTimeAudioFormat.h ***/
  23120. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23121. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23122. #if JUCE_QUICKTIME
  23123. /**
  23124. Uses QuickTime to read the audio track a movie or media file.
  23125. As well as QuickTime movies, this should also manage to open other audio
  23126. files that quicktime can understand, like mp3, m4a, etc.
  23127. @see AudioFormat
  23128. */
  23129. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  23130. {
  23131. public:
  23132. /** Creates a format object. */
  23133. QuickTimeAudioFormat();
  23134. /** Destructor. */
  23135. ~QuickTimeAudioFormat();
  23136. const Array <int> getPossibleSampleRates();
  23137. const Array <int> getPossibleBitDepths();
  23138. bool canDoStereo();
  23139. bool canDoMono();
  23140. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23141. const bool deleteStreamIfOpeningFails);
  23142. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23143. double sampleRateToUse,
  23144. unsigned int numberOfChannels,
  23145. int bitsPerSample,
  23146. const StringPairArray& metadataValues,
  23147. int qualityOptionIndex);
  23148. juce_UseDebuggingNewOperator
  23149. };
  23150. #endif
  23151. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23152. /*** End of inlined file: juce_QuickTimeAudioFormat.h ***/
  23153. #endif
  23154. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23155. /*** Start of inlined file: juce_WavAudioFormat.h ***/
  23156. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23157. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23158. /**
  23159. Reads and Writes WAV format audio files.
  23160. @see AudioFormat
  23161. */
  23162. class JUCE_API WavAudioFormat : public AudioFormat
  23163. {
  23164. public:
  23165. /** Creates a format object. */
  23166. WavAudioFormat();
  23167. /** Destructor. */
  23168. ~WavAudioFormat();
  23169. /** Metadata property name used by wav readers and writers for adding
  23170. a BWAV chunk to the file.
  23171. @see AudioFormatReader::metadataValues, createWriterFor
  23172. */
  23173. static const char* const bwavDescription;
  23174. /** Metadata property name used by wav readers and writers for adding
  23175. a BWAV chunk to the file.
  23176. @see AudioFormatReader::metadataValues, createWriterFor
  23177. */
  23178. static const char* const bwavOriginator;
  23179. /** Metadata property name used by wav readers and writers for adding
  23180. a BWAV chunk to the file.
  23181. @see AudioFormatReader::metadataValues, createWriterFor
  23182. */
  23183. static const char* const bwavOriginatorRef;
  23184. /** Metadata property name used by wav readers and writers for adding
  23185. a BWAV chunk to the file.
  23186. Date format is: yyyy-mm-dd
  23187. @see AudioFormatReader::metadataValues, createWriterFor
  23188. */
  23189. static const char* const bwavOriginationDate;
  23190. /** Metadata property name used by wav readers and writers for adding
  23191. a BWAV chunk to the file.
  23192. Time format is: hh-mm-ss
  23193. @see AudioFormatReader::metadataValues, createWriterFor
  23194. */
  23195. static const char* const bwavOriginationTime;
  23196. /** Metadata property name used by wav readers and writers for adding
  23197. a BWAV chunk to the file.
  23198. This is the number of samples from the start of an edit that the
  23199. file is supposed to begin at. Seems like an obvious mistake to
  23200. only allow a file to occur in an edit once, but that's the way
  23201. it is..
  23202. @see AudioFormatReader::metadataValues, createWriterFor
  23203. */
  23204. static const char* const bwavTimeReference;
  23205. /** Metadata property name used by wav readers and writers for adding
  23206. a BWAV chunk to the file.
  23207. This is a
  23208. @see AudioFormatReader::metadataValues, createWriterFor
  23209. */
  23210. static const char* const bwavCodingHistory;
  23211. /** Utility function to fill out the appropriate metadata for a BWAV file.
  23212. This just makes it easier than using the property names directly, and it
  23213. fills out the time and date in the right format.
  23214. */
  23215. static const StringPairArray createBWAVMetadata (const String& description,
  23216. const String& originator,
  23217. const String& originatorRef,
  23218. const Time& dateAndTime,
  23219. const int64 timeReferenceSamples,
  23220. const String& codingHistory);
  23221. const Array <int> getPossibleSampleRates();
  23222. const Array <int> getPossibleBitDepths();
  23223. bool canDoStereo();
  23224. bool canDoMono();
  23225. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23226. const bool deleteStreamIfOpeningFails);
  23227. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23228. double sampleRateToUse,
  23229. unsigned int numberOfChannels,
  23230. int bitsPerSample,
  23231. const StringPairArray& metadataValues,
  23232. int qualityOptionIndex);
  23233. /** Utility function to replace the metadata in a wav file with a new set of values.
  23234. If possible, this cheats by overwriting just the metadata region of the file, rather
  23235. than by copying the whole file again.
  23236. */
  23237. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  23238. juce_UseDebuggingNewOperator
  23239. };
  23240. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23241. /*** End of inlined file: juce_WavAudioFormat.h ***/
  23242. #endif
  23243. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23244. /*** Start of inlined file: juce_AudioFormatReaderSource.h ***/
  23245. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23246. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23247. /*** Start of inlined file: juce_PositionableAudioSource.h ***/
  23248. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23249. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23250. /**
  23251. A type of AudioSource which can be repositioned.
  23252. The basic AudioSource just streams continuously with no idea of a current
  23253. time or length, so the PositionableAudioSource is used for a finite stream
  23254. that has a current read position.
  23255. @see AudioSource, AudioTransportSource
  23256. */
  23257. class JUCE_API PositionableAudioSource : public AudioSource
  23258. {
  23259. protected:
  23260. /** Creates the PositionableAudioSource. */
  23261. PositionableAudioSource() throw() {}
  23262. public:
  23263. /** Destructor */
  23264. ~PositionableAudioSource() {}
  23265. /** Tells the stream to move to a new position.
  23266. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  23267. should return samples from this position.
  23268. Note that this may be called on a different thread to getNextAudioBlock(),
  23269. so the subclass should make sure it's synchronised.
  23270. */
  23271. virtual void setNextReadPosition (int newPosition) = 0;
  23272. /** Returns the position from which the next block will be returned.
  23273. @see setNextReadPosition
  23274. */
  23275. virtual int getNextReadPosition() const = 0;
  23276. /** Returns the total length of the stream (in samples). */
  23277. virtual int getTotalLength() const = 0;
  23278. /** Returns true if this source is actually playing in a loop. */
  23279. virtual bool isLooping() const = 0;
  23280. };
  23281. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23282. /*** End of inlined file: juce_PositionableAudioSource.h ***/
  23283. /**
  23284. A type of AudioSource that will read from an AudioFormatReader.
  23285. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  23286. */
  23287. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  23288. {
  23289. public:
  23290. /** Creates an AudioFormatReaderSource for a given reader.
  23291. @param sourceReader the reader to use as the data source
  23292. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  23293. when this object is deleted; if false it will be
  23294. left up to the caller to manage its lifetime
  23295. */
  23296. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  23297. const bool deleteReaderWhenThisIsDeleted);
  23298. /** Destructor. */
  23299. ~AudioFormatReaderSource();
  23300. /** Toggles loop-mode.
  23301. If set to true, it will continuously loop the input source. If false,
  23302. it will just emit silence after the source has finished.
  23303. @see isLooping
  23304. */
  23305. void setLooping (const bool shouldLoop) throw();
  23306. /** Returns whether loop-mode is turned on or not. */
  23307. bool isLooping() const { return looping; }
  23308. /** Returns the reader that's being used. */
  23309. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  23310. /** Implementation of the AudioSource method. */
  23311. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23312. /** Implementation of the AudioSource method. */
  23313. void releaseResources();
  23314. /** Implementation of the AudioSource method. */
  23315. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23316. /** Implements the PositionableAudioSource method. */
  23317. void setNextReadPosition (int newPosition);
  23318. /** Implements the PositionableAudioSource method. */
  23319. int getNextReadPosition() const;
  23320. /** Implements the PositionableAudioSource method. */
  23321. int getTotalLength() const;
  23322. juce_UseDebuggingNewOperator
  23323. private:
  23324. AudioFormatReader* reader;
  23325. bool deleteReader;
  23326. int volatile nextPlayPos;
  23327. bool volatile looping;
  23328. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  23329. AudioFormatReaderSource (const AudioFormatReaderSource&);
  23330. AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  23331. };
  23332. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23333. /*** End of inlined file: juce_AudioFormatReaderSource.h ***/
  23334. #endif
  23335. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23336. #endif
  23337. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23338. /*** Start of inlined file: juce_AudioSourcePlayer.h ***/
  23339. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23340. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23341. /*** Start of inlined file: juce_AudioIODevice.h ***/
  23342. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23343. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23344. class AudioIODevice;
  23345. /**
  23346. One of these is passed to an AudioIODevice object to stream the audio data
  23347. in and out.
  23348. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  23349. method on its own high-priority audio thread, when it needs to send or receive
  23350. the next block of data.
  23351. @see AudioIODevice, AudioDeviceManager
  23352. */
  23353. class JUCE_API AudioIODeviceCallback
  23354. {
  23355. public:
  23356. /** Destructor. */
  23357. virtual ~AudioIODeviceCallback() {}
  23358. /** Processes a block of incoming and outgoing audio data.
  23359. The subclass's implementation should use the incoming audio for whatever
  23360. purposes it needs to, and must fill all the output channels with the next
  23361. block of output data before returning.
  23362. The channel data is arranged with the same array indices as the channel name
  23363. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  23364. that aren't specified in AudioIODevice::open() will have a null pointer for their
  23365. associated channel, so remember to check for this.
  23366. @param inputChannelData a set of arrays containing the audio data for each
  23367. incoming channel - this data is valid until the function
  23368. returns. There will be one channel of data for each input
  23369. channel that was enabled when the audio device was opened
  23370. (see AudioIODevice::open())
  23371. @param numInputChannels the number of pointers to channel data in the
  23372. inputChannelData array.
  23373. @param outputChannelData a set of arrays which need to be filled with the data
  23374. that should be sent to each outgoing channel of the device.
  23375. There will be one channel of data for each output channel
  23376. that was enabled when the audio device was opened (see
  23377. AudioIODevice::open())
  23378. The initial contents of the array is undefined, so the
  23379. callback function must fill all the channels with zeros if
  23380. its output is silence. Failing to do this could cause quite
  23381. an unpleasant noise!
  23382. @param numOutputChannels the number of pointers to channel data in the
  23383. outputChannelData array.
  23384. @param numSamples the number of samples in each channel of the input and
  23385. output arrays. The number of samples will depend on the
  23386. audio device's buffer size and will usually remain constant,
  23387. although this isn't guaranteed, so make sure your code can
  23388. cope with reasonable changes in the buffer size from one
  23389. callback to the next.
  23390. */
  23391. virtual void audioDeviceIOCallback (const float** inputChannelData,
  23392. int numInputChannels,
  23393. float** outputChannelData,
  23394. int numOutputChannels,
  23395. int numSamples) = 0;
  23396. /** Called to indicate that the device is about to start calling back.
  23397. This will be called just before the audio callbacks begin, either when this
  23398. callback has just been added to an audio device, or after the device has been
  23399. restarted because of a sample-rate or block-size change.
  23400. You can use this opportunity to find out the sample rate and block size
  23401. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  23402. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  23403. @param device the audio IO device that will be used to drive the callback.
  23404. Note that if you're going to store this this pointer, it is
  23405. only valid until the next time that audioDeviceStopped is called.
  23406. */
  23407. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  23408. /** Called to indicate that the device has stopped.
  23409. */
  23410. virtual void audioDeviceStopped() = 0;
  23411. };
  23412. /**
  23413. Base class for an audio device with synchronised input and output channels.
  23414. Subclasses of this are used to implement different protocols such as DirectSound,
  23415. ASIO, CoreAudio, etc.
  23416. To create one of these, you'll need to use the AudioIODeviceType class - see the
  23417. documentation for that class for more info.
  23418. For an easier way of managing audio devices and their settings, have a look at the
  23419. AudioDeviceManager class.
  23420. @see AudioIODeviceType, AudioDeviceManager
  23421. */
  23422. class JUCE_API AudioIODevice
  23423. {
  23424. public:
  23425. /** Destructor. */
  23426. virtual ~AudioIODevice();
  23427. /** Returns the device's name, (as set in the constructor). */
  23428. const String& getName() const throw() { return name; }
  23429. /** Returns the type of the device.
  23430. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  23431. */
  23432. const String& getTypeName() const throw() { return typeName; }
  23433. /** Returns the names of all the available output channels on this device.
  23434. To find out which of these are currently in use, call getActiveOutputChannels().
  23435. */
  23436. virtual const StringArray getOutputChannelNames() = 0;
  23437. /** Returns the names of all the available input channels on this device.
  23438. To find out which of these are currently in use, call getActiveInputChannels().
  23439. */
  23440. virtual const StringArray getInputChannelNames() = 0;
  23441. /** Returns the number of sample-rates this device supports.
  23442. To find out which rates are available on this device, use this method to
  23443. find out how many there are, and getSampleRate() to get the rates.
  23444. @see getSampleRate
  23445. */
  23446. virtual int getNumSampleRates() = 0;
  23447. /** Returns one of the sample-rates this device supports.
  23448. To find out which rates are available on this device, use getNumSampleRates() to
  23449. find out how many there are, and getSampleRate() to get the individual rates.
  23450. The sample rate is set by the open() method.
  23451. (Note that for DirectSound some rates might not work, depending on combinations
  23452. of i/o channels that are being opened).
  23453. @see getNumSampleRates
  23454. */
  23455. virtual double getSampleRate (int index) = 0;
  23456. /** Returns the number of sizes of buffer that are available.
  23457. @see getBufferSizeSamples, getDefaultBufferSize
  23458. */
  23459. virtual int getNumBufferSizesAvailable() = 0;
  23460. /** Returns one of the possible buffer-sizes.
  23461. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  23462. @returns a number of samples
  23463. @see getNumBufferSizesAvailable, getDefaultBufferSize
  23464. */
  23465. virtual int getBufferSizeSamples (int index) = 0;
  23466. /** Returns the default buffer-size to use.
  23467. @returns a number of samples
  23468. @see getNumBufferSizesAvailable, getBufferSizeSamples
  23469. */
  23470. virtual int getDefaultBufferSize() = 0;
  23471. /** Tries to open the device ready to play.
  23472. @param inputChannels a BigInteger in which a set bit indicates that the corresponding
  23473. input channel should be enabled
  23474. @param outputChannels a BigInteger in which a set bit indicates that the corresponding
  23475. output channel should be enabled
  23476. @param sampleRate the sample rate to try to use - to find out which rates are
  23477. available, see getNumSampleRates() and getSampleRate()
  23478. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  23479. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  23480. @returns an error description if there's a problem, or an empty string if it succeeds in
  23481. opening the device
  23482. @see close
  23483. */
  23484. virtual const String open (const BigInteger& inputChannels,
  23485. const BigInteger& outputChannels,
  23486. double sampleRate,
  23487. int bufferSizeSamples) = 0;
  23488. /** Closes and releases the device if it's open. */
  23489. virtual void close() = 0;
  23490. /** Returns true if the device is still open.
  23491. A device might spontaneously close itself if something goes wrong, so this checks if
  23492. it's still open.
  23493. */
  23494. virtual bool isOpen() = 0;
  23495. /** Starts the device actually playing.
  23496. This must be called after the device has been opened.
  23497. @param callback the callback to use for streaming the data.
  23498. @see AudioIODeviceCallback, open
  23499. */
  23500. virtual void start (AudioIODeviceCallback* callback) = 0;
  23501. /** Stops the device playing.
  23502. Once a device has been started, this will stop it. Any pending calls to the
  23503. callback class will be flushed before this method returns.
  23504. */
  23505. virtual void stop() = 0;
  23506. /** Returns true if the device is still calling back.
  23507. The device might mysteriously stop, so this checks whether it's
  23508. still playing.
  23509. */
  23510. virtual bool isPlaying() = 0;
  23511. /** Returns the last error that happened if anything went wrong. */
  23512. virtual const String getLastError() = 0;
  23513. /** Returns the buffer size that the device is currently using.
  23514. If the device isn't actually open, this value doesn't really mean much.
  23515. */
  23516. virtual int getCurrentBufferSizeSamples() = 0;
  23517. /** Returns the sample rate that the device is currently using.
  23518. If the device isn't actually open, this value doesn't really mean much.
  23519. */
  23520. virtual double getCurrentSampleRate() = 0;
  23521. /** Returns the device's current physical bit-depth.
  23522. If the device isn't actually open, this value doesn't really mean much.
  23523. */
  23524. virtual int getCurrentBitDepth() = 0;
  23525. /** Returns a mask showing which of the available output channels are currently
  23526. enabled.
  23527. @see getOutputChannelNames
  23528. */
  23529. virtual const BigInteger getActiveOutputChannels() const = 0;
  23530. /** Returns a mask showing which of the available input channels are currently
  23531. enabled.
  23532. @see getInputChannelNames
  23533. */
  23534. virtual const BigInteger getActiveInputChannels() const = 0;
  23535. /** Returns the device's output latency.
  23536. This is the delay in samples between a callback getting a block of data, and
  23537. that data actually getting played.
  23538. */
  23539. virtual int getOutputLatencyInSamples() = 0;
  23540. /** Returns the device's input latency.
  23541. This is the delay in samples between some audio actually arriving at the soundcard,
  23542. and the callback getting passed this block of data.
  23543. */
  23544. virtual int getInputLatencyInSamples() = 0;
  23545. /** True if this device can show a pop-up control panel for editing its settings.
  23546. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  23547. to display it.
  23548. */
  23549. virtual bool hasControlPanel() const;
  23550. /** Shows a device-specific control panel if there is one.
  23551. This should only be called for devices which return true from hasControlPanel().
  23552. */
  23553. virtual bool showControlPanel();
  23554. protected:
  23555. /** Creates a device, setting its name and type member variables. */
  23556. AudioIODevice (const String& deviceName,
  23557. const String& typeName);
  23558. /** @internal */
  23559. String name, typeName;
  23560. };
  23561. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23562. /*** End of inlined file: juce_AudioIODevice.h ***/
  23563. /**
  23564. Wrapper class to continuously stream audio from an audio source to an
  23565. AudioIODevice.
  23566. This object acts as an AudioIODeviceCallback, so can be attached to an
  23567. output device, and will stream audio from an AudioSource.
  23568. */
  23569. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  23570. {
  23571. public:
  23572. /** Creates an empty AudioSourcePlayer. */
  23573. AudioSourcePlayer();
  23574. /** Destructor.
  23575. Make sure this object isn't still being used by an AudioIODevice before
  23576. deleting it!
  23577. */
  23578. virtual ~AudioSourcePlayer();
  23579. /** Changes the current audio source to play from.
  23580. If the source passed in is already being used, this method will do nothing.
  23581. If the source is not null, its prepareToPlay() method will be called
  23582. before it starts being used for playback.
  23583. If there's another source currently playing, its releaseResources() method
  23584. will be called after it has been swapped for the new one.
  23585. @param newSource the new source to use - this will NOT be deleted
  23586. by this object when no longer needed, so it's the
  23587. caller's responsibility to manage it.
  23588. */
  23589. void setSource (AudioSource* newSource);
  23590. /** Returns the source that's playing.
  23591. May return 0 if there's no source.
  23592. */
  23593. AudioSource* getCurrentSource() const throw() { return source; }
  23594. /** Sets a gain to apply to the audio data.
  23595. @see getGain
  23596. */
  23597. void setGain (const float newGain) throw();
  23598. /** Returns the current gain.
  23599. @see setGain
  23600. */
  23601. float getGain() const throw() { return gain; }
  23602. /** Implementation of the AudioIODeviceCallback method. */
  23603. void audioDeviceIOCallback (const float** inputChannelData,
  23604. int totalNumInputChannels,
  23605. float** outputChannelData,
  23606. int totalNumOutputChannels,
  23607. int numSamples);
  23608. /** Implementation of the AudioIODeviceCallback method. */
  23609. void audioDeviceAboutToStart (AudioIODevice* device);
  23610. /** Implementation of the AudioIODeviceCallback method. */
  23611. void audioDeviceStopped();
  23612. juce_UseDebuggingNewOperator
  23613. private:
  23614. CriticalSection readLock;
  23615. AudioSource* source;
  23616. double sampleRate;
  23617. int bufferSize;
  23618. float* channels [128];
  23619. float* outputChans [128];
  23620. const float* inputChans [128];
  23621. AudioSampleBuffer tempBuffer;
  23622. float lastGain, gain;
  23623. AudioSourcePlayer (const AudioSourcePlayer&);
  23624. AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  23625. };
  23626. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23627. /*** End of inlined file: juce_AudioSourcePlayer.h ***/
  23628. #endif
  23629. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23630. /*** Start of inlined file: juce_AudioTransportSource.h ***/
  23631. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23632. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23633. /*** Start of inlined file: juce_BufferingAudioSource.h ***/
  23634. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23635. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23636. /**
  23637. An AudioSource which takes another source as input, and buffers it using a thread.
  23638. Create this as a wrapper around another thread, and it will read-ahead with
  23639. a background thread to smooth out playback. You can either create one of these
  23640. directly, or use it indirectly using an AudioTransportSource.
  23641. @see PositionableAudioSource, AudioTransportSource
  23642. */
  23643. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  23644. {
  23645. public:
  23646. /** Creates a BufferingAudioSource.
  23647. @param source the input source to read from
  23648. @param deleteSourceWhenDeleted if true, then the input source object will
  23649. be deleted when this object is deleted
  23650. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  23651. */
  23652. BufferingAudioSource (PositionableAudioSource* source,
  23653. const bool deleteSourceWhenDeleted,
  23654. int numberOfSamplesToBuffer);
  23655. /** Destructor.
  23656. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  23657. flag was set in the constructor.
  23658. */
  23659. ~BufferingAudioSource();
  23660. /** Implementation of the AudioSource method. */
  23661. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23662. /** Implementation of the AudioSource method. */
  23663. void releaseResources();
  23664. /** Implementation of the AudioSource method. */
  23665. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23666. /** Implements the PositionableAudioSource method. */
  23667. void setNextReadPosition (int newPosition);
  23668. /** Implements the PositionableAudioSource method. */
  23669. int getNextReadPosition() const;
  23670. /** Implements the PositionableAudioSource method. */
  23671. int getTotalLength() const { return source->getTotalLength(); }
  23672. /** Implements the PositionableAudioSource method. */
  23673. bool isLooping() const { return source->isLooping(); }
  23674. juce_UseDebuggingNewOperator
  23675. private:
  23676. PositionableAudioSource* source;
  23677. bool deleteSourceWhenDeleted;
  23678. int numberOfSamplesToBuffer;
  23679. AudioSampleBuffer buffer;
  23680. CriticalSection bufferStartPosLock;
  23681. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  23682. bool wasSourceLooping;
  23683. double volatile sampleRate;
  23684. friend class SharedBufferingAudioSourceThread;
  23685. bool readNextBufferChunk();
  23686. void readBufferSection (int start, int length, int bufferOffset);
  23687. BufferingAudioSource (const BufferingAudioSource&);
  23688. BufferingAudioSource& operator= (const BufferingAudioSource&);
  23689. };
  23690. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23691. /*** End of inlined file: juce_BufferingAudioSource.h ***/
  23692. /*** Start of inlined file: juce_ResamplingAudioSource.h ***/
  23693. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23694. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23695. /**
  23696. A type of AudioSource that takes an input source and changes its sample rate.
  23697. @see AudioSource
  23698. */
  23699. class JUCE_API ResamplingAudioSource : public AudioSource
  23700. {
  23701. public:
  23702. /** Creates a ResamplingAudioSource for a given input source.
  23703. @param inputSource the input source to read from
  23704. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23705. this object is deleted
  23706. */
  23707. ResamplingAudioSource (AudioSource* const inputSource,
  23708. const bool deleteInputWhenDeleted);
  23709. /** Destructor. */
  23710. ~ResamplingAudioSource();
  23711. /** Changes the resampling ratio.
  23712. (This value can be changed at any time, even while the source is running).
  23713. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  23714. values will speed it up; lower values will slow it
  23715. down. The ratio must be greater than 0
  23716. */
  23717. void setResamplingRatio (const double samplesInPerOutputSample);
  23718. /** Returns the current resampling ratio.
  23719. This is the value that was set by setResamplingRatio().
  23720. */
  23721. double getResamplingRatio() const throw() { return ratio; }
  23722. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23723. void releaseResources();
  23724. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23725. juce_UseDebuggingNewOperator
  23726. private:
  23727. AudioSource* const input;
  23728. const bool deleteInputWhenDeleted;
  23729. double ratio, lastRatio;
  23730. AudioSampleBuffer buffer;
  23731. int bufferPos, sampsInBuffer;
  23732. double subSampleOffset;
  23733. double coefficients[6];
  23734. CriticalSection ratioLock;
  23735. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  23736. void createLowPass (const double proportionalRate);
  23737. struct FilterState
  23738. {
  23739. double x1, x2, y1, y2;
  23740. };
  23741. FilterState filterStates[2];
  23742. void resetFilters();
  23743. void applyFilter (float* samples, int num, FilterState& fs);
  23744. ResamplingAudioSource (const ResamplingAudioSource&);
  23745. ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  23746. };
  23747. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23748. /*** End of inlined file: juce_ResamplingAudioSource.h ***/
  23749. /**
  23750. An AudioSource that takes a PositionableAudioSource and allows it to be
  23751. played, stopped, started, etc.
  23752. This can also be told use a buffer and background thread to read ahead, and
  23753. if can correct for different sample-rates.
  23754. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  23755. to control playback of an audio file.
  23756. @see AudioSource, AudioSourcePlayer
  23757. */
  23758. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  23759. public ChangeBroadcaster
  23760. {
  23761. public:
  23762. /** Creates an AudioTransportSource.
  23763. After creating one of these, use the setSource() method to select an input source.
  23764. */
  23765. AudioTransportSource();
  23766. /** Destructor. */
  23767. ~AudioTransportSource();
  23768. /** Sets the reader that is being used as the input source.
  23769. This will stop playback, reset the position to 0 and change to the new reader.
  23770. The source passed in will not be deleted by this object, so must be managed by
  23771. the caller.
  23772. @param newSource the new input source to use. This may be zero
  23773. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  23774. is zero, no reading ahead will be done; if it's
  23775. greater than zero, a BufferingAudioSource will be used
  23776. to do the reading-ahead
  23777. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  23778. rate of the source, and playback will be sample-rate
  23779. adjusted to maintain playback at the correct pitch. If
  23780. this is 0, no sample-rate adjustment will be performed
  23781. */
  23782. void setSource (PositionableAudioSource* const newSource,
  23783. int readAheadBufferSize = 0,
  23784. double sourceSampleRateToCorrectFor = 0.0);
  23785. /** Changes the current playback position in the source stream.
  23786. The next time the getNextAudioBlock() method is called, this
  23787. is the time from which it'll read data.
  23788. @see getPosition
  23789. */
  23790. void setPosition (double newPosition);
  23791. /** Returns the position that the next data block will be read from
  23792. This is a time in seconds.
  23793. */
  23794. double getCurrentPosition() const;
  23795. /** Returns true if the player has stopped because its input stream ran out of data.
  23796. */
  23797. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  23798. /** Starts playing (if a source has been selected).
  23799. If it starts playing, this will send a message to any ChangeListeners
  23800. that are registered with this object.
  23801. */
  23802. void start();
  23803. /** Stops playing.
  23804. If it's actually playing, this will send a message to any ChangeListeners
  23805. that are registered with this object.
  23806. */
  23807. void stop();
  23808. /** Returns true if it's currently playing. */
  23809. bool isPlaying() const throw() { return playing; }
  23810. /** Changes the gain to apply to the output.
  23811. @param newGain a factor by which to multiply the outgoing samples,
  23812. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  23813. */
  23814. void setGain (const float newGain) throw();
  23815. /** Returns the current gain setting.
  23816. @see setGain
  23817. */
  23818. float getGain() const throw() { return gain; }
  23819. /** Implementation of the AudioSource method. */
  23820. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23821. /** Implementation of the AudioSource method. */
  23822. void releaseResources();
  23823. /** Implementation of the AudioSource method. */
  23824. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23825. /** Implements the PositionableAudioSource method. */
  23826. void setNextReadPosition (int newPosition);
  23827. /** Implements the PositionableAudioSource method. */
  23828. int getNextReadPosition() const;
  23829. /** Implements the PositionableAudioSource method. */
  23830. int getTotalLength() const;
  23831. /** Implements the PositionableAudioSource method. */
  23832. bool isLooping() const;
  23833. juce_UseDebuggingNewOperator
  23834. private:
  23835. PositionableAudioSource* source;
  23836. ResamplingAudioSource* resamplerSource;
  23837. BufferingAudioSource* bufferingSource;
  23838. PositionableAudioSource* positionableSource;
  23839. AudioSource* masterSource;
  23840. CriticalSection callbackLock;
  23841. float volatile gain, lastGain;
  23842. bool volatile playing, stopped;
  23843. double sampleRate, sourceSampleRate;
  23844. int blockSize, readAheadBufferSize;
  23845. bool isPrepared, inputStreamEOF;
  23846. AudioTransportSource (const AudioTransportSource&);
  23847. AudioTransportSource& operator= (const AudioTransportSource&);
  23848. };
  23849. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23850. /*** End of inlined file: juce_AudioTransportSource.h ***/
  23851. #endif
  23852. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23853. #endif
  23854. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23855. /*** Start of inlined file: juce_ChannelRemappingAudioSource.h ***/
  23856. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23857. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23858. /**
  23859. An AudioSource that takes the audio from another source, and re-maps its
  23860. input and output channels to a different arrangement.
  23861. You can use this to increase or decrease the number of channels that an
  23862. audio source uses, or to re-order those channels.
  23863. Call the reset() method before using it to set up a default mapping, and then
  23864. the setInputChannelMapping() and setOutputChannelMapping() methods to
  23865. create an appropriate mapping, otherwise no channels will be connected and
  23866. it'll produce silence.
  23867. @see AudioSource
  23868. */
  23869. class ChannelRemappingAudioSource : public AudioSource
  23870. {
  23871. public:
  23872. /** Creates a remapping source that will pass on audio from the given input.
  23873. @param source the input source to use. Make sure that this doesn't
  23874. get deleted before the ChannelRemappingAudioSource object
  23875. @param deleteSourceWhenDeleted if true, the input source will be deleted
  23876. when this object is deleted, if false, the caller is
  23877. responsible for its deletion
  23878. */
  23879. ChannelRemappingAudioSource (AudioSource* const source,
  23880. const bool deleteSourceWhenDeleted);
  23881. /** Destructor. */
  23882. ~ChannelRemappingAudioSource();
  23883. /** Specifies a number of channels that this audio source must produce from its
  23884. getNextAudioBlock() callback.
  23885. */
  23886. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  23887. /** Clears any mapped channels.
  23888. After this, no channels are mapped, so this object will produce silence. Create
  23889. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  23890. */
  23891. void clearAllMappings() throw();
  23892. /** Creates an input channel mapping.
  23893. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  23894. data will be sent to destChannelIndex of our input source.
  23895. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  23896. source specified when this object was created).
  23897. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  23898. during our getNextAudioBlock() callback
  23899. */
  23900. void setInputChannelMapping (const int destChannelIndex,
  23901. const int sourceChannelIndex) throw();
  23902. /** Creates an output channel mapping.
  23903. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  23904. our input audio source will be copied to channel destChannelIndex of the final buffer.
  23905. @param sourceChannelIndex the index of an output channel coming from our input audio source
  23906. (i.e. the source specified when this object was created).
  23907. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  23908. during our getNextAudioBlock() callback
  23909. */
  23910. void setOutputChannelMapping (const int sourceChannelIndex,
  23911. const int destChannelIndex) throw();
  23912. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  23913. our input audio source.
  23914. */
  23915. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  23916. /** Returns the output channel to which channel outputChannelIndex of our input audio
  23917. source will be sent to.
  23918. */
  23919. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  23920. /** Returns an XML object to encapsulate the state of the mappings.
  23921. @see restoreFromXml
  23922. */
  23923. XmlElement* createXml() const throw();
  23924. /** Restores the mappings from an XML object created by createXML().
  23925. @see createXml
  23926. */
  23927. void restoreFromXml (const XmlElement& e) throw();
  23928. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23929. void releaseResources();
  23930. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23931. juce_UseDebuggingNewOperator
  23932. private:
  23933. int requiredNumberOfChannels;
  23934. Array <int> remappedInputs, remappedOutputs;
  23935. AudioSource* const source;
  23936. const bool deleteSourceWhenDeleted;
  23937. AudioSampleBuffer buffer;
  23938. AudioSourceChannelInfo remappedInfo;
  23939. CriticalSection lock;
  23940. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  23941. ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  23942. };
  23943. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23944. /*** End of inlined file: juce_ChannelRemappingAudioSource.h ***/
  23945. #endif
  23946. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23947. /*** Start of inlined file: juce_IIRFilterAudioSource.h ***/
  23948. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23949. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23950. /*** Start of inlined file: juce_IIRFilter.h ***/
  23951. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  23952. #define __JUCE_IIRFILTER_JUCEHEADER__
  23953. /**
  23954. An IIR filter that can perform low, high, or band-pass filtering on an
  23955. audio signal.
  23956. @see IIRFilterAudioSource
  23957. */
  23958. class JUCE_API IIRFilter
  23959. {
  23960. public:
  23961. /** Creates a filter.
  23962. Initially the filter is inactive, so will have no effect on samples that
  23963. you process with it. Use the appropriate method to turn it into the type
  23964. of filter needed.
  23965. */
  23966. IIRFilter();
  23967. /** Creates a copy of another filter. */
  23968. IIRFilter (const IIRFilter& other);
  23969. /** Destructor. */
  23970. ~IIRFilter();
  23971. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  23972. Note that this clears the processing state, but the type of filter and
  23973. its coefficients aren't changed. To put a filter into an inactive state, use
  23974. the makeInactive() method.
  23975. */
  23976. void reset() throw();
  23977. /** Performs the filter operation on the given set of samples.
  23978. */
  23979. void processSamples (float* samples,
  23980. int numSamples) throw();
  23981. /** Processes a single sample, without any locking or checking.
  23982. Use this if you need fast processing of a single value, but be aware that
  23983. this isn't thread-safe in the way that processSamples() is.
  23984. */
  23985. float processSingleSampleRaw (float sample) throw();
  23986. /** Sets the filter up to act as a low-pass filter.
  23987. */
  23988. void makeLowPass (double sampleRate,
  23989. double frequency) throw();
  23990. /** Sets the filter up to act as a high-pass filter.
  23991. */
  23992. void makeHighPass (double sampleRate,
  23993. double frequency) throw();
  23994. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  23995. The gain is a scale factor that the low frequencies are multiplied by, so values
  23996. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  23997. attenuate them.
  23998. */
  23999. void makeLowShelf (double sampleRate,
  24000. double cutOffFrequency,
  24001. double Q,
  24002. float gainFactor) throw();
  24003. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  24004. The gain is a scale factor that the high frequencies are multiplied by, so values
  24005. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  24006. attenuate them.
  24007. */
  24008. void makeHighShelf (double sampleRate,
  24009. double cutOffFrequency,
  24010. double Q,
  24011. float gainFactor) throw();
  24012. /** Sets the filter up to act as a band pass filter centred around a
  24013. frequency, with a variable Q and gain.
  24014. The gain is a scale factor that the centre frequencies are multiplied by, so
  24015. values greater than 1.0 will boost the centre frequencies, values less than
  24016. 1.0 will attenuate them.
  24017. */
  24018. void makeBandPass (double sampleRate,
  24019. double centreFrequency,
  24020. double Q,
  24021. float gainFactor) throw();
  24022. /** Clears the filter's coefficients so that it becomes inactive.
  24023. */
  24024. void makeInactive() throw();
  24025. /** Makes this filter duplicate the set-up of another one.
  24026. */
  24027. void copyCoefficientsFrom (const IIRFilter& other) throw();
  24028. juce_UseDebuggingNewOperator
  24029. protected:
  24030. CriticalSection processLock;
  24031. void setCoefficients (double c1, double c2, double c3,
  24032. double c4, double c5, double c6) throw();
  24033. bool active;
  24034. float coefficients[6];
  24035. float x1, x2, y1, y2;
  24036. // (use the copyCoefficientsFrom() method instead of this operator)
  24037. IIRFilter& operator= (const IIRFilter&);
  24038. };
  24039. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  24040. /*** End of inlined file: juce_IIRFilter.h ***/
  24041. /**
  24042. An AudioSource that performs an IIR filter on another source.
  24043. */
  24044. class JUCE_API IIRFilterAudioSource : public AudioSource
  24045. {
  24046. public:
  24047. /** Creates a IIRFilterAudioSource for a given input source.
  24048. @param inputSource the input source to read from
  24049. @param deleteInputWhenDeleted if true, the input source will be deleted when
  24050. this object is deleted
  24051. */
  24052. IIRFilterAudioSource (AudioSource* const inputSource,
  24053. const bool deleteInputWhenDeleted);
  24054. /** Destructor. */
  24055. ~IIRFilterAudioSource();
  24056. /** Changes the filter to use the same parameters as the one being passed in.
  24057. */
  24058. void setFilterParameters (const IIRFilter& newSettings);
  24059. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24060. void releaseResources();
  24061. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24062. juce_UseDebuggingNewOperator
  24063. private:
  24064. AudioSource* const input;
  24065. const bool deleteInputWhenDeleted;
  24066. OwnedArray <IIRFilter> iirFilters;
  24067. IIRFilterAudioSource (const IIRFilterAudioSource&);
  24068. IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  24069. };
  24070. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24071. /*** End of inlined file: juce_IIRFilterAudioSource.h ***/
  24072. #endif
  24073. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24074. /*** Start of inlined file: juce_MixerAudioSource.h ***/
  24075. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24076. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24077. /**
  24078. An AudioSource that mixes together the output of a set of other AudioSources.
  24079. Input sources can be added and removed while the mixer is running as long as their
  24080. prepareToPlay() and releaseResources() methods are called before and after adding
  24081. them to the mixer.
  24082. */
  24083. class JUCE_API MixerAudioSource : public AudioSource
  24084. {
  24085. public:
  24086. /** Creates a MixerAudioSource.
  24087. */
  24088. MixerAudioSource();
  24089. /** Destructor. */
  24090. ~MixerAudioSource();
  24091. /** Adds an input source to the mixer.
  24092. If the mixer is running you'll need to make sure that the input source
  24093. is ready to play by calling its prepareToPlay() method before adding it.
  24094. If the mixer is stopped, then its input sources will be automatically
  24095. prepared when the mixer's prepareToPlay() method is called.
  24096. @param newInput the source to add to the mixer
  24097. @param deleteWhenRemoved if true, then this source will be deleted when
  24098. the mixer is deleted or when removeAllInputs() is
  24099. called (unless the source is previously removed
  24100. with the removeInputSource method)
  24101. */
  24102. void addInputSource (AudioSource* newInput,
  24103. const bool deleteWhenRemoved);
  24104. /** Removes an input source.
  24105. If the mixer is running, this will remove the source but not call its
  24106. releaseResources() method, so the caller might want to do this manually.
  24107. @param input the source to remove
  24108. @param deleteSource whether to delete this source after it's been removed
  24109. */
  24110. void removeInputSource (AudioSource* input,
  24111. const bool deleteSource);
  24112. /** Removes all the input sources.
  24113. If the mixer is running, this will remove the sources but not call their
  24114. releaseResources() method, so the caller might want to do this manually.
  24115. Any sources which were added with the deleteWhenRemoved flag set will be
  24116. deleted by this method.
  24117. */
  24118. void removeAllInputs();
  24119. /** Implementation of the AudioSource method.
  24120. This will call prepareToPlay() on all its input sources.
  24121. */
  24122. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24123. /** Implementation of the AudioSource method.
  24124. This will call releaseResources() on all its input sources.
  24125. */
  24126. void releaseResources();
  24127. /** Implementation of the AudioSource method. */
  24128. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24129. juce_UseDebuggingNewOperator
  24130. private:
  24131. Array <AudioSource*> inputs;
  24132. BigInteger inputsToDelete;
  24133. CriticalSection lock;
  24134. AudioSampleBuffer tempBuffer;
  24135. double currentSampleRate;
  24136. int bufferSizeExpected;
  24137. MixerAudioSource (const MixerAudioSource&);
  24138. MixerAudioSource& operator= (const MixerAudioSource&);
  24139. };
  24140. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24141. /*** End of inlined file: juce_MixerAudioSource.h ***/
  24142. #endif
  24143. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  24144. #endif
  24145. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24146. #endif
  24147. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24148. /*** Start of inlined file: juce_ToneGeneratorAudioSource.h ***/
  24149. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24150. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24151. /**
  24152. A simple AudioSource that generates a sine wave.
  24153. */
  24154. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  24155. {
  24156. public:
  24157. /** Creates a ToneGeneratorAudioSource. */
  24158. ToneGeneratorAudioSource();
  24159. /** Destructor. */
  24160. ~ToneGeneratorAudioSource();
  24161. /** Sets the signal's amplitude. */
  24162. void setAmplitude (const float newAmplitude);
  24163. /** Sets the signal's frequency. */
  24164. void setFrequency (const double newFrequencyHz);
  24165. /** Implementation of the AudioSource method. */
  24166. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24167. /** Implementation of the AudioSource method. */
  24168. void releaseResources();
  24169. /** Implementation of the AudioSource method. */
  24170. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24171. juce_UseDebuggingNewOperator
  24172. private:
  24173. double frequency, sampleRate;
  24174. double currentPhase, phasePerSample;
  24175. float amplitude;
  24176. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  24177. ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  24178. };
  24179. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24180. /*** End of inlined file: juce_ToneGeneratorAudioSource.h ***/
  24181. #endif
  24182. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24183. /*** Start of inlined file: juce_AudioDeviceManager.h ***/
  24184. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24185. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24186. /*** Start of inlined file: juce_AudioIODeviceType.h ***/
  24187. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24188. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24189. class AudioDeviceManager;
  24190. class Component;
  24191. /**
  24192. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  24193. To get a list of available audio driver types, use the AudioDeviceManager::createAudioDeviceTypes()
  24194. method. Each of the objects returned can then be used to list the available
  24195. devices of that type. E.g.
  24196. @code
  24197. OwnedArray <AudioIODeviceType> types;
  24198. myAudioDeviceManager.createAudioDeviceTypes (types);
  24199. for (int i = 0; i < types.size(); ++i)
  24200. {
  24201. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  24202. types[i]->scanForDevices(); // This must be called before getting the list of devices
  24203. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  24204. for (int j = 0; j < deviceNames.size(); ++j)
  24205. {
  24206. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  24207. ...
  24208. }
  24209. }
  24210. @endcode
  24211. For an easier way of managing audio devices and their settings, have a look at the
  24212. AudioDeviceManager class.
  24213. @see AudioIODevice, AudioDeviceManager
  24214. */
  24215. class JUCE_API AudioIODeviceType
  24216. {
  24217. public:
  24218. /** Returns the name of this type of driver that this object manages.
  24219. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  24220. */
  24221. const String& getTypeName() const throw() { return typeName; }
  24222. /** Refreshes the object's cached list of known devices.
  24223. This must be called at least once before calling getDeviceNames() or any of
  24224. the other device creation methods.
  24225. */
  24226. virtual void scanForDevices() = 0;
  24227. /** Returns the list of available devices of this type.
  24228. The scanForDevices() method must have been called to create this list.
  24229. @param wantInputNames only really used by DirectSound where devices are split up
  24230. into inputs and outputs, this indicates whether to use
  24231. the input or output name to refer to a pair of devices.
  24232. */
  24233. virtual const StringArray getDeviceNames (bool wantInputNames = false) const = 0;
  24234. /** Returns the name of the default device.
  24235. This will be one of the names from the getDeviceNames() list.
  24236. @param forInput if true, this means that a default input device should be
  24237. returned; if false, it should return the default output
  24238. */
  24239. virtual int getDefaultDeviceIndex (bool forInput) const = 0;
  24240. /** Returns the index of a given device in the list of device names.
  24241. If asInput is true, it shows the index in the inputs list, otherwise it
  24242. looks for it in the outputs list.
  24243. */
  24244. virtual int getIndexOfDevice (AudioIODevice* device, bool asInput) const = 0;
  24245. /** Returns true if two different devices can be used for the input and output.
  24246. */
  24247. virtual bool hasSeparateInputsAndOutputs() const = 0;
  24248. /** Creates one of the devices of this type.
  24249. The deviceName must be one of the strings returned by getDeviceNames(), and
  24250. scanForDevices() must have been called before this method is used.
  24251. */
  24252. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  24253. const String& inputDeviceName) = 0;
  24254. struct DeviceSetupDetails
  24255. {
  24256. AudioDeviceManager* manager;
  24257. int minNumInputChannels, maxNumInputChannels;
  24258. int minNumOutputChannels, maxNumOutputChannels;
  24259. bool useStereoPairs;
  24260. };
  24261. /** Destructor. */
  24262. virtual ~AudioIODeviceType();
  24263. protected:
  24264. explicit AudioIODeviceType (const String& typeName);
  24265. private:
  24266. String typeName;
  24267. AudioIODeviceType (const AudioIODeviceType&);
  24268. AudioIODeviceType& operator= (const AudioIODeviceType&);
  24269. };
  24270. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24271. /*** End of inlined file: juce_AudioIODeviceType.h ***/
  24272. /*** Start of inlined file: juce_MidiInput.h ***/
  24273. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  24274. #define __JUCE_MIDIINPUT_JUCEHEADER__
  24275. /*** Start of inlined file: juce_MidiMessage.h ***/
  24276. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  24277. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  24278. /**
  24279. Encapsulates a MIDI message.
  24280. @see MidiMessageSequence, MidiOutput, MidiInput
  24281. */
  24282. class JUCE_API MidiMessage
  24283. {
  24284. public:
  24285. /** Creates a 3-byte short midi message.
  24286. @param byte1 message byte 1
  24287. @param byte2 message byte 2
  24288. @param byte3 message byte 3
  24289. @param timeStamp the time to give the midi message - this value doesn't
  24290. use any particular units, so will be application-specific
  24291. */
  24292. MidiMessage (int byte1, int byte2, int byte3, double timeStamp = 0) throw();
  24293. /** Creates a 2-byte short midi message.
  24294. @param byte1 message byte 1
  24295. @param byte2 message byte 2
  24296. @param timeStamp the time to give the midi message - this value doesn't
  24297. use any particular units, so will be application-specific
  24298. */
  24299. MidiMessage (int byte1, int byte2, double timeStamp = 0) throw();
  24300. /** Creates a 1-byte short midi message.
  24301. @param byte1 message byte 1
  24302. @param timeStamp the time to give the midi message - this value doesn't
  24303. use any particular units, so will be application-specific
  24304. */
  24305. MidiMessage (int byte1, double timeStamp = 0) throw();
  24306. /** Creates a midi message from a block of data. */
  24307. MidiMessage (const void* data, int numBytes, double timeStamp = 0);
  24308. /** Reads the next midi message from some data.
  24309. This will read as many bytes from a data stream as it needs to make a
  24310. complete message, and will return the number of bytes it used. This lets
  24311. you read a sequence of midi messages from a file or stream.
  24312. @param data the data to read from
  24313. @param maxBytesToUse the maximum number of bytes it's allowed to read
  24314. @param numBytesUsed returns the number of bytes that were actually needed
  24315. @param lastStatusByte in a sequence of midi messages, the initial byte
  24316. can be dropped from a message if it's the same as the
  24317. first byte of the previous message, so this lets you
  24318. supply the byte to use if the first byte of the message
  24319. has in fact been dropped.
  24320. @param timeStamp the time to give the midi message - this value doesn't
  24321. use any particular units, so will be application-specific
  24322. */
  24323. MidiMessage (const void* data, int maxBytesToUse,
  24324. int& numBytesUsed, uint8 lastStatusByte,
  24325. double timeStamp = 0);
  24326. /** Creates a copy of another midi message. */
  24327. MidiMessage (const MidiMessage& other);
  24328. /** Creates a copy of another midi message, with a different timestamp. */
  24329. MidiMessage (const MidiMessage& other, double newTimeStamp);
  24330. /** Destructor. */
  24331. ~MidiMessage();
  24332. /** Copies this message from another one. */
  24333. MidiMessage& operator= (const MidiMessage& other);
  24334. /** Returns a pointer to the raw midi data.
  24335. @see getRawDataSize
  24336. */
  24337. uint8* getRawData() const throw() { return data; }
  24338. /** Returns the number of bytes of data in the message.
  24339. @see getRawData
  24340. */
  24341. int getRawDataSize() const throw() { return size; }
  24342. /** Returns the timestamp associated with this message.
  24343. The exact meaning of this time and its units will vary, as messages are used in
  24344. a variety of different contexts.
  24345. If you're getting the message from a midi file, this could be a time in seconds, or
  24346. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  24347. If the message is being used in a MidiBuffer, it might indicate the number of
  24348. audio samples from the start of the buffer.
  24349. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  24350. for details of the way that it initialises this value.
  24351. @see setTimeStamp, addToTimeStamp
  24352. */
  24353. double getTimeStamp() const throw() { return timeStamp; }
  24354. /** Changes the message's associated timestamp.
  24355. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  24356. @see addToTimeStamp, getTimeStamp
  24357. */
  24358. void setTimeStamp (double newTimestamp) throw() { timeStamp = newTimestamp; }
  24359. /** Adds a value to the message's timestamp.
  24360. The units for the timestamp will be application-specific.
  24361. */
  24362. void addToTimeStamp (double delta) throw() { timeStamp += delta; }
  24363. /** Returns the midi channel associated with the message.
  24364. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  24365. if it's a sysex)
  24366. @see isForChannel, setChannel
  24367. */
  24368. int getChannel() const throw();
  24369. /** Returns true if the message applies to the given midi channel.
  24370. @param channelNumber the channel number to look for, in the range 1 to 16
  24371. @see getChannel, setChannel
  24372. */
  24373. bool isForChannel (int channelNumber) const throw();
  24374. /** Changes the message's midi channel.
  24375. This won't do anything for non-channel messages like sysexes.
  24376. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  24377. */
  24378. void setChannel (int newChannelNumber) throw();
  24379. /** Returns true if this is a system-exclusive message.
  24380. */
  24381. bool isSysEx() const throw();
  24382. /** Returns a pointer to the sysex data inside the message.
  24383. If this event isn't a sysex event, it'll return 0.
  24384. @see getSysExDataSize
  24385. */
  24386. const uint8* getSysExData() const throw();
  24387. /** Returns the size of the sysex data.
  24388. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  24389. @see getSysExData
  24390. */
  24391. int getSysExDataSize() const throw();
  24392. /** Returns true if this message is a 'key-down' event.
  24393. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  24394. velocity 0, it will still be considered to be a note-on and the
  24395. method will return true. If returnTrueForVelocity0 is false, then
  24396. if this is a note-on event with velocity 0, it'll be regarded as
  24397. a note-off, and the method will return false
  24398. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  24399. */
  24400. bool isNoteOn (bool returnTrueForVelocity0 = false) const throw();
  24401. /** Creates a key-down message (using a floating-point velocity).
  24402. @param channel the midi channel, in the range 1 to 16
  24403. @param noteNumber the key number, 0 to 127
  24404. @param velocity in the range 0 to 1.0
  24405. @see isNoteOn
  24406. */
  24407. static const MidiMessage noteOn (int channel, int noteNumber, float velocity) throw();
  24408. /** Creates a key-down message (using an integer velocity).
  24409. @param channel the midi channel, in the range 1 to 16
  24410. @param noteNumber the key number, 0 to 127
  24411. @param velocity in the range 0 to 127
  24412. @see isNoteOn
  24413. */
  24414. static const MidiMessage noteOn (int channel, int noteNumber, uint8 velocity) throw();
  24415. /** Returns true if this message is a 'key-up' event.
  24416. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  24417. for a note-on event with a velocity of 0.
  24418. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  24419. */
  24420. bool isNoteOff (bool returnTrueForNoteOnVelocity0 = true) const throw();
  24421. /** Creates a key-up message.
  24422. @param channel the midi channel, in the range 1 to 16
  24423. @param noteNumber the key number, 0 to 127
  24424. @see isNoteOff
  24425. */
  24426. static const MidiMessage noteOff (int channel, int noteNumber) throw();
  24427. /** Returns true if this message is a 'key-down' or 'key-up' event.
  24428. @see isNoteOn, isNoteOff
  24429. */
  24430. bool isNoteOnOrOff() const throw();
  24431. /** Returns the midi note number for note-on and note-off messages.
  24432. If the message isn't a note-on or off, the value returned will be
  24433. meaningless.
  24434. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  24435. */
  24436. int getNoteNumber() const throw();
  24437. /** Changes the midi note number of a note-on or note-off message.
  24438. If the message isn't a note on or off, this will do nothing.
  24439. */
  24440. void setNoteNumber (int newNoteNumber) throw();
  24441. /** Returns the velocity of a note-on or note-off message.
  24442. The value returned will be in the range 0 to 127.
  24443. If the message isn't a note-on or off event, it will return 0.
  24444. @see getFloatVelocity
  24445. */
  24446. uint8 getVelocity() const throw();
  24447. /** Returns the velocity of a note-on or note-off message.
  24448. The value returned will be in the range 0 to 1.0
  24449. If the message isn't a note-on or off event, it will return 0.
  24450. @see getVelocity, setVelocity
  24451. */
  24452. float getFloatVelocity() const throw();
  24453. /** Changes the velocity of a note-on or note-off message.
  24454. If the message isn't a note on or off, this will do nothing.
  24455. @param newVelocity the new velocity, in the range 0 to 1.0
  24456. @see getFloatVelocity, multiplyVelocity
  24457. */
  24458. void setVelocity (float newVelocity) throw();
  24459. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  24460. If the message isn't a note on or off, this will do nothing.
  24461. @param scaleFactor the value by which to multiply the velocity
  24462. @see setVelocity
  24463. */
  24464. void multiplyVelocity (float scaleFactor) throw();
  24465. /** Returns true if the message is a program (patch) change message.
  24466. @see getProgramChangeNumber, getGMInstrumentName
  24467. */
  24468. bool isProgramChange() const throw();
  24469. /** Returns the new program number of a program change message.
  24470. If the message isn't a program change, the value returned will be
  24471. nonsense.
  24472. @see isProgramChange, getGMInstrumentName
  24473. */
  24474. int getProgramChangeNumber() const throw();
  24475. /** Creates a program-change message.
  24476. @param channel the midi channel, in the range 1 to 16
  24477. @param programNumber the midi program number, 0 to 127
  24478. @see isProgramChange, getGMInstrumentName
  24479. */
  24480. static const MidiMessage programChange (int channel, int programNumber) throw();
  24481. /** Returns true if the message is a pitch-wheel move.
  24482. @see getPitchWheelValue, pitchWheel
  24483. */
  24484. bool isPitchWheel() const throw();
  24485. /** Returns the pitch wheel position from a pitch-wheel move message.
  24486. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  24487. If called for messages which aren't pitch wheel events, the number returned will be
  24488. nonsense.
  24489. @see isPitchWheel
  24490. */
  24491. int getPitchWheelValue() const throw();
  24492. /** Creates a pitch-wheel move message.
  24493. @param channel the midi channel, in the range 1 to 16
  24494. @param position the wheel position, in the range 0 to 16383
  24495. @see isPitchWheel
  24496. */
  24497. static const MidiMessage pitchWheel (int channel, int position) throw();
  24498. /** Returns true if the message is an aftertouch event.
  24499. For aftertouch events, use the getNoteNumber() method to find out the key
  24500. that it applies to, and getAftertouchValue() to find out the amount. Use
  24501. getChannel() to find out the channel.
  24502. @see getAftertouchValue, getNoteNumber
  24503. */
  24504. bool isAftertouch() const throw();
  24505. /** Returns the amount of aftertouch from an aftertouch messages.
  24506. The value returned is in the range 0 to 127, and will be nonsense for messages
  24507. other than aftertouch messages.
  24508. @see isAftertouch
  24509. */
  24510. int getAfterTouchValue() const throw();
  24511. /** Creates an aftertouch message.
  24512. @param channel the midi channel, in the range 1 to 16
  24513. @param noteNumber the key number, 0 to 127
  24514. @param aftertouchAmount the amount of aftertouch, 0 to 127
  24515. @see isAftertouch
  24516. */
  24517. static const MidiMessage aftertouchChange (int channel,
  24518. int noteNumber,
  24519. int aftertouchAmount) throw();
  24520. /** Returns true if the message is a channel-pressure change event.
  24521. This is like aftertouch, but common to the whole channel rather than a specific
  24522. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  24523. to find out the channel.
  24524. @see channelPressureChange
  24525. */
  24526. bool isChannelPressure() const throw();
  24527. /** Returns the pressure from a channel pressure change message.
  24528. @returns the pressure, in the range 0 to 127
  24529. @see isChannelPressure, channelPressureChange
  24530. */
  24531. int getChannelPressureValue() const throw();
  24532. /** Creates a channel-pressure change event.
  24533. @param channel the midi channel: 1 to 16
  24534. @param pressure the pressure, 0 to 127
  24535. @see isChannelPressure
  24536. */
  24537. static const MidiMessage channelPressureChange (int channel, int pressure) throw();
  24538. /** Returns true if this is a midi controller message.
  24539. @see getControllerNumber, getControllerValue, controllerEvent
  24540. */
  24541. bool isController() const throw();
  24542. /** Returns the controller number of a controller message.
  24543. The name of the controller can be looked up using the getControllerName() method.
  24544. Note that the value returned is invalid for messages that aren't controller changes.
  24545. @see isController, getControllerName, getControllerValue
  24546. */
  24547. int getControllerNumber() const throw();
  24548. /** Returns the controller value from a controller message.
  24549. A value 0 to 127 is returned to indicate the new controller position.
  24550. Note that the value returned is invalid for messages that aren't controller changes.
  24551. @see isController, getControllerNumber
  24552. */
  24553. int getControllerValue() const throw();
  24554. /** Creates a controller message.
  24555. @param channel the midi channel, in the range 1 to 16
  24556. @param controllerType the type of controller
  24557. @param value the controller value
  24558. @see isController
  24559. */
  24560. static const MidiMessage controllerEvent (int channel,
  24561. int controllerType,
  24562. int value) throw();
  24563. /** Checks whether this message is an all-notes-off message.
  24564. @see allNotesOff
  24565. */
  24566. bool isAllNotesOff() const throw();
  24567. /** Checks whether this message is an all-sound-off message.
  24568. @see allSoundOff
  24569. */
  24570. bool isAllSoundOff() const throw();
  24571. /** Creates an all-notes-off message.
  24572. @param channel the midi channel, in the range 1 to 16
  24573. @see isAllNotesOff
  24574. */
  24575. static const MidiMessage allNotesOff (int channel) throw();
  24576. /** Creates an all-sound-off message.
  24577. @param channel the midi channel, in the range 1 to 16
  24578. @see isAllSoundOff
  24579. */
  24580. static const MidiMessage allSoundOff (int channel) throw();
  24581. /** Creates an all-controllers-off message.
  24582. @param channel the midi channel, in the range 1 to 16
  24583. */
  24584. static const MidiMessage allControllersOff (int channel) throw();
  24585. /** Returns true if this event is a meta-event.
  24586. Meta-events are things like tempo changes, track names, etc.
  24587. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  24588. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  24589. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  24590. */
  24591. bool isMetaEvent() const throw();
  24592. /** Returns a meta-event's type number.
  24593. If the message isn't a meta-event, this will return -1.
  24594. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  24595. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  24596. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  24597. */
  24598. int getMetaEventType() const throw();
  24599. /** Returns a pointer to the data in a meta-event.
  24600. @see isMetaEvent, getMetaEventLength
  24601. */
  24602. const uint8* getMetaEventData() const throw();
  24603. /** Returns the length of the data for a meta-event.
  24604. @see isMetaEvent, getMetaEventData
  24605. */
  24606. int getMetaEventLength() const throw();
  24607. /** Returns true if this is a 'track' meta-event. */
  24608. bool isTrackMetaEvent() const throw();
  24609. /** Returns true if this is an 'end-of-track' meta-event. */
  24610. bool isEndOfTrackMetaEvent() const throw();
  24611. /** Creates an end-of-track meta-event.
  24612. @see isEndOfTrackMetaEvent
  24613. */
  24614. static const MidiMessage endOfTrack() throw();
  24615. /** Returns true if this is an 'track name' meta-event.
  24616. You can use the getTextFromTextMetaEvent() method to get the track's name.
  24617. */
  24618. bool isTrackNameEvent() const throw();
  24619. /** Returns true if this is a 'text' meta-event.
  24620. @see getTextFromTextMetaEvent
  24621. */
  24622. bool isTextMetaEvent() const throw();
  24623. /** Returns the text from a text meta-event.
  24624. @see isTextMetaEvent
  24625. */
  24626. const String getTextFromTextMetaEvent() const;
  24627. /** Returns true if this is a 'tempo' meta-event.
  24628. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  24629. */
  24630. bool isTempoMetaEvent() const throw();
  24631. /** Returns the tick length from a tempo meta-event.
  24632. @param timeFormat the 16-bit time format value from the midi file's header.
  24633. @returns the tick length (in seconds).
  24634. @see isTempoMetaEvent
  24635. */
  24636. double getTempoMetaEventTickLength (short timeFormat) const throw();
  24637. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  24638. @see isTempoMetaEvent, getTempoMetaEventTickLength
  24639. */
  24640. double getTempoSecondsPerQuarterNote() const throw();
  24641. /** Creates a tempo meta-event.
  24642. @see isTempoMetaEvent
  24643. */
  24644. static const MidiMessage tempoMetaEvent (int microsecondsPerQuarterNote) throw();
  24645. /** Returns true if this is a 'time-signature' meta-event.
  24646. @see getTimeSignatureInfo
  24647. */
  24648. bool isTimeSignatureMetaEvent() const throw();
  24649. /** Returns the time-signature values from a time-signature meta-event.
  24650. @see isTimeSignatureMetaEvent
  24651. */
  24652. void getTimeSignatureInfo (int& numerator, int& denominator) const throw();
  24653. /** Creates a time-signature meta-event.
  24654. @see isTimeSignatureMetaEvent
  24655. */
  24656. static const MidiMessage timeSignatureMetaEvent (int numerator, int denominator);
  24657. /** Returns true if this is a 'key-signature' meta-event.
  24658. @see getKeySignatureNumberOfSharpsOrFlats
  24659. */
  24660. bool isKeySignatureMetaEvent() const throw();
  24661. /** Returns the key from a key-signature meta-event.
  24662. @see isKeySignatureMetaEvent
  24663. */
  24664. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  24665. /** Returns true if this is a 'channel' meta-event.
  24666. A channel meta-event specifies the midi channel that should be used
  24667. for subsequent meta-events.
  24668. @see getMidiChannelMetaEventChannel
  24669. */
  24670. bool isMidiChannelMetaEvent() const throw();
  24671. /** Returns the channel number from a channel meta-event.
  24672. @returns the channel, in the range 1 to 16.
  24673. @see isMidiChannelMetaEvent
  24674. */
  24675. int getMidiChannelMetaEventChannel() const throw();
  24676. /** Creates a midi channel meta-event.
  24677. @param channel the midi channel, in the range 1 to 16
  24678. @see isMidiChannelMetaEvent
  24679. */
  24680. static const MidiMessage midiChannelMetaEvent (int channel) throw();
  24681. /** Returns true if this is an active-sense message. */
  24682. bool isActiveSense() const throw();
  24683. /** Returns true if this is a midi start event.
  24684. @see midiStart
  24685. */
  24686. bool isMidiStart() const throw();
  24687. /** Creates a midi start event. */
  24688. static const MidiMessage midiStart() throw();
  24689. /** Returns true if this is a midi continue event.
  24690. @see midiContinue
  24691. */
  24692. bool isMidiContinue() const throw();
  24693. /** Creates a midi continue event. */
  24694. static const MidiMessage midiContinue() throw();
  24695. /** Returns true if this is a midi stop event.
  24696. @see midiStop
  24697. */
  24698. bool isMidiStop() const throw();
  24699. /** Creates a midi stop event. */
  24700. static const MidiMessage midiStop() throw();
  24701. /** Returns true if this is a midi clock event.
  24702. @see midiClock, songPositionPointer
  24703. */
  24704. bool isMidiClock() const throw();
  24705. /** Creates a midi clock event. */
  24706. static const MidiMessage midiClock() throw();
  24707. /** Returns true if this is a song-position-pointer message.
  24708. @see getSongPositionPointerMidiBeat, songPositionPointer
  24709. */
  24710. bool isSongPositionPointer() const throw();
  24711. /** Returns the midi beat-number of a song-position-pointer message.
  24712. @see isSongPositionPointer, songPositionPointer
  24713. */
  24714. int getSongPositionPointerMidiBeat() const throw();
  24715. /** Creates a song-position-pointer message.
  24716. The position is a number of midi beats from the start of the song, where 1 midi
  24717. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  24718. are 4 midi beats in a quarter-note.
  24719. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  24720. */
  24721. static const MidiMessage songPositionPointer (int positionInMidiBeats) throw();
  24722. /** Returns true if this is a quarter-frame midi timecode message.
  24723. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  24724. */
  24725. bool isQuarterFrame() const throw();
  24726. /** Returns the sequence number of a quarter-frame midi timecode message.
  24727. This will be a value between 0 and 7.
  24728. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  24729. */
  24730. int getQuarterFrameSequenceNumber() const throw();
  24731. /** Returns the value from a quarter-frame message.
  24732. This will be the lower nybble of the message's data-byte, a value
  24733. between 0 and 15
  24734. */
  24735. int getQuarterFrameValue() const throw();
  24736. /** Creates a quarter-frame MTC message.
  24737. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  24738. @param value a value 0 to 15 for the lower nybble of the message's data byte
  24739. */
  24740. static const MidiMessage quarterFrame (int sequenceNumber, int value) throw();
  24741. /** SMPTE timecode types.
  24742. Used by the getFullFrameParameters() and fullFrame() methods.
  24743. */
  24744. enum SmpteTimecodeType
  24745. {
  24746. fps24 = 0,
  24747. fps25 = 1,
  24748. fps30drop = 2,
  24749. fps30 = 3
  24750. };
  24751. /** Returns true if this is a full-frame midi timecode message.
  24752. */
  24753. bool isFullFrame() const throw();
  24754. /** Extracts the timecode information from a full-frame midi timecode message.
  24755. You should only call this on messages where you've used isFullFrame() to
  24756. check that they're the right kind.
  24757. */
  24758. void getFullFrameParameters (int& hours,
  24759. int& minutes,
  24760. int& seconds,
  24761. int& frames,
  24762. SmpteTimecodeType& timecodeType) const throw();
  24763. /** Creates a full-frame MTC message.
  24764. */
  24765. static const MidiMessage fullFrame (int hours,
  24766. int minutes,
  24767. int seconds,
  24768. int frames,
  24769. SmpteTimecodeType timecodeType);
  24770. /** Types of MMC command.
  24771. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  24772. */
  24773. enum MidiMachineControlCommand
  24774. {
  24775. mmc_stop = 1,
  24776. mmc_play = 2,
  24777. mmc_deferredplay = 3,
  24778. mmc_fastforward = 4,
  24779. mmc_rewind = 5,
  24780. mmc_recordStart = 6,
  24781. mmc_recordStop = 7,
  24782. mmc_pause = 9
  24783. };
  24784. /** Checks whether this is an MMC message.
  24785. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  24786. */
  24787. bool isMidiMachineControlMessage() const throw();
  24788. /** For an MMC message, this returns its type.
  24789. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  24790. calling this method.
  24791. */
  24792. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  24793. /** Creates an MMC message.
  24794. */
  24795. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  24796. /** Checks whether this is an MMC "goto" message.
  24797. If it is, the parameters passed-in are set to the time that the message contains.
  24798. @see midiMachineControlGoto
  24799. */
  24800. bool isMidiMachineControlGoto (int& hours,
  24801. int& minutes,
  24802. int& seconds,
  24803. int& frames) const throw();
  24804. /** Creates an MMC "goto" message.
  24805. This messages tells the device to go to a specific frame.
  24806. @see isMidiMachineControlGoto
  24807. */
  24808. static const MidiMessage midiMachineControlGoto (int hours,
  24809. int minutes,
  24810. int seconds,
  24811. int frames);
  24812. /** Creates a master-volume change message.
  24813. @param volume the volume, 0 to 1.0
  24814. */
  24815. static const MidiMessage masterVolume (float volume);
  24816. /** Creates a system-exclusive message.
  24817. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  24818. */
  24819. static const MidiMessage createSysExMessage (const uint8* sysexData,
  24820. int dataSize);
  24821. /** Reads a midi variable-length integer.
  24822. @param data the data to read the number from
  24823. @param numBytesUsed on return, this will be set to the number of bytes that were read
  24824. */
  24825. static int readVariableLengthVal (const uint8* data,
  24826. int& numBytesUsed) throw();
  24827. /** Based on the first byte of a short midi message, this uses a lookup table
  24828. to return the message length (either 1, 2, or 3 bytes).
  24829. The value passed in must be 0x80 or higher.
  24830. */
  24831. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  24832. /** Returns the name of a midi note number.
  24833. E.g "C", "D#", etc.
  24834. @param noteNumber the midi note number, 0 to 127
  24835. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  24836. they'll be flattened, e.g. "Db"
  24837. @param includeOctaveNumber if true, the octave number will be appended to the string,
  24838. e.g. "C#4"
  24839. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  24840. number that will be used for middle C's octave
  24841. @see getMidiNoteInHertz
  24842. */
  24843. static const String getMidiNoteName (int noteNumber,
  24844. bool useSharps,
  24845. bool includeOctaveNumber,
  24846. int octaveNumForMiddleC) throw();
  24847. /** Returns the frequency of a midi note number.
  24848. @see getMidiNoteName
  24849. */
  24850. static const double getMidiNoteInHertz (int noteNumber) throw();
  24851. /** Returns the standard name of a GM instrument.
  24852. @param midiInstrumentNumber the program number 0 to 127
  24853. @see getProgramChangeNumber
  24854. */
  24855. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  24856. /** Returns the name of a bank of GM instruments.
  24857. @param midiBankNumber the bank, 0 to 15
  24858. */
  24859. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  24860. /** Returns the standard name of a channel 10 percussion sound.
  24861. @param midiNoteNumber the key number, 35 to 81
  24862. */
  24863. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  24864. /** Returns the name of a controller type number.
  24865. @see getControllerNumber
  24866. */
  24867. static const String getControllerName (int controllerNumber) throw();
  24868. juce_UseDebuggingNewOperator
  24869. private:
  24870. double timeStamp;
  24871. uint8* data;
  24872. int size;
  24873. union
  24874. {
  24875. uint8 asBytes[4];
  24876. uint32 asInt32;
  24877. } preallocatedData;
  24878. };
  24879. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  24880. /*** End of inlined file: juce_MidiMessage.h ***/
  24881. class MidiInput;
  24882. /**
  24883. Receives midi messages from a midi input device.
  24884. This class is overridden to handle incoming midi messages. See the MidiInput
  24885. class for more details.
  24886. @see MidiInput
  24887. */
  24888. class JUCE_API MidiInputCallback
  24889. {
  24890. public:
  24891. /** Destructor. */
  24892. virtual ~MidiInputCallback() {}
  24893. /** Receives an incoming message.
  24894. A MidiInput object will call this method when a midi event arrives. It'll be
  24895. called on a high-priority system thread, so avoid doing anything time-consuming
  24896. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  24897. for queueing incoming messages for use later.
  24898. @param source the MidiInput object that generated the message
  24899. @param message the incoming message. The message's timestamp is set to a value
  24900. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  24901. time when the message arrived.
  24902. */
  24903. virtual void handleIncomingMidiMessage (MidiInput* source,
  24904. const MidiMessage& message) = 0;
  24905. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  24906. If a long sysex message is broken up into multiple packets, this callback is made
  24907. for each packet that arrives until the message is finished, at which point
  24908. the normal handleIncomingMidiMessage() callback will be made with the entire
  24909. message.
  24910. The message passed in will contain the start of a sysex, but won't be finished
  24911. with the terminating 0xf7 byte.
  24912. */
  24913. virtual void handlePartialSysexMessage (MidiInput* source,
  24914. const uint8* messageData,
  24915. const int numBytesSoFar,
  24916. const double timestamp)
  24917. {
  24918. // (this bit is just to avoid compiler warnings about unused variables)
  24919. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  24920. }
  24921. };
  24922. /**
  24923. Represents a midi input device.
  24924. To create one of these, use the static getDevices() method to find out what inputs are
  24925. available, and then use the openDevice() method to try to open one.
  24926. @see MidiOutput
  24927. */
  24928. class JUCE_API MidiInput
  24929. {
  24930. public:
  24931. /** Returns a list of the available midi input devices.
  24932. You can open one of the devices by passing its index into the
  24933. openDevice() method.
  24934. @see getDefaultDeviceIndex, openDevice
  24935. */
  24936. static const StringArray getDevices();
  24937. /** Returns the index of the default midi input device to use.
  24938. This refers to the index in the list returned by getDevices().
  24939. */
  24940. static int getDefaultDeviceIndex();
  24941. /** Tries to open one of the midi input devices.
  24942. This will return a MidiInput object if it manages to open it. You can then
  24943. call start() and stop() on this device, and delete it when no longer needed.
  24944. If the device can't be opened, this will return a null pointer.
  24945. @param deviceIndex the index of a device from the list returned by getDevices()
  24946. @param callback the object that will receive the midi messages from this device.
  24947. @see MidiInputCallback, getDevices
  24948. */
  24949. static MidiInput* openDevice (int deviceIndex,
  24950. MidiInputCallback* callback);
  24951. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  24952. /** This will try to create a new midi input device (Not available on Windows).
  24953. This will attempt to create a new midi input device with the specified name,
  24954. for other apps to connect to.
  24955. Returns 0 if a device can't be created.
  24956. @param deviceName the name to use for the new device
  24957. @param callback the object that will receive the midi messages from this device.
  24958. */
  24959. static MidiInput* createNewDevice (const String& deviceName,
  24960. MidiInputCallback* callback);
  24961. #endif
  24962. /** Destructor. */
  24963. virtual ~MidiInput();
  24964. /** Returns the name of this device.
  24965. */
  24966. virtual const String getName() const throw() { return name; }
  24967. /** Allows you to set a custom name for the device, in case you don't like the name
  24968. it was given when created.
  24969. */
  24970. virtual void setName (const String& newName) throw() { name = newName; }
  24971. /** Starts the device running.
  24972. After calling this, the device will start sending midi messages to the
  24973. MidiInputCallback object that was specified when the openDevice() method
  24974. was called.
  24975. @see stop
  24976. */
  24977. virtual void start();
  24978. /** Stops the device running.
  24979. @see start
  24980. */
  24981. virtual void stop();
  24982. juce_UseDebuggingNewOperator
  24983. protected:
  24984. String name;
  24985. void* internal;
  24986. explicit MidiInput (const String& name);
  24987. private:
  24988. MidiInput (const MidiInput&);
  24989. MidiInput& operator= (const MidiInput&);
  24990. };
  24991. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  24992. /*** End of inlined file: juce_MidiInput.h ***/
  24993. /*** Start of inlined file: juce_MidiOutput.h ***/
  24994. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  24995. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  24996. /*** Start of inlined file: juce_MidiBuffer.h ***/
  24997. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  24998. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  24999. /**
  25000. Holds a sequence of time-stamped midi events.
  25001. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  25002. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  25003. @see MidiMessage
  25004. */
  25005. class JUCE_API MidiBuffer
  25006. {
  25007. public:
  25008. /** Creates an empty MidiBuffer. */
  25009. MidiBuffer() throw();
  25010. /** Creates a MidiBuffer containing a single midi message. */
  25011. explicit MidiBuffer (const MidiMessage& message) throw();
  25012. /** Creates a copy of another MidiBuffer. */
  25013. MidiBuffer (const MidiBuffer& other) throw();
  25014. /** Makes a copy of another MidiBuffer. */
  25015. MidiBuffer& operator= (const MidiBuffer& other) throw();
  25016. /** Destructor */
  25017. ~MidiBuffer() throw();
  25018. /** Removes all events from the buffer. */
  25019. void clear() throw();
  25020. /** Removes all events between two times from the buffer.
  25021. All events for which (start <= event position < start + numSamples) will
  25022. be removed.
  25023. */
  25024. void clear (const int start,
  25025. const int numSamples) throw();
  25026. /** Returns true if the buffer is empty.
  25027. To actually retrieve the events, use a MidiBuffer::Iterator object
  25028. */
  25029. bool isEmpty() const throw();
  25030. /** Counts the number of events in the buffer.
  25031. This is actually quite a slow operation, as it has to iterate through all
  25032. the events, so you might prefer to call isEmpty() if that's all you need
  25033. to know.
  25034. */
  25035. int getNumEvents() const throw();
  25036. /** Adds an event to the buffer.
  25037. The sample number will be used to determine the position of the event in
  25038. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  25039. ignored.
  25040. If an event is added whose sample position is the same as one or more events
  25041. already in the buffer, the new event will be placed after the existing ones.
  25042. To retrieve events, use a MidiBuffer::Iterator object
  25043. */
  25044. void addEvent (const MidiMessage& midiMessage,
  25045. const int sampleNumber) throw();
  25046. /** Adds an event to the buffer from raw midi data.
  25047. The sample number will be used to determine the position of the event in
  25048. the buffer, which is always kept sorted.
  25049. If an event is added whose sample position is the same as one or more events
  25050. already in the buffer, the new event will be placed after the existing ones.
  25051. The event data will be inspected to calculate the number of bytes in length that
  25052. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  25053. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  25054. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  25055. add an event at all.
  25056. To retrieve events, use a MidiBuffer::Iterator object
  25057. */
  25058. void addEvent (const uint8* const rawMidiData,
  25059. const int maxBytesOfMidiData,
  25060. const int sampleNumber) throw();
  25061. /** Adds some events from another buffer to this one.
  25062. @param otherBuffer the buffer containing the events you want to add
  25063. @param startSample the lowest sample number in the source buffer for which
  25064. events should be added. Any source events whose timestamp is
  25065. less than this will be ignored
  25066. @param numSamples the valid range of samples from the source buffer for which
  25067. events should be added - i.e. events in the source buffer whose
  25068. timestamp is greater than or equal to (startSample + numSamples)
  25069. will be ignored. If this value is less than 0, all events after
  25070. startSample will be taken.
  25071. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  25072. that are added to this buffer
  25073. */
  25074. void addEvents (const MidiBuffer& otherBuffer,
  25075. const int startSample,
  25076. const int numSamples,
  25077. const int sampleDeltaToAdd) throw();
  25078. /** Returns the sample number of the first event in the buffer.
  25079. If the buffer's empty, this will just return 0.
  25080. */
  25081. int getFirstEventTime() const throw();
  25082. /** Returns the sample number of the last event in the buffer.
  25083. If the buffer's empty, this will just return 0.
  25084. */
  25085. int getLastEventTime() const throw();
  25086. /** Exchanges the contents of this buffer with another one.
  25087. This is a quick operation, because no memory allocating or copying is done, it
  25088. just swaps the internal state of the two buffers.
  25089. */
  25090. void swapWith (MidiBuffer& other);
  25091. /** Preallocates some memory for the buffer to use.
  25092. This helps to avoid needing to reallocate space when the buffer has messages
  25093. added to it.
  25094. */
  25095. void ensureSize (size_t minimumNumBytes);
  25096. /**
  25097. Used to iterate through the events in a MidiBuffer.
  25098. Note that altering the buffer while an iterator is using it isn't a
  25099. safe operation.
  25100. @see MidiBuffer
  25101. */
  25102. class Iterator
  25103. {
  25104. public:
  25105. /** Creates an Iterator for this MidiBuffer. */
  25106. Iterator (const MidiBuffer& buffer) throw();
  25107. /** Destructor. */
  25108. ~Iterator() throw();
  25109. /** Repositions the iterator so that the next event retrieved will be the first
  25110. one whose sample position is at greater than or equal to the given position.
  25111. */
  25112. void setNextSamplePosition (const int samplePosition) throw();
  25113. /** Retrieves a copy of the next event from the buffer.
  25114. @param result on return, this will be the message (the MidiMessage's timestamp
  25115. is not set)
  25116. @param samplePosition on return, this will be the position of the event
  25117. @returns true if an event was found, or false if the iterator has reached
  25118. the end of the buffer
  25119. */
  25120. bool getNextEvent (MidiMessage& result,
  25121. int& samplePosition) throw();
  25122. /** Retrieves the next event from the buffer.
  25123. @param midiData on return, this pointer will be set to a block of data containing
  25124. the midi message. Note that to make it fast, this is a pointer
  25125. directly into the MidiBuffer's internal data, so is only valid
  25126. temporarily until the MidiBuffer is altered.
  25127. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  25128. midi message
  25129. @param samplePosition on return, this will be the position of the event
  25130. @returns true if an event was found, or false if the iterator has reached
  25131. the end of the buffer
  25132. */
  25133. bool getNextEvent (const uint8* &midiData,
  25134. int& numBytesOfMidiData,
  25135. int& samplePosition) throw();
  25136. juce_UseDebuggingNewOperator
  25137. private:
  25138. const MidiBuffer& buffer;
  25139. const uint8* data;
  25140. Iterator (const Iterator&);
  25141. Iterator& operator= (const Iterator&);
  25142. };
  25143. juce_UseDebuggingNewOperator
  25144. private:
  25145. friend class MidiBuffer::Iterator;
  25146. MemoryBlock data;
  25147. int bytesUsed;
  25148. uint8* getData() const throw();
  25149. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  25150. static int getEventTime (const void* d) throw();
  25151. static uint16 getEventDataSize (const void* d) throw();
  25152. static uint16 getEventTotalSize (const void* d) throw();
  25153. };
  25154. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  25155. /*** End of inlined file: juce_MidiBuffer.h ***/
  25156. /**
  25157. Represents a midi output device.
  25158. To create one of these, use the static getDevices() method to find out what
  25159. outputs are available, then use the openDevice() method to try to open one.
  25160. @see MidiInput
  25161. */
  25162. class JUCE_API MidiOutput : private Thread
  25163. {
  25164. public:
  25165. /** Returns a list of the available midi output devices.
  25166. You can open one of the devices by passing its index into the
  25167. openDevice() method.
  25168. @see getDefaultDeviceIndex, openDevice
  25169. */
  25170. static const StringArray getDevices();
  25171. /** Returns the index of the default midi output device to use.
  25172. This refers to the index in the list returned by getDevices().
  25173. */
  25174. static int getDefaultDeviceIndex();
  25175. /** Tries to open one of the midi output devices.
  25176. This will return a MidiOutput object if it manages to open it. You can then
  25177. send messages to this device, and delete it when no longer needed.
  25178. If the device can't be opened, this will return a null pointer.
  25179. @param deviceIndex the index of a device from the list returned by getDevices()
  25180. @see getDevices
  25181. */
  25182. static MidiOutput* openDevice (int deviceIndex);
  25183. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  25184. /** This will try to create a new midi output device (Not available on Windows).
  25185. This will attempt to create a new midi output device that other apps can connect
  25186. to and use as their midi input.
  25187. Returns 0 if a device can't be created.
  25188. @param deviceName the name to use for the new device
  25189. */
  25190. static MidiOutput* createNewDevice (const String& deviceName);
  25191. #endif
  25192. /** Destructor. */
  25193. virtual ~MidiOutput();
  25194. /** Makes this device output a midi message.
  25195. @see MidiMessage
  25196. */
  25197. virtual void sendMessageNow (const MidiMessage& message);
  25198. /** Sends a midi reset to the device. */
  25199. virtual void reset();
  25200. /** Returns the current volume setting for this device. */
  25201. virtual bool getVolume (float& leftVol,
  25202. float& rightVol);
  25203. /** Changes the overall volume for this device. */
  25204. virtual void setVolume (float leftVol,
  25205. float rightVol);
  25206. /** This lets you supply a block of messages that will be sent out at some point
  25207. in the future.
  25208. The MidiOutput class has an internal thread that can send out timestamped
  25209. messages - this appends a set of messages to its internal buffer, ready for
  25210. sending.
  25211. This will only work if you've already started the thread with startBackgroundThread().
  25212. A time is supplied, at which the block of messages should be sent. This time uses
  25213. the same time base as Time::getMillisecondCounter(), and must be in the future.
  25214. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  25215. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  25216. samplesPerSecondForBuffer value is needed to convert this sample position to a
  25217. real time.
  25218. */
  25219. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  25220. double millisecondCounterToStartAt,
  25221. double samplesPerSecondForBuffer);
  25222. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  25223. */
  25224. virtual void clearAllPendingMessages();
  25225. /** Starts up a background thread so that the device can send blocks of data.
  25226. Call this to get the device ready, before using sendBlockOfMessages().
  25227. */
  25228. virtual void startBackgroundThread();
  25229. /** Stops the background thread, and clears any pending midi events.
  25230. @see startBackgroundThread
  25231. */
  25232. virtual void stopBackgroundThread();
  25233. juce_UseDebuggingNewOperator
  25234. protected:
  25235. void* internal;
  25236. struct PendingMessage
  25237. {
  25238. PendingMessage (const uint8* data, int len, double sampleNumber);
  25239. MidiMessage message;
  25240. PendingMessage* next;
  25241. juce_UseDebuggingNewOperator
  25242. };
  25243. CriticalSection lock;
  25244. PendingMessage* firstMessage;
  25245. MidiOutput();
  25246. void run();
  25247. private:
  25248. MidiOutput (const MidiOutput&);
  25249. MidiOutput& operator= (const MidiOutput&);
  25250. };
  25251. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  25252. /*** End of inlined file: juce_MidiOutput.h ***/
  25253. /*** Start of inlined file: juce_ComboBox.h ***/
  25254. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  25255. #define __JUCE_COMBOBOX_JUCEHEADER__
  25256. /*** Start of inlined file: juce_Label.h ***/
  25257. #ifndef __JUCE_LABEL_JUCEHEADER__
  25258. #define __JUCE_LABEL_JUCEHEADER__
  25259. /*** Start of inlined file: juce_TextEditor.h ***/
  25260. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  25261. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  25262. /*** Start of inlined file: juce_Viewport.h ***/
  25263. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  25264. #define __JUCE_VIEWPORT_JUCEHEADER__
  25265. /*** Start of inlined file: juce_ScrollBar.h ***/
  25266. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  25267. #define __JUCE_SCROLLBAR_JUCEHEADER__
  25268. /*** Start of inlined file: juce_Button.h ***/
  25269. #ifndef __JUCE_BUTTON_JUCEHEADER__
  25270. #define __JUCE_BUTTON_JUCEHEADER__
  25271. /*** Start of inlined file: juce_TooltipWindow.h ***/
  25272. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  25273. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  25274. /*** Start of inlined file: juce_TooltipClient.h ***/
  25275. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  25276. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  25277. /**
  25278. Components that want to use pop-up tooltips should implement this interface.
  25279. A TooltipWindow will wait for the mouse to hover over a component that
  25280. implements the TooltipClient interface, and when it finds one, it will display
  25281. the tooltip returned by its getTooltip() method.
  25282. @see TooltipWindow, SettableTooltipClient
  25283. */
  25284. class JUCE_API TooltipClient
  25285. {
  25286. public:
  25287. /** Destructor. */
  25288. virtual ~TooltipClient() {}
  25289. /** Returns the string that this object wants to show as its tooltip. */
  25290. virtual const String getTooltip() = 0;
  25291. };
  25292. /**
  25293. An implementation of TooltipClient that stores the tooltip string and a method
  25294. for changing it.
  25295. This makes it easy to add a tooltip to a custom component, by simply adding this
  25296. as a base class and calling setTooltip().
  25297. Many of the Juce widgets already use this as a base class to implement their
  25298. tooltips.
  25299. @see TooltipClient, TooltipWindow
  25300. */
  25301. class JUCE_API SettableTooltipClient : public TooltipClient
  25302. {
  25303. public:
  25304. /** Destructor. */
  25305. virtual ~SettableTooltipClient() {}
  25306. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  25307. virtual const String getTooltip() { return tooltipString; }
  25308. juce_UseDebuggingNewOperator
  25309. protected:
  25310. String tooltipString;
  25311. };
  25312. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  25313. /*** End of inlined file: juce_TooltipClient.h ***/
  25314. /**
  25315. A window that displays a pop-up tooltip when the mouse hovers over another component.
  25316. To enable tooltips in your app, just create a single instance of a TooltipWindow
  25317. object.
  25318. The TooltipWindow object will then stay invisible, waiting until the mouse
  25319. hovers for the specified length of time - it will then see if it's currently
  25320. over a component which implements the TooltipClient interface, and if so,
  25321. it will make itself visible to show the tooltip in the appropriate place.
  25322. @see TooltipClient, SettableTooltipClient
  25323. */
  25324. class JUCE_API TooltipWindow : public Component,
  25325. private Timer
  25326. {
  25327. public:
  25328. /** Creates a tooltip window.
  25329. Make sure your app only creates one instance of this class, otherwise you'll
  25330. get multiple overlaid tooltips appearing. The window will initially be invisible
  25331. and will make itself visible when it needs to display a tip.
  25332. To change the style of tooltips, see the LookAndFeel class for its tooltip
  25333. methods.
  25334. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  25335. otherwise the tooltip will be added to the given parent
  25336. component.
  25337. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  25338. before a tooltip will be shown
  25339. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  25340. */
  25341. explicit TooltipWindow (Component* parentComponent = 0,
  25342. int millisecondsBeforeTipAppears = 700);
  25343. /** Destructor. */
  25344. ~TooltipWindow();
  25345. /** Changes the time before the tip appears.
  25346. This lets you change the value that was set in the constructor.
  25347. */
  25348. void setMillisecondsBeforeTipAppears (int newTimeMs = 700) throw();
  25349. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  25350. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25351. methods.
  25352. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25353. */
  25354. enum ColourIds
  25355. {
  25356. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  25357. textColourId = 0x1001c00, /**< The colour to use for the text. */
  25358. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  25359. };
  25360. juce_UseDebuggingNewOperator
  25361. private:
  25362. int millisecondsBeforeTipAppears;
  25363. Point<int> lastMousePos;
  25364. int mouseClicks;
  25365. unsigned int lastCompChangeTime, lastHideTime;
  25366. Component* lastComponentUnderMouse;
  25367. bool changedCompsSinceShown;
  25368. String tipShowing, lastTipUnderMouse;
  25369. void paint (Graphics& g);
  25370. void mouseEnter (const MouseEvent& e);
  25371. void timerCallback();
  25372. static const String getTipFor (Component* c);
  25373. void showFor (const String& tip);
  25374. void hide();
  25375. TooltipWindow (const TooltipWindow&);
  25376. TooltipWindow& operator= (const TooltipWindow&);
  25377. };
  25378. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  25379. /*** End of inlined file: juce_TooltipWindow.h ***/
  25380. class Button;
  25381. /**
  25382. Used to receive callbacks when a button is clicked.
  25383. @see Button::addButtonListener, Button::removeButtonListener
  25384. */
  25385. class JUCE_API ButtonListener
  25386. {
  25387. public:
  25388. /** Destructor. */
  25389. virtual ~ButtonListener() {}
  25390. /** Called when the button is clicked. */
  25391. virtual void buttonClicked (Button* button) = 0;
  25392. /** Called when the button's state changes. */
  25393. virtual void buttonStateChanged (Button*) {}
  25394. };
  25395. /**
  25396. A base class for buttons.
  25397. This contains all the logic for button behaviours such as enabling/disabling,
  25398. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  25399. and radio groups, etc.
  25400. @see TextButton, DrawableButton, ToggleButton
  25401. */
  25402. class JUCE_API Button : public Component,
  25403. public SettableTooltipClient,
  25404. public ApplicationCommandManagerListener,
  25405. public Value::Listener,
  25406. private KeyListener
  25407. {
  25408. protected:
  25409. /** Creates a button.
  25410. @param buttonName the text to put in the button (the component's name is also
  25411. initially set to this string, but these can be changed later
  25412. using the setName() and setButtonText() methods)
  25413. */
  25414. explicit Button (const String& buttonName);
  25415. public:
  25416. /** Destructor. */
  25417. virtual ~Button();
  25418. /** Changes the button's text.
  25419. @see getButtonText
  25420. */
  25421. void setButtonText (const String& newText);
  25422. /** Returns the text displayed in the button.
  25423. @see setButtonText
  25424. */
  25425. const String getButtonText() const { return text; }
  25426. /** Returns true if the button is currently being held down by the mouse.
  25427. @see isOver
  25428. */
  25429. bool isDown() const throw();
  25430. /** Returns true if the mouse is currently over the button.
  25431. This will be also be true if the mouse is being held down.
  25432. @see isDown
  25433. */
  25434. bool isOver() const throw();
  25435. /** A button has an on/off state associated with it, and this changes that.
  25436. By default buttons are 'off' and for simple buttons that you click to perform
  25437. an action you won't change this. Toggle buttons, however will want to
  25438. change their state when turned on or off.
  25439. @param shouldBeOn whether to set the button's toggle state to be on or
  25440. off. If it's a member of a button group, this will
  25441. always try to turn it on, and to turn off any other
  25442. buttons in the group
  25443. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  25444. the button will be repainted but no notification will
  25445. be sent
  25446. @see getToggleState, setRadioGroupId
  25447. */
  25448. void setToggleState (bool shouldBeOn,
  25449. bool sendChangeNotification);
  25450. /** Returns true if the button in 'on'.
  25451. By default buttons are 'off' and for simple buttons that you click to perform
  25452. an action you won't change this. Toggle buttons, however will want to
  25453. change their state when turned on or off.
  25454. @see setToggleState
  25455. */
  25456. bool getToggleState() const throw() { return isOn.getValue(); }
  25457. /** Returns the Value object that represents the botton's toggle state.
  25458. You can use this Value object to connect the button's state to external values or setters,
  25459. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  25460. your own Value object.
  25461. @see getToggleState, Value
  25462. */
  25463. Value& getToggleStateValue() { return isOn; }
  25464. /** This tells the button to automatically flip the toggle state when
  25465. the button is clicked.
  25466. If set to true, then before the clicked() callback occurs, the toggle-state
  25467. of the button is flipped.
  25468. */
  25469. void setClickingTogglesState (bool shouldToggle) throw();
  25470. /** Returns true if this button is set to be an automatic toggle-button.
  25471. This returns the last value that was passed to setClickingTogglesState().
  25472. */
  25473. bool getClickingTogglesState() const throw();
  25474. /** Enables the button to act as a member of a mutually-exclusive group
  25475. of 'radio buttons'.
  25476. If the group ID is set to a non-zero number, then this button will
  25477. act as part of a group of buttons with the same ID, only one of
  25478. which can be 'on' at the same time. Note that when it's part of
  25479. a group, clicking a toggle-button that's 'on' won't turn it off.
  25480. To find other buttons with the same ID, this button will search through
  25481. its sibling components for ToggleButtons, so all the buttons for a
  25482. particular group must be placed inside the same parent component.
  25483. Set the group ID back to zero if you want it to act as a normal toggle
  25484. button again.
  25485. @see getRadioGroupId
  25486. */
  25487. void setRadioGroupId (int newGroupId);
  25488. /** Returns the ID of the group to which this button belongs.
  25489. (See setRadioGroupId() for an explanation of this).
  25490. */
  25491. int getRadioGroupId() const throw() { return radioGroupId; }
  25492. /** Registers a listener to receive events when this button's state changes.
  25493. If the listener is already registered, this will not register it again.
  25494. @see removeButtonListener
  25495. */
  25496. void addButtonListener (ButtonListener* newListener);
  25497. /** Removes a previously-registered button listener
  25498. @see addButtonListener
  25499. */
  25500. void removeButtonListener (ButtonListener* listener);
  25501. /** Causes the button to act as if it's been clicked.
  25502. This will asynchronously make the button draw itself going down and up, and
  25503. will then call back the clicked() method as if mouse was clicked on it.
  25504. @see clicked
  25505. */
  25506. virtual void triggerClick();
  25507. /** Sets a command ID for this button to automatically invoke when it's clicked.
  25508. When the button is pressed, it will use the given manager to trigger the
  25509. command ID.
  25510. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  25511. before this button is. To disable the command triggering, call this method and
  25512. pass 0 for the parameters.
  25513. If generateTooltip is true, then the button's tooltip will be automatically
  25514. generated based on the name of this command and its current shortcut key.
  25515. @see addShortcut, getCommandID
  25516. */
  25517. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  25518. int commandID,
  25519. bool generateTooltip);
  25520. /** Returns the command ID that was set by setCommandToTrigger().
  25521. */
  25522. int getCommandID() const throw() { return commandID; }
  25523. /** Assigns a shortcut key to trigger the button.
  25524. The button registers itself with its top-level parent component for keypresses.
  25525. Note that a different way of linking buttons to keypresses is by using the
  25526. setCommandToTrigger() method to invoke a command.
  25527. @see clearShortcuts
  25528. */
  25529. void addShortcut (const KeyPress& key);
  25530. /** Removes all key shortcuts that had been set for this button.
  25531. @see addShortcut
  25532. */
  25533. void clearShortcuts();
  25534. /** Returns true if the given keypress is a shortcut for this button.
  25535. @see addShortcut
  25536. */
  25537. bool isRegisteredForShortcut (const KeyPress& key) const;
  25538. /** Sets an auto-repeat speed for the button when it is held down.
  25539. (Auto-repeat is disabled by default).
  25540. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  25541. triggering the next click. If this is zero, auto-repeat
  25542. is disabled
  25543. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  25544. triggered
  25545. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  25546. get faster, the longer the button is held down, up to the
  25547. minimum interval specified here
  25548. */
  25549. void setRepeatSpeed (int initialDelayInMillisecs,
  25550. int repeatDelayInMillisecs,
  25551. int minimumDelayInMillisecs = -1) throw();
  25552. /** Sets whether the button click should happen when the mouse is pressed or released.
  25553. By default the button is only considered to have been clicked when the mouse is
  25554. released, but setting this to true will make it call the clicked() method as soon
  25555. as the button is pressed.
  25556. This is useful if the button is being used to show a pop-up menu, as it allows
  25557. the click to be used as a drag onto the menu.
  25558. */
  25559. void setTriggeredOnMouseDown (bool isTriggeredOnMouseDown) throw();
  25560. /** Returns the number of milliseconds since the last time the button
  25561. went into the 'down' state.
  25562. */
  25563. uint32 getMillisecondsSinceButtonDown() const throw();
  25564. /** (overridden from Component to do special stuff). */
  25565. void setVisible (bool shouldBeVisible);
  25566. /** Sets the tooltip for this button.
  25567. @see TooltipClient, TooltipWindow
  25568. */
  25569. void setTooltip (const String& newTooltip);
  25570. // (implementation of the TooltipClient method)
  25571. const String getTooltip();
  25572. /** A combination of these flags are used by setConnectedEdges().
  25573. */
  25574. enum ConnectedEdgeFlags
  25575. {
  25576. ConnectedOnLeft = 1,
  25577. ConnectedOnRight = 2,
  25578. ConnectedOnTop = 4,
  25579. ConnectedOnBottom = 8
  25580. };
  25581. /** Hints about which edges of the button might be connected to adjoining buttons.
  25582. The value passed in is a bitwise combination of any of the values in the
  25583. ConnectedEdgeFlags enum.
  25584. E.g. if you are placing two buttons adjacent to each other, you could use this to
  25585. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  25586. without rounded corners on the edges that connect. It's only a hint, so the
  25587. LookAndFeel can choose to ignore it if it's not relevent for this type of
  25588. button.
  25589. */
  25590. void setConnectedEdges (int connectedEdgeFlags);
  25591. /** Returns the set of flags passed into setConnectedEdges(). */
  25592. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  25593. /** Indicates whether the button adjoins another one on its left edge.
  25594. @see setConnectedEdges
  25595. */
  25596. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  25597. /** Indicates whether the button adjoins another one on its right edge.
  25598. @see setConnectedEdges
  25599. */
  25600. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  25601. /** Indicates whether the button adjoins another one on its top edge.
  25602. @see setConnectedEdges
  25603. */
  25604. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  25605. /** Indicates whether the button adjoins another one on its bottom edge.
  25606. @see setConnectedEdges
  25607. */
  25608. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  25609. /** Used by setState(). */
  25610. enum ButtonState
  25611. {
  25612. buttonNormal,
  25613. buttonOver,
  25614. buttonDown
  25615. };
  25616. /** Can be used to force the button into a particular state.
  25617. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  25618. from happening.
  25619. The state that you set here will only last until it is automatically changed when the mouse
  25620. enters or exits the button, or the mouse-button is pressed or released.
  25621. */
  25622. void setState (const ButtonState newState);
  25623. juce_UseDebuggingNewOperator
  25624. protected:
  25625. /** This method is called when the button has been clicked.
  25626. Subclasses can override this to perform whatever they actions they need
  25627. to do.
  25628. Alternatively, a ButtonListener can be added to the button, and these listeners
  25629. will be called when the click occurs.
  25630. @see triggerClick
  25631. */
  25632. virtual void clicked();
  25633. /** This method is called when the button has been clicked.
  25634. By default it just calls clicked(), but you might want to override it to handle
  25635. things like clicking when a modifier key is pressed, etc.
  25636. @see ModifierKeys
  25637. */
  25638. virtual void clicked (const ModifierKeys& modifiers);
  25639. /** Subclasses should override this to actually paint the button's contents.
  25640. It's better to use this than the paint method, because it gives you information
  25641. about the over/down state of the button.
  25642. @param g the graphics context to use
  25643. @param isMouseOverButton true if the button is either in the 'over' or
  25644. 'down' state
  25645. @param isButtonDown true if the button should be drawn in the 'down' position
  25646. */
  25647. virtual void paintButton (Graphics& g,
  25648. bool isMouseOverButton,
  25649. bool isButtonDown) = 0;
  25650. /** Called when the button's up/down/over state changes.
  25651. Subclasses can override this if they need to do something special when the button
  25652. goes up or down.
  25653. @see isDown, isOver
  25654. */
  25655. virtual void buttonStateChanged();
  25656. /** @internal */
  25657. virtual void internalClickCallback (const ModifierKeys& modifiers);
  25658. /** @internal */
  25659. void handleCommandMessage (int commandId);
  25660. /** @internal */
  25661. void mouseEnter (const MouseEvent& e);
  25662. /** @internal */
  25663. void mouseExit (const MouseEvent& e);
  25664. /** @internal */
  25665. void mouseDown (const MouseEvent& e);
  25666. /** @internal */
  25667. void mouseDrag (const MouseEvent& e);
  25668. /** @internal */
  25669. void mouseUp (const MouseEvent& e);
  25670. /** @internal */
  25671. bool keyPressed (const KeyPress& key);
  25672. /** @internal */
  25673. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  25674. /** @internal */
  25675. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  25676. /** @internal */
  25677. void paint (Graphics& g);
  25678. /** @internal */
  25679. void parentHierarchyChanged();
  25680. /** @internal */
  25681. void focusGained (FocusChangeType cause);
  25682. /** @internal */
  25683. void focusLost (FocusChangeType cause);
  25684. /** @internal */
  25685. void enablementChanged();
  25686. /** @internal */
  25687. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  25688. /** @internal */
  25689. void applicationCommandListChanged();
  25690. /** @internal */
  25691. void valueChanged (Value& value);
  25692. private:
  25693. Array <KeyPress> shortcuts;
  25694. Component::SafePointer<Component> keySource;
  25695. String text;
  25696. ListenerList <ButtonListener> buttonListeners;
  25697. class RepeatTimer;
  25698. friend class RepeatTimer;
  25699. friend class ScopedPointer <RepeatTimer>;
  25700. ScopedPointer <RepeatTimer> repeatTimer;
  25701. uint32 buttonPressTime, lastTimeCallbackTime;
  25702. ApplicationCommandManager* commandManagerToUse;
  25703. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  25704. int radioGroupId, commandID, connectedEdgeFlags;
  25705. ButtonState buttonState;
  25706. Value isOn;
  25707. bool lastToggleState : 1;
  25708. bool clickTogglesState : 1;
  25709. bool needsToRelease : 1;
  25710. bool needsRepainting : 1;
  25711. bool isKeyDown : 1;
  25712. bool triggerOnMouseDown : 1;
  25713. bool generateTooltip : 1;
  25714. void repeatTimerCallback();
  25715. RepeatTimer& getRepeatTimer();
  25716. ButtonState updateState (const MouseEvent* const e);
  25717. bool isShortcutPressed() const;
  25718. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  25719. void flashButtonState();
  25720. void sendClickMessage (const ModifierKeys& modifiers);
  25721. void sendStateMessage();
  25722. Button (const Button&);
  25723. Button& operator= (const Button&);
  25724. };
  25725. #endif // __JUCE_BUTTON_JUCEHEADER__
  25726. /*** End of inlined file: juce_Button.h ***/
  25727. class ScrollBar;
  25728. /**
  25729. A class for receiving events from a ScrollBar.
  25730. You can register a ScrollBarListener with a ScrollBar using the ScrollBar::addListener()
  25731. method, and it will be called when the bar's position changes.
  25732. @see ScrollBar::addListener, ScrollBar::removeListener
  25733. */
  25734. class JUCE_API ScrollBarListener
  25735. {
  25736. public:
  25737. /** Destructor. */
  25738. virtual ~ScrollBarListener() {}
  25739. /** Called when a ScrollBar is moved.
  25740. @param scrollBarThatHasMoved the bar that has moved
  25741. @param newRangeStart the new range start of this bar
  25742. */
  25743. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  25744. double newRangeStart) = 0;
  25745. };
  25746. /**
  25747. A scrollbar component.
  25748. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  25749. sets the range of values it can represent. Then you can use setCurrentRange() to
  25750. change the position and size of the scrollbar's 'thumb'.
  25751. Registering a ScrollBarListener with the scrollbar will allow you to find out when
  25752. the user moves it, and you can use the getCurrentRangeStart() to find out where
  25753. they moved it to.
  25754. The scrollbar will adjust its own visibility according to whether its thumb size
  25755. allows it to actually be scrolled.
  25756. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  25757. instead of handling a scrollbar directly.
  25758. @see ScrollBarListener
  25759. */
  25760. class JUCE_API ScrollBar : public Component,
  25761. public AsyncUpdater,
  25762. private Timer
  25763. {
  25764. public:
  25765. /** Creates a Scrollbar.
  25766. @param isVertical whether it should be a vertical or horizontal bar
  25767. @param buttonsAreVisible whether to show the up/down or left/right buttons
  25768. */
  25769. ScrollBar (bool isVertical,
  25770. bool buttonsAreVisible = true);
  25771. /** Destructor. */
  25772. ~ScrollBar();
  25773. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  25774. bool isVertical() const throw() { return vertical; }
  25775. /** Changes the scrollbar's direction.
  25776. You'll also need to resize the bar appropriately - this just changes its internal
  25777. layout.
  25778. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  25779. */
  25780. void setOrientation (bool shouldBeVertical);
  25781. /** Shows or hides the scrollbar's buttons. */
  25782. void setButtonVisibility (bool buttonsAreVisible);
  25783. /** Tells the scrollbar whether to make itself invisible when not needed.
  25784. The default behaviour is for a scrollbar to become invisible when the thumb
  25785. fills the whole of its range (i.e. when it can't be moved). Setting this
  25786. value to false forces the bar to always be visible.
  25787. @see autoHides()
  25788. */
  25789. void setAutoHide (bool shouldHideWhenFullRange);
  25790. /** Returns true if this scrollbar is set to auto-hide when its thumb is as big
  25791. as its maximum range.
  25792. @see setAutoHide
  25793. */
  25794. bool autoHides() const throw();
  25795. /** Sets the minimum and maximum values that the bar will move between.
  25796. The bar's thumb will always be constrained so that the entire thumb lies
  25797. within this range.
  25798. @see setCurrentRange
  25799. */
  25800. void setRangeLimits (const Range<double>& newRangeLimit);
  25801. /** Sets the minimum and maximum values that the bar will move between.
  25802. The bar's thumb will always be constrained so that the entire thumb lies
  25803. within this range.
  25804. @see setCurrentRange
  25805. */
  25806. void setRangeLimits (double minimum, double maximum);
  25807. /** Returns the current limits on the thumb position.
  25808. @see setRangeLimits
  25809. */
  25810. const Range<double> getRangeLimit() const throw() { return totalRange; }
  25811. /** Returns the lower value that the thumb can be set to.
  25812. This is the value set by setRangeLimits().
  25813. */
  25814. double getMinimumRangeLimit() const throw() { return totalRange.getStart(); }
  25815. /** Returns the upper value that the thumb can be set to.
  25816. This is the value set by setRangeLimits().
  25817. */
  25818. double getMaximumRangeLimit() const throw() { return totalRange.getEnd(); }
  25819. /** Changes the position of the scrollbar's 'thumb'.
  25820. If this method call actually changes the scrollbar's position, it will trigger an
  25821. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  25822. are registered.
  25823. @see getCurrentRange. setCurrentRangeStart
  25824. */
  25825. void setCurrentRange (const Range<double>& newRange);
  25826. /** Changes the position of the scrollbar's 'thumb'.
  25827. This sets both the position and size of the thumb - to just set the position without
  25828. changing the size, you can use setCurrentRangeStart().
  25829. If this method call actually changes the scrollbar's position, it will trigger an
  25830. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  25831. are registered.
  25832. @param newStart the top (or left) of the thumb, in the range
  25833. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  25834. value is beyond these limits, it will be clipped.
  25835. @param newSize the size of the thumb, such that
  25836. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  25837. size is beyond these limits, it will be clipped.
  25838. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  25839. */
  25840. void setCurrentRange (double newStart, double newSize);
  25841. /** Moves the bar's thumb position.
  25842. This will move the thumb position without changing the thumb size. Note
  25843. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  25844. If this method call actually changes the scrollbar's position, it will trigger an
  25845. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  25846. are registered.
  25847. @see setCurrentRange
  25848. */
  25849. void setCurrentRangeStart (double newStart);
  25850. /** Returns the current thumb range.
  25851. @see getCurrentRange, setCurrentRange
  25852. */
  25853. const Range<double> getCurrentRange() const throw() { return visibleRange; }
  25854. /** Returns the position of the top of the thumb.
  25855. @see getCurrentRange, setCurrentRangeStart
  25856. */
  25857. double getCurrentRangeStart() const throw() { return visibleRange.getStart(); }
  25858. /** Returns the current size of the thumb.
  25859. @see getCurrentRange, setCurrentRange
  25860. */
  25861. double getCurrentRangeSize() const throw() { return visibleRange.getLength(); }
  25862. /** Sets the amount by which the up and down buttons will move the bar.
  25863. The value here is in terms of the total range, and is added or subtracted
  25864. from the thumb position when the user clicks an up/down (or left/right) button.
  25865. */
  25866. void setSingleStepSize (double newSingleStepSize);
  25867. /** Moves the scrollbar by a number of single-steps.
  25868. This will move the bar by a multiple of its single-step interval (as
  25869. specified using the setSingleStepSize() method).
  25870. A positive value here will move the bar down or to the right, a negative
  25871. value moves it up or to the left.
  25872. */
  25873. void moveScrollbarInSteps (int howManySteps);
  25874. /** Moves the scroll bar up or down in pages.
  25875. This will move the bar by a multiple of its current thumb size, effectively
  25876. doing a page-up or down.
  25877. A positive value here will move the bar down or to the right, a negative
  25878. value moves it up or to the left.
  25879. */
  25880. void moveScrollbarInPages (int howManyPages);
  25881. /** Scrolls to the top (or left).
  25882. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  25883. */
  25884. void scrollToTop();
  25885. /** Scrolls to the bottom (or right).
  25886. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  25887. */
  25888. void scrollToBottom();
  25889. /** Changes the delay before the up and down buttons autorepeat when they are held
  25890. down.
  25891. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  25892. @see Button::setRepeatSpeed
  25893. */
  25894. void setButtonRepeatSpeed (int initialDelayInMillisecs,
  25895. int repeatDelayInMillisecs,
  25896. int minimumDelayInMillisecs = -1);
  25897. /** A set of colour IDs to use to change the colour of various aspects of the component.
  25898. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25899. methods.
  25900. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25901. */
  25902. enum ColourIds
  25903. {
  25904. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  25905. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  25906. 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. */
  25907. };
  25908. /** Registers a listener that will be called when the scrollbar is moved. */
  25909. void addListener (ScrollBarListener* listener);
  25910. /** Deregisters a previously-registered listener. */
  25911. void removeListener (ScrollBarListener* listener);
  25912. /** @internal */
  25913. bool keyPressed (const KeyPress& key);
  25914. /** @internal */
  25915. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  25916. /** @internal */
  25917. void lookAndFeelChanged();
  25918. /** @internal */
  25919. void handleAsyncUpdate();
  25920. /** @internal */
  25921. void mouseDown (const MouseEvent& e);
  25922. /** @internal */
  25923. void mouseDrag (const MouseEvent& e);
  25924. /** @internal */
  25925. void mouseUp (const MouseEvent& e);
  25926. /** @internal */
  25927. void paint (Graphics& g);
  25928. /** @internal */
  25929. void resized();
  25930. juce_UseDebuggingNewOperator
  25931. private:
  25932. Range <double> totalRange, visibleRange;
  25933. double singleStepSize, dragStartRange;
  25934. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  25935. int dragStartMousePos, lastMousePos;
  25936. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  25937. bool vertical, isDraggingThumb, autohides;
  25938. class ScrollbarButton;
  25939. friend class ScopedPointer<ScrollbarButton>;
  25940. ScopedPointer<ScrollbarButton> upButton, downButton;
  25941. ListenerList <ScrollBarListener> listeners;
  25942. void updateThumbPosition();
  25943. void timerCallback();
  25944. ScrollBar (const ScrollBar&);
  25945. ScrollBar& operator= (const ScrollBar&);
  25946. };
  25947. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  25948. /*** End of inlined file: juce_ScrollBar.h ***/
  25949. /**
  25950. A Viewport is used to contain a larger child component, and allows the child
  25951. to be automatically scrolled around.
  25952. To use a Viewport, just create one and set the component that goes inside it
  25953. using the setViewedComponent() method. When the child component changes size,
  25954. the Viewport will adjust its scrollbars accordingly.
  25955. A subclass of the viewport can be created which will receive calls to its
  25956. visibleAreaChanged() method when the subcomponent changes position or size.
  25957. */
  25958. class JUCE_API Viewport : public Component,
  25959. private ComponentListener,
  25960. private ScrollBarListener
  25961. {
  25962. public:
  25963. /** Creates a Viewport.
  25964. The viewport is initially empty - use the setViewedComponent() method to
  25965. add a child component for it to manage.
  25966. */
  25967. explicit Viewport (const String& componentName = String::empty);
  25968. /** Destructor. */
  25969. ~Viewport();
  25970. /** Sets the component that this viewport will contain and scroll around.
  25971. This will add the given component to this Viewport and position it at
  25972. (0, 0).
  25973. (Don't add or remove any child components directly using the normal
  25974. Component::addChildComponent() methods).
  25975. @param newViewedComponent the component to add to this viewport (this pointer
  25976. may be null). The component passed in will be deleted
  25977. by the Viewport when it's no longer needed
  25978. @see getViewedComponent
  25979. */
  25980. void setViewedComponent (Component* newViewedComponent);
  25981. /** Returns the component that's currently being used inside the Viewport.
  25982. @see setViewedComponent
  25983. */
  25984. Component* getViewedComponent() const throw() { return contentComp; }
  25985. /** Changes the position of the viewed component.
  25986. The inner component will be moved so that the pixel at the top left of
  25987. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  25988. within the inner component.
  25989. This will update the scrollbars and might cause a call to visibleAreaChanged().
  25990. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  25991. */
  25992. void setViewPosition (int xPixelsOffset, int yPixelsOffset);
  25993. /** Changes the view position as a proportion of the distance it can move.
  25994. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  25995. visible area in the top-left, and (1, 1) would put it as far down and
  25996. to the right as it's possible to go whilst keeping the child component
  25997. on-screen.
  25998. */
  25999. void setViewPositionProportionately (double proportionX, double proportionY);
  26000. /** If the specified position is at the edges of the viewport, this method scrolls
  26001. the viewport to bring that position nearer to the centre.
  26002. Call this if you're dragging an object inside a viewport and want to make it scroll
  26003. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  26004. useful when auto-scrolling.
  26005. @param mouseX the x position, relative to the Viewport's top-left
  26006. @param mouseY the y position, relative to the Viewport's top-left
  26007. @param distanceFromEdge specifies how close to an edge the position needs to be
  26008. before the viewport should scroll in that direction
  26009. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  26010. to scroll by.
  26011. @returns true if the viewport was scrolled
  26012. */
  26013. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  26014. /** Returns the position within the child component of the top-left of its visible area.
  26015. */
  26016. const Point<int> getViewPosition() const throw() { return lastVisibleArea.getPosition(); }
  26017. /** Returns the position within the child component of the top-left of its visible area.
  26018. @see getViewWidth, setViewPosition
  26019. */
  26020. int getViewPositionX() const throw() { return lastVisibleArea.getX(); }
  26021. /** Returns the position within the child component of the top-left of its visible area.
  26022. @see getViewHeight, setViewPosition
  26023. */
  26024. int getViewPositionY() const throw() { return lastVisibleArea.getY(); }
  26025. /** Returns the width of the visible area of the child component.
  26026. This may be less than the width of this Viewport if there's a vertical scrollbar
  26027. or if the child component is itself smaller.
  26028. */
  26029. int getViewWidth() const throw() { return lastVisibleArea.getWidth(); }
  26030. /** Returns the height of the visible area of the child component.
  26031. This may be less than the height of this Viewport if there's a horizontal scrollbar
  26032. or if the child component is itself smaller.
  26033. */
  26034. int getViewHeight() const throw() { return lastVisibleArea.getHeight(); }
  26035. /** Returns the width available within this component for the contents.
  26036. This will be the width of the viewport component minus the width of a
  26037. vertical scrollbar (if visible).
  26038. */
  26039. int getMaximumVisibleWidth() const;
  26040. /** Returns the height available within this component for the contents.
  26041. This will be the height of the viewport component minus the space taken up
  26042. by a horizontal scrollbar (if visible).
  26043. */
  26044. int getMaximumVisibleHeight() const;
  26045. /** Callback method that is called when the visible area changes.
  26046. This will be called when the visible area is moved either be scrolling or
  26047. by calls to setViewPosition(), etc.
  26048. */
  26049. virtual void visibleAreaChanged (int visibleX, int visibleY,
  26050. int visibleW, int visibleH);
  26051. /** Turns scrollbars on or off.
  26052. If set to false, the scrollbars won't ever appear. When true (the default)
  26053. they will appear only when needed.
  26054. */
  26055. void setScrollBarsShown (bool showVerticalScrollbarIfNeeded,
  26056. bool showHorizontalScrollbarIfNeeded);
  26057. /** True if the vertical scrollbar is enabled.
  26058. @see setScrollBarsShown
  26059. */
  26060. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  26061. /** True if the horizontal scrollbar is enabled.
  26062. @see setScrollBarsShown
  26063. */
  26064. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  26065. /** Changes the width of the scrollbars.
  26066. If this isn't specified, the default width from the LookAndFeel class will be used.
  26067. @see LookAndFeel::getDefaultScrollbarWidth
  26068. */
  26069. void setScrollBarThickness (int thickness);
  26070. /** Returns the thickness of the scrollbars.
  26071. @see setScrollBarThickness
  26072. */
  26073. int getScrollBarThickness() const;
  26074. /** Changes the distance that a single-step click on a scrollbar button
  26075. will move the viewport.
  26076. */
  26077. void setSingleStepSizes (int stepX, int stepY);
  26078. /** Shows or hides the buttons on any scrollbars that are used.
  26079. @see ScrollBar::setButtonVisibility
  26080. */
  26081. void setScrollBarButtonVisibility (bool buttonsVisible);
  26082. /** Returns a pointer to the scrollbar component being used.
  26083. Handy if you need to customise the bar somehow.
  26084. */
  26085. ScrollBar* getVerticalScrollBar() throw() { return &verticalScrollBar; }
  26086. /** Returns a pointer to the scrollbar component being used.
  26087. Handy if you need to customise the bar somehow.
  26088. */
  26089. ScrollBar* getHorizontalScrollBar() throw() { return &horizontalScrollBar; }
  26090. juce_UseDebuggingNewOperator
  26091. /** @internal */
  26092. void resized();
  26093. /** @internal */
  26094. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  26095. /** @internal */
  26096. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26097. /** @internal */
  26098. bool keyPressed (const KeyPress& key);
  26099. /** @internal */
  26100. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  26101. /** @internal */
  26102. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26103. private:
  26104. Component::SafePointer<Component> contentComp;
  26105. Rectangle<int> lastVisibleArea;
  26106. int scrollBarThickness;
  26107. int singleStepX, singleStepY;
  26108. bool showHScrollbar, showVScrollbar;
  26109. Component contentHolder;
  26110. ScrollBar verticalScrollBar;
  26111. ScrollBar horizontalScrollBar;
  26112. void updateVisibleArea();
  26113. Viewport (const Viewport&);
  26114. Viewport& operator= (const Viewport&);
  26115. };
  26116. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  26117. /*** End of inlined file: juce_Viewport.h ***/
  26118. /*** Start of inlined file: juce_PopupMenu.h ***/
  26119. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  26120. #define __JUCE_POPUPMENU_JUCEHEADER__
  26121. class PopupMenuCustomComponent;
  26122. /** Creates and displays a popup-menu.
  26123. To show a popup-menu, you create one of these, add some items to it, then
  26124. call its show() method, which returns the id of the item the user selects.
  26125. E.g. @code
  26126. void MyWidget::mouseDown (const MouseEvent& e)
  26127. {
  26128. PopupMenu m;
  26129. m.addItem (1, "item 1");
  26130. m.addItem (2, "item 2");
  26131. const int result = m.show();
  26132. if (result == 0)
  26133. {
  26134. // user dismissed the menu without picking anything
  26135. }
  26136. else if (result == 1)
  26137. {
  26138. // user picked item 1
  26139. }
  26140. else if (result == 2)
  26141. {
  26142. // user picked item 2
  26143. }
  26144. }
  26145. @endcode
  26146. Submenus are easy too: @code
  26147. void MyWidget::mouseDown (const MouseEvent& e)
  26148. {
  26149. PopupMenu subMenu;
  26150. subMenu.addItem (1, "item 1");
  26151. subMenu.addItem (2, "item 2");
  26152. PopupMenu mainMenu;
  26153. mainMenu.addItem (3, "item 3");
  26154. mainMenu.addSubMenu ("other choices", subMenu);
  26155. const int result = m.show();
  26156. ...etc
  26157. }
  26158. @endcode
  26159. */
  26160. class JUCE_API PopupMenu
  26161. {
  26162. public:
  26163. /** Creates an empty popup menu. */
  26164. PopupMenu();
  26165. /** Creates a copy of another menu. */
  26166. PopupMenu (const PopupMenu& other);
  26167. /** Destructor. */
  26168. ~PopupMenu();
  26169. /** Copies this menu from another one. */
  26170. PopupMenu& operator= (const PopupMenu& other);
  26171. /** Resets the menu, removing all its items. */
  26172. void clear();
  26173. /** Appends a new text item for this menu to show.
  26174. @param itemResultId the number that will be returned from the show() method
  26175. if the user picks this item. The value should never be
  26176. zero, because that's used to indicate that the user didn't
  26177. select anything.
  26178. @param itemText the text to show.
  26179. @param isActive if false, the item will be shown 'greyed-out' and can't be
  26180. picked
  26181. @param isTicked if true, the item will be shown with a tick next to it
  26182. @param iconToUse if this is non-zero, it should be an image that will be
  26183. displayed to the left of the item. This method will take its
  26184. own copy of the image passed-in, so there's no need to keep
  26185. it hanging around.
  26186. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  26187. */
  26188. void addItem (int itemResultId,
  26189. const String& itemText,
  26190. bool isActive = true,
  26191. bool isTicked = false,
  26192. const Image& iconToUse = Image());
  26193. /** Adds an item that represents one of the commands in a command manager object.
  26194. @param commandManager the manager to use to trigger the command and get information
  26195. about it
  26196. @param commandID the ID of the command
  26197. @param displayName if this is non-empty, then this string will be used instead of
  26198. the command's registered name
  26199. */
  26200. void addCommandItem (ApplicationCommandManager* commandManager,
  26201. int commandID,
  26202. const String& displayName = String::empty);
  26203. /** Appends a text item with a special colour.
  26204. This is the same as addItem(), but specifies a colour to use for the
  26205. text, which will override the default colours that are used by the
  26206. current look-and-feel. See addItem() for a description of the parameters.
  26207. */
  26208. void addColouredItem (int itemResultId,
  26209. const String& itemText,
  26210. const Colour& itemTextColour,
  26211. bool isActive = true,
  26212. bool isTicked = false,
  26213. const Image& iconToUse = Image());
  26214. /** Appends a custom menu item.
  26215. This will add a user-defined component to use as a menu item. The component
  26216. passed in will be deleted by this menu when it's no longer needed.
  26217. @see PopupMenuCustomComponent
  26218. */
  26219. void addCustomItem (int itemResultId, PopupMenuCustomComponent* customComponent);
  26220. /** Appends a custom menu item that can't be used to trigger a result.
  26221. This will add a user-defined component to use as a menu item. Unlike the
  26222. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  26223. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  26224. delete the component when it's finished, so it's the caller's responsibility
  26225. to manage the component that is passed-in.
  26226. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  26227. detection of a mouse-click on your component, and use that to trigger the
  26228. menu ID specified in itemResultId. If this is false, the menu item can't
  26229. be triggered, so itemResultId is not used.
  26230. @see PopupMenuCustomComponent
  26231. */
  26232. void addCustomItem (int itemResultId,
  26233. Component* customComponent,
  26234. int idealWidth, int idealHeight,
  26235. bool triggerMenuItemAutomaticallyWhenClicked);
  26236. /** Appends a sub-menu.
  26237. If the menu that's passed in is empty, it will appear as an inactive item.
  26238. */
  26239. void addSubMenu (const String& subMenuName,
  26240. const PopupMenu& subMenu,
  26241. bool isActive = true,
  26242. const Image& iconToUse = Image(),
  26243. bool isTicked = false);
  26244. /** Appends a separator to the menu, to help break it up into sections.
  26245. The menu class is smart enough not to display separators at the top or bottom
  26246. of the menu, and it will replace mutliple adjacent separators with a single
  26247. one, so your code can be quite free and easy about adding these, and it'll
  26248. always look ok.
  26249. */
  26250. void addSeparator();
  26251. /** Adds a non-clickable text item to the menu.
  26252. This is a bold-font items which can be used as a header to separate the items
  26253. into named groups.
  26254. */
  26255. void addSectionHeader (const String& title);
  26256. /** Returns the number of items that the menu currently contains.
  26257. (This doesn't count separators).
  26258. */
  26259. int getNumItems() const throw();
  26260. /** Returns true if the menu contains a command item that triggers the given command. */
  26261. bool containsCommandItem (int commandID) const;
  26262. /** Returns true if the menu contains any items that can be used. */
  26263. bool containsAnyActiveItems() const throw();
  26264. /** Displays the menu and waits for the user to pick something.
  26265. This will display the menu modally, and return the ID of the item that the
  26266. user picks. If they click somewhere off the menu to get rid of it without
  26267. choosing anything, this will return 0.
  26268. The current location of the mouse will be used as the position to show the
  26269. menu - to explicitly set the menu's position, use showAt() instead. Depending
  26270. on where this point is on the screen, the menu will appear above, below or
  26271. to the side of the point.
  26272. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  26273. then when the menu first appears, it will make sure
  26274. that this item is visible. So if the menu has too many
  26275. items to fit on the screen, it will be scrolled to a
  26276. position where this item is visible.
  26277. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  26278. than this if some items are too long to fit.
  26279. @param maximumNumColumns if there are too many items to fit on-screen in a single
  26280. vertical column, the menu may be laid out as a series of
  26281. columns - this is the maximum number allowed. To use the
  26282. default value for this (probably about 7), you can pass
  26283. in zero.
  26284. @param standardItemHeight if this is non-zero, it will be used as the standard
  26285. height for menu items (apart from custom items)
  26286. @see showAt
  26287. */
  26288. int show (int itemIdThatMustBeVisible = 0,
  26289. int minimumWidth = 0,
  26290. int maximumNumColumns = 0,
  26291. int standardItemHeight = 0);
  26292. /** Displays the menu at a specific location.
  26293. This is the same as show(), but uses a specific location (in global screen
  26294. co-ordinates) rather than the current mouse position.
  26295. Note that the co-ordinates don't specify the top-left of the menu - they
  26296. indicate a point of interest, and the menu will position itself nearby to
  26297. this point, trying to keep it fully on-screen.
  26298. @see show()
  26299. */
  26300. int showAt (int screenX,
  26301. int screenY,
  26302. int itemIdThatMustBeVisible = 0,
  26303. int minimumWidth = 0,
  26304. int maximumNumColumns = 0,
  26305. int standardItemHeight = 0);
  26306. /** Displays the menu as if it's attached to a component such as a button.
  26307. This is similar to showAt(), but will position it next to the given component, e.g.
  26308. so that the menu's edge is aligned with that of the component. This is intended for
  26309. things like buttons that trigger a pop-up menu.
  26310. */
  26311. int showAt (Component* componentToAttachTo,
  26312. int itemIdThatMustBeVisible = 0,
  26313. int minimumWidth = 0,
  26314. int maximumNumColumns = 0,
  26315. int standardItemHeight = 0);
  26316. /** Closes any menus that are currently open.
  26317. This might be useful if you have a situation where your window is being closed
  26318. by some means other than a user action, and you'd like to make sure that menus
  26319. aren't left hanging around.
  26320. */
  26321. static void JUCE_CALLTYPE dismissAllActiveMenus();
  26322. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  26323. This can be called before show() if you need a customised menu. Be careful
  26324. not to delete the LookAndFeel object before the menu has been deleted.
  26325. */
  26326. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  26327. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  26328. These constants can be used either via the LookAndFeel::setColour()
  26329. method for the look and feel that is set for this menu with setLookAndFeel()
  26330. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  26331. */
  26332. enum ColourIds
  26333. {
  26334. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  26335. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  26336. colour is specified when the item is added). */
  26337. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  26338. addSectionHeader() method). */
  26339. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  26340. highlighted menu item. */
  26341. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  26342. highlighted item. */
  26343. };
  26344. /**
  26345. Allows you to iterate through the items in a pop-up menu, and examine
  26346. their properties.
  26347. To use this, just create one and repeatedly call its next() method. When this
  26348. returns true, all the member variables of the iterator are filled-out with
  26349. information describing the menu item. When it returns false, the end of the
  26350. list has been reached.
  26351. */
  26352. class JUCE_API MenuItemIterator
  26353. {
  26354. public:
  26355. /** Creates an iterator that will scan through the items in the specified
  26356. menu.
  26357. Be careful not to add any items to a menu while it is being iterated,
  26358. or things could get out of step.
  26359. */
  26360. MenuItemIterator (const PopupMenu& menu);
  26361. /** Destructor. */
  26362. ~MenuItemIterator();
  26363. /** Returns true if there is another item, and sets up all this object's
  26364. member variables to reflect that item's properties.
  26365. */
  26366. bool next();
  26367. String itemName;
  26368. const PopupMenu* subMenu;
  26369. int itemId;
  26370. bool isSeparator;
  26371. bool isTicked;
  26372. bool isEnabled;
  26373. bool isCustomComponent;
  26374. bool isSectionHeader;
  26375. const Colour* customColour;
  26376. Image customImage;
  26377. ApplicationCommandManager* commandManager;
  26378. juce_UseDebuggingNewOperator
  26379. private:
  26380. const PopupMenu& menu;
  26381. int index;
  26382. MenuItemIterator (const MenuItemIterator&);
  26383. MenuItemIterator& operator= (const MenuItemIterator&);
  26384. };
  26385. juce_UseDebuggingNewOperator
  26386. private:
  26387. class Item;
  26388. class ItemComponent;
  26389. class Window;
  26390. friend class MenuItemIterator;
  26391. friend class ItemComponent;
  26392. friend class Window;
  26393. friend class PopupMenuCustomComponent;
  26394. friend class OwnedArray <Item>;
  26395. friend class ScopedPointer <Window>;
  26396. OwnedArray <Item> items;
  26397. LookAndFeel* lookAndFeel;
  26398. bool separatorPending;
  26399. void addSeparatorIfPending();
  26400. int showMenu (int x, int y, int w, int h,
  26401. int itemIdThatMustBeVisible,
  26402. int minimumWidth,
  26403. int maximumNumColumns,
  26404. int standardItemHeight,
  26405. bool alignToRectangle,
  26406. Component* componentAttachedTo);
  26407. friend class MenuBarComponent;
  26408. Component* createMenuComponent (int x, int y, int w, int h,
  26409. int itemIdThatMustBeVisible,
  26410. int minimumWidth,
  26411. int maximumNumColumns,
  26412. int standardItemHeight,
  26413. bool alignToRectangle,
  26414. Component* menuBarComponent,
  26415. ApplicationCommandManager** managerOfChosenCommand,
  26416. Component* componentAttachedTo);
  26417. };
  26418. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  26419. /*** End of inlined file: juce_PopupMenu.h ***/
  26420. /*** Start of inlined file: juce_TextInputTarget.h ***/
  26421. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  26422. #define __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  26423. /** An abstract base class that is implemented by components that wish to be used
  26424. as text editors.
  26425. This class allows different types of text editor component to provide a uniform
  26426. interface, which can be used by things like OS-specific input methods, on-screen
  26427. keyboards, etc.
  26428. */
  26429. class JUCE_API TextInputTarget
  26430. {
  26431. public:
  26432. /** */
  26433. TextInputTarget() {}
  26434. /** Destructor. */
  26435. virtual ~TextInputTarget() {}
  26436. /** Returns true if this input target is currently accepting input.
  26437. For example, a text editor might return false if it's in read-only mode.
  26438. */
  26439. virtual bool isTextInputActive() const = 0;
  26440. /** Returns the extents of the selected text region, or an empty range if
  26441. nothing is selected,
  26442. */
  26443. virtual const Range<int> getHighlightedRegion() const = 0;
  26444. /** Sets the currently-selected text region.
  26445. */
  26446. virtual void setHighlightedRegion (const Range<int>& newRange) = 0;
  26447. /** Returns a specified sub-section of the text.
  26448. */
  26449. virtual const String getTextInRange (const Range<int>& range) const = 0;
  26450. /** Inserts some text, overwriting the selected text region, if there is one. */
  26451. virtual void insertTextAtCaret (const String& textToInsert) = 0;
  26452. };
  26453. #endif // __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  26454. /*** End of inlined file: juce_TextInputTarget.h ***/
  26455. class TextEditor;
  26456. /**
  26457. Receives callbacks from a TextEditor component when it changes.
  26458. @see TextEditor::addListener
  26459. */
  26460. class JUCE_API TextEditorListener
  26461. {
  26462. public:
  26463. /** Destructor. */
  26464. virtual ~TextEditorListener() {}
  26465. /** Called when the user changes the text in some way. */
  26466. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  26467. /** Called when the user presses the return key. */
  26468. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  26469. /** Called when the user presses the escape key. */
  26470. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  26471. /** Called when the text editor loses focus. */
  26472. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  26473. };
  26474. /**
  26475. A component containing text that can be edited.
  26476. A TextEditor can either be in single- or multi-line mode, and supports mixed
  26477. fonts and colours.
  26478. @see TextEditorListener, Label
  26479. */
  26480. class JUCE_API TextEditor : public Component,
  26481. public TextInputTarget,
  26482. public SettableTooltipClient
  26483. {
  26484. public:
  26485. /** Creates a new, empty text editor.
  26486. @param componentName the name to pass to the component for it to use as its name
  26487. @param passwordCharacter if this is not zero, this character will be used as a replacement
  26488. for all characters that are drawn on screen - e.g. to create
  26489. a password-style textbox containing circular blobs instead of text,
  26490. you could set this value to 0x25cf, which is the unicode character
  26491. for a black splodge (not all fonts include this, though), or 0x2022,
  26492. which is a bullet (probably the best choice for linux).
  26493. */
  26494. explicit TextEditor (const String& componentName = String::empty,
  26495. juce_wchar passwordCharacter = 0);
  26496. /** Destructor. */
  26497. virtual ~TextEditor();
  26498. /** Puts the editor into either multi- or single-line mode.
  26499. By default, the editor will be in single-line mode, so use this if you need a multi-line
  26500. editor.
  26501. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  26502. on if you want a multi-line editor with line-breaks.
  26503. @see isMultiLine, setReturnKeyStartsNewLine
  26504. */
  26505. void setMultiLine (bool shouldBeMultiLine,
  26506. bool shouldWordWrap = true);
  26507. /** Returns true if the editor is in multi-line mode.
  26508. */
  26509. bool isMultiLine() const;
  26510. /** Changes the behaviour of the return key.
  26511. If set to true, the return key will insert a new-line into the text; if false
  26512. it will trigger a call to the TextEditorListener::textEditorReturnKeyPressed()
  26513. method. By default this is set to false, and when true it will only insert
  26514. new-lines when in multi-line mode (see setMultiLine()).
  26515. */
  26516. void setReturnKeyStartsNewLine (bool shouldStartNewLine);
  26517. /** Returns the value set by setReturnKeyStartsNewLine().
  26518. See setReturnKeyStartsNewLine() for more info.
  26519. */
  26520. bool getReturnKeyStartsNewLine() const { return returnKeyStartsNewLine; }
  26521. /** Indicates whether the tab key should be accepted and used to input a tab character,
  26522. or whether it gets ignored.
  26523. By default the tab key is ignored, so that it can be used to switch keyboard focus
  26524. between components.
  26525. */
  26526. void setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed);
  26527. /** Returns true if the tab key is being used for input.
  26528. @see setTabKeyUsedAsCharacter
  26529. */
  26530. bool isTabKeyUsedAsCharacter() const { return tabKeyUsed; }
  26531. /** Changes the editor to read-only mode.
  26532. By default, the text editor is not read-only. If you're making it read-only, you
  26533. might also want to call setCaretVisible (false) to get rid of the caret.
  26534. The text can still be highlighted and copied when in read-only mode.
  26535. @see isReadOnly, setCaretVisible
  26536. */
  26537. void setReadOnly (bool shouldBeReadOnly);
  26538. /** Returns true if the editor is in read-only mode.
  26539. */
  26540. bool isReadOnly() const;
  26541. /** Makes the caret visible or invisible.
  26542. By default the caret is visible.
  26543. @see setCaretColour, setCaretPosition
  26544. */
  26545. void setCaretVisible (bool shouldBeVisible);
  26546. /** Returns true if the caret is enabled.
  26547. @see setCaretVisible
  26548. */
  26549. bool isCaretVisible() const { return caretVisible; }
  26550. /** Enables/disables a vertical scrollbar.
  26551. (This only applies when in multi-line mode). When the text gets too long to fit
  26552. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  26553. this is enabled, the scrollbar will be hidden unless it's needed.
  26554. By default the scrollbar is enabled.
  26555. */
  26556. void setScrollbarsShown (bool shouldBeEnabled);
  26557. /** Returns true if scrollbars are enabled.
  26558. @see setScrollbarsShown
  26559. */
  26560. bool areScrollbarsShown() const { return scrollbarVisible; }
  26561. /** Changes the password character used to disguise the text.
  26562. @param passwordCharacter if this is not zero, this character will be used as a replacement
  26563. for all characters that are drawn on screen - e.g. to create
  26564. a password-style textbox containing circular blobs instead of text,
  26565. you could set this value to 0x25cf, which is the unicode character
  26566. for a black splodge (not all fonts include this, though), or 0x2022,
  26567. which is a bullet (probably the best choice for linux).
  26568. */
  26569. void setPasswordCharacter (juce_wchar passwordCharacter);
  26570. /** Returns the current password character.
  26571. @see setPasswordCharacter
  26572. */
  26573. juce_wchar getPasswordCharacter() const { return passwordCharacter; }
  26574. /** Allows a right-click menu to appear for the editor.
  26575. (This defaults to being enabled).
  26576. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  26577. of options such as cut/copy/paste, undo/redo, etc.
  26578. */
  26579. void setPopupMenuEnabled (bool menuEnabled);
  26580. /** Returns true if the right-click menu is enabled.
  26581. @see setPopupMenuEnabled
  26582. */
  26583. bool isPopupMenuEnabled() const { return popupMenuEnabled; }
  26584. /** Returns true if a popup-menu is currently being displayed.
  26585. */
  26586. bool isPopupMenuCurrentlyActive() const { return menuActive; }
  26587. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  26588. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26589. methods.
  26590. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26591. */
  26592. enum ColourIds
  26593. {
  26594. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  26595. transparent if necessary. */
  26596. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  26597. that because the editor can contain multiple colours, calling this
  26598. method won't change the colour of existing text - to do that, call
  26599. applyFontToAllText() after calling this method.*/
  26600. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  26601. the text - this can be transparent if you don't want to show any
  26602. highlighting.*/
  26603. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  26604. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  26605. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  26606. the edge of the component. */
  26607. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  26608. the edge of the component when it has focus. */
  26609. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  26610. around the edge of the editor. */
  26611. };
  26612. /** Sets the font to use for newly added text.
  26613. This will change the font that will be used next time any text is added or entered
  26614. into the editor. It won't change the font of any existing text - to do that, use
  26615. applyFontToAllText() instead.
  26616. @see applyFontToAllText
  26617. */
  26618. void setFont (const Font& newFont);
  26619. /** Applies a font to all the text in the editor.
  26620. This will also set the current font to use for any new text that's added.
  26621. @see setFont
  26622. */
  26623. void applyFontToAllText (const Font& newFont);
  26624. /** Returns the font that's currently being used for new text.
  26625. @see setFont
  26626. */
  26627. const Font getFont() const;
  26628. /** If set to true, focusing on the editor will highlight all its text.
  26629. (Set to false by default).
  26630. This is useful for boxes where you expect the user to re-enter all the
  26631. text when they focus on the component, rather than editing what's already there.
  26632. */
  26633. void setSelectAllWhenFocused (bool b);
  26634. /** Sets limits on the characters that can be entered.
  26635. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  26636. limit is set
  26637. @param allowedCharacters if this is non-empty, then only characters that occur in
  26638. this string are allowed to be entered into the editor.
  26639. */
  26640. void setInputRestrictions (int maxTextLength,
  26641. const String& allowedCharacters = String::empty);
  26642. /** When the text editor is empty, it can be set to display a message.
  26643. This is handy for things like telling the user what to type in the box - the
  26644. string is only displayed, it's not taken to actually be the contents of
  26645. the editor.
  26646. */
  26647. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse);
  26648. /** Changes the size of the scrollbars that are used.
  26649. Handy if you need smaller scrollbars for a small text box.
  26650. */
  26651. void setScrollBarThickness (int newThicknessPixels);
  26652. /** Shows or hides the buttons on any scrollbars that are used.
  26653. @see ScrollBar::setButtonVisibility
  26654. */
  26655. void setScrollBarButtonVisibility (bool buttonsVisible);
  26656. /** Registers a listener to be told when things happen to the text.
  26657. @see removeListener
  26658. */
  26659. void addListener (TextEditorListener* newListener);
  26660. /** Deregisters a listener.
  26661. @see addListener
  26662. */
  26663. void removeListener (TextEditorListener* listenerToRemove);
  26664. /** Returns the entire contents of the editor. */
  26665. const String getText() const;
  26666. /** Returns a section of the contents of the editor. */
  26667. const String getTextInRange (const Range<int>& textRange) const;
  26668. /** Returns true if there are no characters in the editor.
  26669. This is more efficient than calling getText().isEmpty().
  26670. */
  26671. bool isEmpty() const;
  26672. /** Sets the entire content of the editor.
  26673. This will clear the editor and insert the given text (using the current text colour
  26674. and font). You can set the current text colour using
  26675. @code setColour (TextEditor::textColourId, ...);
  26676. @endcode
  26677. @param newText the text to add
  26678. @param sendTextChangeMessage if true, this will cause a change message to
  26679. be sent to all the listeners.
  26680. @see insertText
  26681. */
  26682. void setText (const String& newText,
  26683. bool sendTextChangeMessage = true);
  26684. /** Returns a Value object that can be used to get or set the text.
  26685. Bear in mind that this operate quite slowly if your text box contains large
  26686. amounts of text, as it needs to dynamically build the string that's involved. It's
  26687. best used for small text boxes.
  26688. */
  26689. Value& getTextValue();
  26690. /** Inserts some text at the current cursor position.
  26691. If a section of the text is highlighted, it will be replaced by
  26692. this string, otherwise it will be inserted.
  26693. To delete a section of text, you can use setHighlightedRegion() to
  26694. highlight it, and call insertTextAtCursor (String::empty).
  26695. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  26696. */
  26697. void insertTextAtCaret (const String& textToInsert);
  26698. /** Deletes all the text from the editor. */
  26699. void clear();
  26700. /** Deletes the currently selected region, and puts it on the clipboard.
  26701. @see copy, paste, SystemClipboard
  26702. */
  26703. void cut();
  26704. /** Copies any currently selected region to the clipboard.
  26705. @see cut, paste, SystemClipboard
  26706. */
  26707. void copy();
  26708. /** Pastes the contents of the clipboard into the editor at the cursor position.
  26709. @see cut, copy, SystemClipboard
  26710. */
  26711. void paste();
  26712. /** Moves the caret to be in front of a given character.
  26713. @see getCaretPosition
  26714. */
  26715. void setCaretPosition (int newIndex);
  26716. /** Returns the current index of the caret.
  26717. @see setCaretPosition
  26718. */
  26719. int getCaretPosition() const;
  26720. /** Attempts to scroll the text editor so that the caret ends up at
  26721. a specified position.
  26722. This won't affect the caret's position within the text, it tries to scroll
  26723. the entire editor vertically and horizontally so that the caret is sitting
  26724. at the given position (relative to the top-left of this component).
  26725. Depending on the amount of text available, it might not be possible to
  26726. scroll far enough for the caret to reach this exact position, but it
  26727. will go as far as it can in that direction.
  26728. */
  26729. void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);
  26730. /** Get the graphical position of the caret.
  26731. The rectangle returned is relative to the component's top-left corner.
  26732. @see scrollEditorToPositionCaret
  26733. */
  26734. const Rectangle<int> getCaretRectangle();
  26735. /** Selects a section of the text. */
  26736. void setHighlightedRegion (const Range<int>& newSelection);
  26737. /** Returns the range of characters that are selected.
  26738. If nothing is selected, this will return an empty range.
  26739. @see setHighlightedRegion
  26740. */
  26741. const Range<int> getHighlightedRegion() const { return selection; }
  26742. /** Returns the section of text that is currently selected. */
  26743. const String getHighlightedText() const;
  26744. /** Finds the index of the character at a given position.
  26745. The co-ordinates are relative to the component's top-left.
  26746. */
  26747. int getTextIndexAt (int x, int y);
  26748. /** Counts the number of characters in the text.
  26749. This is quicker than getting the text as a string if you just need to know
  26750. the length.
  26751. */
  26752. int getTotalNumChars() const;
  26753. /** Returns the total width of the text, as it is currently laid-out.
  26754. This may be larger than the size of the TextEditor, and can change when
  26755. the TextEditor is resized or the text changes.
  26756. */
  26757. int getTextWidth() const;
  26758. /** Returns the maximum height of the text, as it is currently laid-out.
  26759. This may be larger than the size of the TextEditor, and can change when
  26760. the TextEditor is resized or the text changes.
  26761. */
  26762. int getTextHeight() const;
  26763. /** Changes the size of the gap at the top and left-edge of the editor.
  26764. By default there's a gap of 4 pixels.
  26765. */
  26766. void setIndents (int newLeftIndent, int newTopIndent);
  26767. /** Changes the size of border left around the edge of the component.
  26768. @see getBorder
  26769. */
  26770. void setBorder (const BorderSize& border);
  26771. /** Returns the size of border around the edge of the component.
  26772. @see setBorder
  26773. */
  26774. const BorderSize getBorder() const;
  26775. /** Used to disable the auto-scrolling which keeps the cursor visible.
  26776. If true (the default), the editor will scroll when the cursor moves offscreen. If
  26777. set to false, it won't.
  26778. */
  26779. void setScrollToShowCursor (bool shouldScrollToShowCursor);
  26780. /** @internal */
  26781. void paint (Graphics& g);
  26782. /** @internal */
  26783. void paintOverChildren (Graphics& g);
  26784. /** @internal */
  26785. void mouseDown (const MouseEvent& e);
  26786. /** @internal */
  26787. void mouseUp (const MouseEvent& e);
  26788. /** @internal */
  26789. void mouseDrag (const MouseEvent& e);
  26790. /** @internal */
  26791. void mouseDoubleClick (const MouseEvent& e);
  26792. /** @internal */
  26793. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26794. /** @internal */
  26795. bool keyPressed (const KeyPress& key);
  26796. /** @internal */
  26797. bool keyStateChanged (bool isKeyDown);
  26798. /** @internal */
  26799. void focusGained (FocusChangeType cause);
  26800. /** @internal */
  26801. void focusLost (FocusChangeType cause);
  26802. /** @internal */
  26803. void resized();
  26804. /** @internal */
  26805. void enablementChanged();
  26806. /** @internal */
  26807. void colourChanged();
  26808. /** @internal */
  26809. bool isTextInputActive() const;
  26810. juce_UseDebuggingNewOperator
  26811. protected:
  26812. /** This adds the items to the popup menu.
  26813. By default it adds the cut/copy/paste items, but you can override this if
  26814. you need to replace these with your own items.
  26815. If you want to add your own items to the existing ones, you can override this,
  26816. call the base class's addPopupMenuItems() method, then append your own items.
  26817. When the menu has been shown, performPopupMenuAction() will be called to
  26818. perform the item that the user has chosen.
  26819. The default menu items will be added using item IDs in the range
  26820. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  26821. menu IDs.
  26822. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  26823. a pointer to the info about it, or may be null if the menu is being triggered
  26824. by some other means.
  26825. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  26826. */
  26827. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  26828. const MouseEvent* mouseClickEvent);
  26829. /** This is called to perform one of the items that was shown on the popup menu.
  26830. If you've overridden addPopupMenuItems(), you should also override this
  26831. to perform the actions that you've added.
  26832. If you've overridden addPopupMenuItems() but have still left the default items
  26833. on the menu, remember to call the superclass's performPopupMenuAction()
  26834. so that it can perform the default actions if that's what the user clicked on.
  26835. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  26836. */
  26837. virtual void performPopupMenuAction (int menuItemID);
  26838. /** Scrolls the minimum distance needed to get the caret into view. */
  26839. void scrollToMakeSureCursorIsVisible();
  26840. /** @internal */
  26841. void moveCaret (int newCaretPos);
  26842. /** @internal */
  26843. void moveCursorTo (int newPosition, bool isSelecting);
  26844. /** Used internally to dispatch a text-change message. */
  26845. void textChanged();
  26846. /** Begins a new transaction in the UndoManager.
  26847. */
  26848. void newTransaction();
  26849. /** Used internally to trigger an undo or redo. */
  26850. void doUndoRedo (bool isRedo);
  26851. /** Can be overridden to intercept return key presses directly */
  26852. virtual void returnPressed();
  26853. /** Can be overridden to intercept escape key presses directly */
  26854. virtual void escapePressed();
  26855. /** @internal */
  26856. void handleCommandMessage (int commandId);
  26857. private:
  26858. class Iterator;
  26859. class UniformTextSection;
  26860. class TextHolderComponent;
  26861. class InsertAction;
  26862. class RemoveAction;
  26863. friend class InsertAction;
  26864. friend class RemoveAction;
  26865. ScopedPointer <Viewport> viewport;
  26866. TextHolderComponent* textHolder;
  26867. BorderSize borderSize;
  26868. bool readOnly : 1;
  26869. bool multiline : 1;
  26870. bool wordWrap : 1;
  26871. bool returnKeyStartsNewLine : 1;
  26872. bool caretVisible : 1;
  26873. bool popupMenuEnabled : 1;
  26874. bool selectAllTextWhenFocused : 1;
  26875. bool scrollbarVisible : 1;
  26876. bool wasFocused : 1;
  26877. bool caretFlashState : 1;
  26878. bool keepCursorOnScreen : 1;
  26879. bool tabKeyUsed : 1;
  26880. bool menuActive : 1;
  26881. bool valueTextNeedsUpdating : 1;
  26882. UndoManager undoManager;
  26883. float cursorX, cursorY, cursorHeight;
  26884. int maxTextLength;
  26885. Range<int> selection;
  26886. int leftIndent, topIndent;
  26887. unsigned int lastTransactionTime;
  26888. Font currentFont;
  26889. mutable int totalNumChars;
  26890. int caretPosition;
  26891. Array <UniformTextSection*> sections;
  26892. String textToShowWhenEmpty;
  26893. Colour colourForTextWhenEmpty;
  26894. juce_wchar passwordCharacter;
  26895. Value textValue;
  26896. enum
  26897. {
  26898. notDragging,
  26899. draggingSelectionStart,
  26900. draggingSelectionEnd
  26901. } dragType;
  26902. String allowedCharacters;
  26903. ListenerList <TextEditorListener> listeners;
  26904. void coalesceSimilarSections();
  26905. void splitSection (int sectionIndex, int charToSplitAt);
  26906. void clearInternal (UndoManager* um);
  26907. void insert (const String& text, int insertIndex, const Font& font,
  26908. const Colour& colour, UndoManager* um, int caretPositionToMoveTo);
  26909. void reinsert (int insertIndex, const Array <UniformTextSection*>& sections);
  26910. void remove (const Range<int>& range, UndoManager* um, int caretPositionToMoveTo);
  26911. void getCharPosition (int index, float& x, float& y, float& lineHeight) const;
  26912. void updateCaretPosition();
  26913. void textWasChangedByValue();
  26914. int indexAtPosition (float x, float y);
  26915. int findWordBreakAfter (int position) const;
  26916. int findWordBreakBefore (int position) const;
  26917. friend class TextHolderComponent;
  26918. friend class TextEditorViewport;
  26919. void drawContent (Graphics& g);
  26920. void updateTextHolderSize();
  26921. float getWordWrapWidth() const;
  26922. void timerCallbackInt();
  26923. void repaintCaret();
  26924. void repaintText (const Range<int>& range);
  26925. UndoManager* getUndoManager() throw();
  26926. TextEditor (const TextEditor&);
  26927. TextEditor& operator= (const TextEditor&);
  26928. };
  26929. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  26930. /*** End of inlined file: juce_TextEditor.h ***/
  26931. class Label;
  26932. /**
  26933. A class for receiving events from a Label.
  26934. You can register a LabelListener with a Label using the Label::addListener()
  26935. method, and it will be called when the text of the label changes, either because
  26936. of a call to Label::setText() or by the user editing the text (if the label is
  26937. editable).
  26938. @see Label::addListener, Label::removeListener
  26939. */
  26940. class JUCE_API LabelListener
  26941. {
  26942. public:
  26943. /** Destructor. */
  26944. virtual ~LabelListener() {}
  26945. /** Called when a Label's text has changed.
  26946. */
  26947. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  26948. };
  26949. /**
  26950. A component that displays a text string, and can optionally become a text
  26951. editor when clicked.
  26952. */
  26953. class JUCE_API Label : public Component,
  26954. public SettableTooltipClient,
  26955. protected TextEditorListener,
  26956. private ComponentListener,
  26957. private Value::Listener
  26958. {
  26959. public:
  26960. /** Creates a Label.
  26961. @param componentName the name to give the component
  26962. @param labelText the text to show in the label
  26963. */
  26964. Label (const String& componentName = String::empty,
  26965. const String& labelText = String::empty);
  26966. /** Destructor. */
  26967. ~Label();
  26968. /** Changes the label text.
  26969. If broadcastChangeMessage is true and the new text is different to the current
  26970. text, then the class will broadcast a change message to any LabelListeners that
  26971. are registered.
  26972. */
  26973. void setText (const String& newText,
  26974. bool broadcastChangeMessage);
  26975. /** Returns the label's current text.
  26976. @param returnActiveEditorContents if this is true and the label is currently
  26977. being edited, then this method will return the
  26978. text as it's being shown in the editor. If false,
  26979. then the value returned here won't be updated until
  26980. the user has finished typing and pressed the return
  26981. key.
  26982. */
  26983. const String getText (bool returnActiveEditorContents = false) const throw();
  26984. /** Returns the text content as a Value object.
  26985. You can call Value::referTo() on this object to make the label read and control
  26986. a Value object that you supply.
  26987. */
  26988. Value& getTextValue() { return textValue; }
  26989. /** Changes the font to use to draw the text.
  26990. @see getFont
  26991. */
  26992. void setFont (const Font& newFont) throw();
  26993. /** Returns the font currently being used.
  26994. @see setFont
  26995. */
  26996. const Font& getFont() const throw();
  26997. /** A set of colour IDs to use to change the colour of various aspects of the label.
  26998. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26999. methods.
  27000. Note that you can also use the constants from TextEditor::ColourIds to change the
  27001. colour of the text editor that is opened when a label is editable.
  27002. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  27003. */
  27004. enum ColourIds
  27005. {
  27006. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  27007. textColourId = 0x1000281, /**< The colour for the text. */
  27008. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  27009. Leave this transparent to not have an outline. */
  27010. };
  27011. /** Sets the style of justification to be used for positioning the text.
  27012. (The default is Justification::centredLeft)
  27013. */
  27014. void setJustificationType (const Justification& justification) throw();
  27015. /** Returns the type of justification, as set in setJustificationType(). */
  27016. const Justification getJustificationType() const throw() { return justification; }
  27017. /** Changes the gap that is left between the edge of the component and the text.
  27018. By default there's a small gap left at the sides of the component to allow for
  27019. the drawing of the border, but you can change this if necessary.
  27020. */
  27021. void setBorderSize (int horizontalBorder, int verticalBorder);
  27022. /** Returns the size of the horizontal gap being left around the text.
  27023. */
  27024. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  27025. /** Returns the size of the vertical gap being left around the text.
  27026. */
  27027. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  27028. /** Makes this label "stick to" another component.
  27029. This will cause the label to follow another component around, staying
  27030. either to its left or above it.
  27031. @param owner the component to follow
  27032. @param onLeft if true, the label will stay on the left of its component; if
  27033. false, it will stay above it.
  27034. */
  27035. void attachToComponent (Component* owner, bool onLeft);
  27036. /** If this label has been attached to another component using attachToComponent, this
  27037. returns the other component.
  27038. Returns 0 if the label is not attached.
  27039. */
  27040. Component* getAttachedComponent() const;
  27041. /** If the label is attached to the left of another component, this returns true.
  27042. Returns false if the label is above the other component. This is only relevent if
  27043. attachToComponent() has been called.
  27044. */
  27045. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  27046. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  27047. using ellipsis.
  27048. @see Graphics::drawFittedText
  27049. */
  27050. void setMinimumHorizontalScale (float newScale);
  27051. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  27052. /** Registers a listener that will be called when the label's text changes. */
  27053. void addListener (LabelListener* listener) throw();
  27054. /** Deregisters a previously-registered listener. */
  27055. void removeListener (LabelListener* listener) throw();
  27056. /** Makes the label turn into a TextEditor when clicked.
  27057. By default this is turned off.
  27058. If turned on, then single- or double-clicking will turn the label into
  27059. an editor. If the user then changes the text, then the ChangeBroadcaster
  27060. base class will be used to send change messages to any listeners that
  27061. have registered.
  27062. If the user changes the text, the textWasEdited() method will be called
  27063. afterwards, and subclasses can override this if they need to do anything
  27064. special.
  27065. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  27066. @param editOnDoubleClick if true, a double-click is needed to start editing
  27067. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  27068. edited will discard any changes; if false, then this will
  27069. commit the changes.
  27070. @see showEditor, setEditorColours, TextEditor
  27071. */
  27072. void setEditable (bool editOnSingleClick,
  27073. bool editOnDoubleClick = false,
  27074. bool lossOfFocusDiscardsChanges = false) throw();
  27075. /** Returns true if this option was set using setEditable(). */
  27076. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  27077. /** Returns true if this option was set using setEditable(). */
  27078. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  27079. /** Returns true if this option has been set in a call to setEditable(). */
  27080. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  27081. /** Returns true if the user can edit this label's text. */
  27082. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  27083. /** Makes the editor appear as if the label had been clicked by the user.
  27084. @see textWasEdited, setEditable
  27085. */
  27086. void showEditor();
  27087. /** Hides the editor if it was being shown.
  27088. @param discardCurrentEditorContents if true, the label's text will be
  27089. reset to whatever it was before the editor
  27090. was shown; if false, the current contents of the
  27091. editor will be used to set the label's text
  27092. before it is hidden.
  27093. */
  27094. void hideEditor (bool discardCurrentEditorContents);
  27095. /** Returns true if the editor is currently focused and active. */
  27096. bool isBeingEdited() const throw();
  27097. juce_UseDebuggingNewOperator
  27098. protected:
  27099. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  27100. Subclasses can override this if they need to customise this component in some way.
  27101. */
  27102. virtual TextEditor* createEditorComponent();
  27103. /** Called after the user changes the text.
  27104. */
  27105. virtual void textWasEdited();
  27106. /** Called when the text has been altered.
  27107. */
  27108. virtual void textWasChanged();
  27109. /** Called when the text editor has just appeared, due to a user click or other
  27110. focus change.
  27111. */
  27112. virtual void editorShown (TextEditor* editorComponent);
  27113. /** Called when the text editor is going to be deleted, after editing has finished.
  27114. */
  27115. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  27116. /** @internal */
  27117. void paint (Graphics& g);
  27118. /** @internal */
  27119. void resized();
  27120. /** @internal */
  27121. void mouseUp (const MouseEvent& e);
  27122. /** @internal */
  27123. void mouseDoubleClick (const MouseEvent& e);
  27124. /** @internal */
  27125. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  27126. /** @internal */
  27127. void componentParentHierarchyChanged (Component& component);
  27128. /** @internal */
  27129. void componentVisibilityChanged (Component& component);
  27130. /** @internal */
  27131. void inputAttemptWhenModal();
  27132. /** @internal */
  27133. void focusGained (FocusChangeType);
  27134. /** @internal */
  27135. void enablementChanged();
  27136. /** @internal */
  27137. KeyboardFocusTraverser* createFocusTraverser();
  27138. /** @internal */
  27139. void textEditorTextChanged (TextEditor& editor);
  27140. /** @internal */
  27141. void textEditorReturnKeyPressed (TextEditor& editor);
  27142. /** @internal */
  27143. void textEditorEscapeKeyPressed (TextEditor& editor);
  27144. /** @internal */
  27145. void textEditorFocusLost (TextEditor& editor);
  27146. /** @internal */
  27147. void colourChanged();
  27148. /** @internal */
  27149. void valueChanged (Value&);
  27150. private:
  27151. Value textValue;
  27152. String lastTextValue;
  27153. Font font;
  27154. Justification justification;
  27155. ScopedPointer <TextEditor> editor;
  27156. ListenerList <LabelListener> listeners;
  27157. Component::SafePointer<Component> ownerComponent;
  27158. int horizontalBorderSize, verticalBorderSize;
  27159. float minimumHorizontalScale;
  27160. bool editSingleClick : 1;
  27161. bool editDoubleClick : 1;
  27162. bool lossOfFocusDiscardsChanges : 1;
  27163. bool leftOfOwnerComp : 1;
  27164. bool updateFromTextEditorContents();
  27165. void callChangeListeners();
  27166. Label (const Label&);
  27167. Label& operator= (const Label&);
  27168. };
  27169. #endif // __JUCE_LABEL_JUCEHEADER__
  27170. /*** End of inlined file: juce_Label.h ***/
  27171. class ComboBox;
  27172. /**
  27173. A class for receiving events from a ComboBox.
  27174. You can register a ComboBoxListener with a ComboBox using the ComboBox::addListener()
  27175. method, and it will be called when the selected item in the box changes.
  27176. @see ComboBox::addListener, ComboBox::removeListener
  27177. */
  27178. class JUCE_API ComboBoxListener
  27179. {
  27180. public:
  27181. /** Destructor. */
  27182. virtual ~ComboBoxListener() {}
  27183. /** Called when a ComboBox has its selected item changed.
  27184. */
  27185. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  27186. };
  27187. /**
  27188. A component that lets the user choose from a drop-down list of choices.
  27189. The combo-box has a list of text strings, each with an associated id number,
  27190. that will be shown in the drop-down list when the user clicks on the component.
  27191. The currently selected choice is displayed in the combo-box, and this can
  27192. either be read-only text, or editable.
  27193. To find out when the user selects a different item or edits the text, you
  27194. can register a ComboBoxListener to receive callbacks.
  27195. @see ComboBoxListener
  27196. */
  27197. class JUCE_API ComboBox : public Component,
  27198. public SettableTooltipClient,
  27199. private LabelListener,
  27200. private AsyncUpdater,
  27201. private Value::Listener
  27202. {
  27203. public:
  27204. /** Creates a combo-box.
  27205. On construction, the text field will be empty, so you should call the
  27206. setSelectedId() or setText() method to choose the initial value before
  27207. displaying it.
  27208. @param componentName the name to set for the component (see Component::setName())
  27209. */
  27210. explicit ComboBox (const String& componentName = String::empty);
  27211. /** Destructor. */
  27212. ~ComboBox();
  27213. /** Sets whether the test in the combo-box is editable.
  27214. The default state for a new ComboBox is non-editable, and can only be changed
  27215. by choosing from the drop-down list.
  27216. */
  27217. void setEditableText (bool isEditable);
  27218. /** Returns true if the text is directly editable.
  27219. @see setEditableText
  27220. */
  27221. bool isTextEditable() const throw();
  27222. /** Sets the style of justification to be used for positioning the text.
  27223. The default is Justification::centredLeft. The text is displayed using a
  27224. Label component inside the ComboBox.
  27225. */
  27226. void setJustificationType (const Justification& justification) throw();
  27227. /** Returns the current justification for the text box.
  27228. @see setJustificationType
  27229. */
  27230. const Justification getJustificationType() const throw();
  27231. /** Adds an item to be shown in the drop-down list.
  27232. @param newItemText the text of the item to show in the list
  27233. @param newItemId an associated ID number that can be set or retrieved - see
  27234. getSelectedId() and setSelectedId()
  27235. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  27236. */
  27237. void addItem (const String& newItemText,
  27238. int newItemId) throw();
  27239. /** Adds a separator line to the drop-down list.
  27240. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  27241. */
  27242. void addSeparator() throw();
  27243. /** Adds a heading to the drop-down list, so that you can group the items into
  27244. different sections.
  27245. The headings are indented slightly differently to set them apart from the
  27246. items on the list, and obviously can't be selected. You might want to add
  27247. separators between your sections too.
  27248. @see addItem, addSeparator
  27249. */
  27250. void addSectionHeading (const String& headingName) throw();
  27251. /** This allows items in the drop-down list to be selectively disabled.
  27252. When you add an item, it's enabled by default, but you can call this
  27253. method to change its status.
  27254. If you disable an item which is already selected, this won't change the
  27255. current selection - it just stops the user choosing that item from the list.
  27256. */
  27257. void setItemEnabled (int itemId,
  27258. bool shouldBeEnabled) throw();
  27259. /** Changes the text for an existing item.
  27260. */
  27261. void changeItemText (int itemId,
  27262. const String& newText) throw();
  27263. /** Removes all the items from the drop-down list.
  27264. If this call causes the content to be cleared, then a change-message
  27265. will be broadcast unless dontSendChangeMessage is true.
  27266. @see addItem, removeItem, getNumItems
  27267. */
  27268. void clear (bool dontSendChangeMessage = false);
  27269. /** Returns the number of items that have been added to the list.
  27270. Note that this doesn't include headers or separators.
  27271. */
  27272. int getNumItems() const throw();
  27273. /** Returns the text for one of the items in the list.
  27274. Note that this doesn't include headers or separators.
  27275. @param index the item's index from 0 to (getNumItems() - 1)
  27276. */
  27277. const String getItemText (int index) const throw();
  27278. /** Returns the ID for one of the items in the list.
  27279. Note that this doesn't include headers or separators.
  27280. @param index the item's index from 0 to (getNumItems() - 1)
  27281. */
  27282. int getItemId (int index) const throw();
  27283. /** Returns the index in the list of a particular item ID.
  27284. If no such ID is found, this will return -1.
  27285. */
  27286. int indexOfItemId (int itemId) const throw();
  27287. /** Returns the ID of the item that's currently shown in the box.
  27288. If no item is selected, or if the text is editable and the user
  27289. has entered something which isn't one of the items in the list, then
  27290. this will return 0.
  27291. @see setSelectedId, getSelectedItemIndex, getText
  27292. */
  27293. int getSelectedId() const throw();
  27294. /** Returns a Value object that can be used to get or set the selected item's ID.
  27295. You can call Value::referTo() on this object to make the combo box control
  27296. another Value object.
  27297. */
  27298. Value& getSelectedIdAsValue() throw() { return currentId; }
  27299. /** Sets one of the items to be the current selection.
  27300. This will set the ComboBox's text to that of the item that matches
  27301. this ID.
  27302. @param newItemId the new item to select
  27303. @param dontSendChangeMessage if set to true, this method won't trigger a
  27304. change notification
  27305. @see getSelectedId, setSelectedItemIndex, setText
  27306. */
  27307. void setSelectedId (int newItemId,
  27308. bool dontSendChangeMessage = false) throw();
  27309. /** Returns the index of the item that's currently shown in the box.
  27310. If no item is selected, or if the text is editable and the user
  27311. has entered something which isn't one of the items in the list, then
  27312. this will return -1.
  27313. @see setSelectedItemIndex, getSelectedId, getText
  27314. */
  27315. int getSelectedItemIndex() const throw();
  27316. /** Sets one of the items to be the current selection.
  27317. This will set the ComboBox's text to that of the item at the given
  27318. index in the list.
  27319. @param newItemIndex the new item to select
  27320. @param dontSendChangeMessage if set to true, this method won't trigger a
  27321. change notification
  27322. @see getSelectedItemIndex, setSelectedId, setText
  27323. */
  27324. void setSelectedItemIndex (int newItemIndex,
  27325. bool dontSendChangeMessage = false) throw();
  27326. /** Returns the text that is currently shown in the combo-box's text field.
  27327. If the ComboBox has editable text, then this text may have been edited
  27328. by the user; otherwise it will be one of the items from the list, or
  27329. possibly an empty string if nothing was selected.
  27330. @see setText, getSelectedId, getSelectedItemIndex
  27331. */
  27332. const String getText() const throw();
  27333. /** Sets the contents of the combo-box's text field.
  27334. The text passed-in will be set as the current text regardless of whether
  27335. it is one of the items in the list. If the current text isn't one of the
  27336. items, then getSelectedId() will return -1, otherwise it wil return
  27337. the approriate ID.
  27338. @param newText the text to select
  27339. @param dontSendChangeMessage if set to true, this method won't trigger a
  27340. change notification
  27341. @see getText
  27342. */
  27343. void setText (const String& newText,
  27344. bool dontSendChangeMessage = false) throw();
  27345. /** Programmatically opens the text editor to allow the user to edit the current item.
  27346. This is the same effect as when the box is clicked-on.
  27347. @see Label::showEditor();
  27348. */
  27349. void showEditor();
  27350. /** Registers a listener that will be called when the box's content changes. */
  27351. void addListener (ComboBoxListener* listener) throw();
  27352. /** Deregisters a previously-registered listener. */
  27353. void removeListener (ComboBoxListener* listener) throw();
  27354. /** Sets a message to display when there is no item currently selected.
  27355. @see getTextWhenNothingSelected
  27356. */
  27357. void setTextWhenNothingSelected (const String& newMessage) throw();
  27358. /** Returns the text that is shown when no item is selected.
  27359. @see setTextWhenNothingSelected
  27360. */
  27361. const String getTextWhenNothingSelected() const throw();
  27362. /** Sets the message to show when there are no items in the list, and the user clicks
  27363. on the drop-down box.
  27364. By default it just says "no choices", but this lets you change it to something more
  27365. meaningful.
  27366. */
  27367. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  27368. /** Returns the text shown when no items have been added to the list.
  27369. @see setTextWhenNoChoicesAvailable
  27370. */
  27371. const String getTextWhenNoChoicesAvailable() const throw();
  27372. /** Gives the ComboBox a tooltip. */
  27373. void setTooltip (const String& newTooltip);
  27374. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  27375. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  27376. methods.
  27377. To change the colours of the menu that pops up
  27378. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  27379. */
  27380. enum ColourIds
  27381. {
  27382. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  27383. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  27384. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  27385. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  27386. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  27387. };
  27388. /** @internal */
  27389. void labelTextChanged (Label*);
  27390. /** @internal */
  27391. void enablementChanged();
  27392. /** @internal */
  27393. void colourChanged();
  27394. /** @internal */
  27395. void focusGained (Component::FocusChangeType cause);
  27396. /** @internal */
  27397. void focusLost (Component::FocusChangeType cause);
  27398. /** @internal */
  27399. void handleAsyncUpdate();
  27400. /** @internal */
  27401. const String getTooltip() { return label->getTooltip(); }
  27402. /** @internal */
  27403. void mouseDown (const MouseEvent&);
  27404. /** @internal */
  27405. void mouseDrag (const MouseEvent&);
  27406. /** @internal */
  27407. void mouseUp (const MouseEvent&);
  27408. /** @internal */
  27409. void lookAndFeelChanged();
  27410. /** @internal */
  27411. void paint (Graphics&);
  27412. /** @internal */
  27413. void resized();
  27414. /** @internal */
  27415. bool keyStateChanged (bool isKeyDown);
  27416. /** @internal */
  27417. bool keyPressed (const KeyPress&);
  27418. /** @internal */
  27419. void valueChanged (Value&);
  27420. juce_UseDebuggingNewOperator
  27421. private:
  27422. struct ItemInfo
  27423. {
  27424. String name;
  27425. int itemId;
  27426. bool isEnabled : 1, isHeading : 1;
  27427. bool isSeparator() const throw();
  27428. bool isRealItem() const throw();
  27429. };
  27430. OwnedArray <ItemInfo> items;
  27431. Value currentId;
  27432. int lastCurrentId;
  27433. bool isButtonDown, separatorPending, menuActive, textIsCustom;
  27434. ListenerList <ComboBoxListener> listeners;
  27435. ScopedPointer<Label> label;
  27436. String textWhenNothingSelected, noChoicesMessage;
  27437. void showPopup();
  27438. ItemInfo* getItemForId (int itemId) const throw();
  27439. ItemInfo* getItemForIndex (int index) const throw();
  27440. ComboBox (const ComboBox&);
  27441. ComboBox& operator= (const ComboBox&);
  27442. };
  27443. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  27444. /*** End of inlined file: juce_ComboBox.h ***/
  27445. /**
  27446. Manages the state of some audio and midi i/o devices.
  27447. This class keeps tracks of a currently-selected audio device, through
  27448. with which it continuously streams data from an audio callback, as well as
  27449. one or more midi inputs.
  27450. The idea is that your application will create one global instance of this object,
  27451. and let it take care of creating and deleting specific types of audio devices
  27452. internally. So when the device is changed, your callbacks will just keep running
  27453. without having to worry about this.
  27454. The manager can save and reload all of its device settings as XML, which
  27455. makes it very easy for you to save and reload the audio setup of your
  27456. application.
  27457. And to make it easy to let the user change its settings, there's a component
  27458. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  27459. device selection/sample-rate/latency controls.
  27460. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  27461. call addAudioCallback() to register your audio callback with it, and use that to process
  27462. your audio data.
  27463. The manager also acts as a handy hub for incoming midi messages, allowing a
  27464. listener to register for messages from either a specific midi device, or from whatever
  27465. the current default midi input device is. The listener then doesn't have to worry about
  27466. re-registering with different midi devices if they are changed or deleted.
  27467. And yet another neat trick is that amount of CPU time being used is measured and
  27468. available with the getCpuUsage() method.
  27469. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  27470. listeners whenever one of its settings is changed.
  27471. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  27472. */
  27473. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  27474. {
  27475. public:
  27476. /** Creates a default AudioDeviceManager.
  27477. Initially no audio device will be selected. You should call the initialise() method
  27478. and register an audio callback with setAudioCallback() before it'll be able to
  27479. actually make any noise.
  27480. */
  27481. AudioDeviceManager();
  27482. /** Destructor. */
  27483. ~AudioDeviceManager();
  27484. /**
  27485. This structure holds a set of properties describing the current audio setup.
  27486. @see AudioDeviceManager::setAudioDeviceSetup()
  27487. */
  27488. struct JUCE_API AudioDeviceSetup
  27489. {
  27490. AudioDeviceSetup();
  27491. bool operator== (const AudioDeviceSetup& other) const;
  27492. /** The name of the audio device used for output.
  27493. The name has to be one of the ones listed by the AudioDeviceManager's currently
  27494. selected device type.
  27495. This may be the same as the input device.
  27496. */
  27497. String outputDeviceName;
  27498. /** The name of the audio device used for input.
  27499. This may be the same as the output device.
  27500. */
  27501. String inputDeviceName;
  27502. /** The current sample rate.
  27503. This rate is used for both the input and output devices.
  27504. */
  27505. double sampleRate;
  27506. /** The buffer size, in samples.
  27507. This buffer size is used for both the input and output devices.
  27508. */
  27509. int bufferSize;
  27510. /** The set of active input channels.
  27511. The bits that are set in this array indicate the channels of the
  27512. input device that are active.
  27513. */
  27514. BigInteger inputChannels;
  27515. /** If this is true, it indicates that the inputChannels array
  27516. should be ignored, and instead, the device's default channels
  27517. should be used.
  27518. */
  27519. bool useDefaultInputChannels;
  27520. /** The set of active output channels.
  27521. The bits that are set in this array indicate the channels of the
  27522. input device that are active.
  27523. */
  27524. BigInteger outputChannels;
  27525. /** If this is true, it indicates that the outputChannels array
  27526. should be ignored, and instead, the device's default channels
  27527. should be used.
  27528. */
  27529. bool useDefaultOutputChannels;
  27530. };
  27531. /** Opens a set of audio devices ready for use.
  27532. This will attempt to open either a default audio device, or one that was
  27533. previously saved as XML.
  27534. @param numInputChannelsNeeded a minimum number of input channels needed
  27535. by your app.
  27536. @param numOutputChannelsNeeded a minimum number of output channels to open
  27537. @param savedState either a previously-saved state that was produced
  27538. by createStateXml(), or 0 if you want the manager
  27539. to choose the best device to open.
  27540. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  27541. fails to open, then a default device will be used
  27542. instead. If false, then on failure, no device is
  27543. opened.
  27544. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  27545. name, then that will be used as the default device
  27546. (assuming that there wasn't one specified in the XML).
  27547. The string can actually be a simple wildcard, containing "*"
  27548. and "?" characters
  27549. @param preferredSetupOptions if this is non-null, the structure will be used as the
  27550. set of preferred settings when opening the device. If you
  27551. use this parameter, the preferredDefaultDeviceName
  27552. field will be ignored
  27553. @returns an error message if anything went wrong, or an empty string if it worked ok.
  27554. */
  27555. const String initialise (int numInputChannelsNeeded,
  27556. int numOutputChannelsNeeded,
  27557. const XmlElement* savedState,
  27558. bool selectDefaultDeviceOnFailure,
  27559. const String& preferredDefaultDeviceName = String::empty,
  27560. const AudioDeviceSetup* preferredSetupOptions = 0);
  27561. /** Returns some XML representing the current state of the manager.
  27562. This stores the current device, its samplerate, block size, etc, and
  27563. can be restored later with initialise().
  27564. */
  27565. XmlElement* createStateXml() const;
  27566. /** Returns the current device properties that are in use.
  27567. @see setAudioDeviceSetup
  27568. */
  27569. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  27570. /** Changes the current device or its settings.
  27571. If you want to change a device property, like the current sample rate or
  27572. block size, you can call getAudioDeviceSetup() to retrieve the current
  27573. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  27574. and pass it back into this method to apply the new settings.
  27575. @param newSetup the settings that you'd like to use
  27576. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  27577. settings will be taken as having been explicitly chosen by the
  27578. user, and the next time createStateXml() is called, these settings
  27579. will be returned. If it's false, then the device is treated as a
  27580. temporary or default device, and a call to createStateXml() will
  27581. return either the last settings that were made with treatAsChosenDevice
  27582. as true, or the last XML settings that were passed into initialise().
  27583. @returns an error message if anything went wrong, or an empty string if it worked ok.
  27584. @see getAudioDeviceSetup
  27585. */
  27586. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  27587. bool treatAsChosenDevice);
  27588. /** Returns the currently-active audio device. */
  27589. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  27590. /** Returns the type of audio device currently in use.
  27591. @see setCurrentAudioDeviceType
  27592. */
  27593. const String getCurrentAudioDeviceType() const { return currentDeviceType; }
  27594. /** Returns the currently active audio device type object.
  27595. Don't keep a copy of this pointer - it's owned by the device manager and could
  27596. change at any time.
  27597. */
  27598. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  27599. /** Changes the class of audio device being used.
  27600. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  27601. this because there's only one type: CoreAudio.
  27602. For a list of types, see getAvailableDeviceTypes().
  27603. */
  27604. void setCurrentAudioDeviceType (const String& type,
  27605. bool treatAsChosenDevice);
  27606. /** Closes the currently-open device.
  27607. You can call restartLastAudioDevice() later to reopen it in the same state
  27608. that it was just in.
  27609. */
  27610. void closeAudioDevice();
  27611. /** Tries to reload the last audio device that was running.
  27612. Note that this only reloads the last device that was running before
  27613. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  27614. and can only be called after a device has been opened with SetAudioDevice().
  27615. If a device is already open, this call will do nothing.
  27616. */
  27617. void restartLastAudioDevice();
  27618. /** Registers an audio callback to be used.
  27619. The manager will redirect callbacks from whatever audio device is currently
  27620. in use to all registered callback objects. If more than one callback is
  27621. active, they will all be given the same input data, and their outputs will
  27622. be summed.
  27623. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  27624. object before returning.
  27625. To remove a callback, use removeAudioCallback().
  27626. */
  27627. void addAudioCallback (AudioIODeviceCallback* newCallback);
  27628. /** Deregisters a previously added callback.
  27629. If necessary, this method will invoke audioDeviceStopped() on the callback
  27630. object before returning.
  27631. @see addAudioCallback
  27632. */
  27633. void removeAudioCallback (AudioIODeviceCallback* callback);
  27634. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  27635. Returns a value between 0 and 1.0
  27636. */
  27637. double getCpuUsage() const;
  27638. /** Enables or disables a midi input device.
  27639. The list of devices can be obtained with the MidiInput::getDevices() method.
  27640. Any incoming messages from enabled input devices will be forwarded on to all the
  27641. listeners that have been registered with the addMidiInputCallback() method. They
  27642. can either register for messages from a particular device, or from just the
  27643. "default" midi input.
  27644. Routing the midi input via an AudioDeviceManager means that when a listener
  27645. registers for the default midi input, this default device can be changed by the
  27646. manager without the listeners having to know about it or re-register.
  27647. It also means that a listener can stay registered for a midi input that is disabled
  27648. or not present, so that when the input is re-enabled, the listener will start
  27649. receiving messages again.
  27650. @see addMidiInputCallback, isMidiInputEnabled
  27651. */
  27652. void setMidiInputEnabled (const String& midiInputDeviceName,
  27653. bool enabled);
  27654. /** Returns true if a given midi input device is being used.
  27655. @see setMidiInputEnabled
  27656. */
  27657. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  27658. /** Registers a listener for callbacks when midi events arrive from a midi input.
  27659. The device name can be empty to indicate that it wants events from whatever the
  27660. current "default" device is. Or it can be the name of one of the midi input devices
  27661. (see MidiInput::getDevices() for the names).
  27662. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  27663. events forwarded on to listeners.
  27664. */
  27665. void addMidiInputCallback (const String& midiInputDeviceName,
  27666. MidiInputCallback* callback);
  27667. /** Removes a listener that was previously registered with addMidiInputCallback().
  27668. */
  27669. void removeMidiInputCallback (const String& midiInputDeviceName,
  27670. MidiInputCallback* callback);
  27671. /** Sets a midi output device to use as the default.
  27672. The list of devices can be obtained with the MidiOutput::getDevices() method.
  27673. The specified device will be opened automatically and can be retrieved with the
  27674. getDefaultMidiOutput() method.
  27675. Pass in an empty string to deselect all devices. For the default device, you
  27676. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  27677. @see getDefaultMidiOutput, getDefaultMidiOutputName
  27678. */
  27679. void setDefaultMidiOutput (const String& deviceName);
  27680. /** Returns the name of the default midi output.
  27681. @see setDefaultMidiOutput, getDefaultMidiOutput
  27682. */
  27683. const String getDefaultMidiOutputName() const { return defaultMidiOutputName; }
  27684. /** Returns the current default midi output device.
  27685. If no device has been selected, or the device can't be opened, this will
  27686. return 0.
  27687. @see getDefaultMidiOutputName
  27688. */
  27689. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  27690. /** Returns a list of the types of device supported.
  27691. */
  27692. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  27693. /** Creates a list of available types.
  27694. This will add a set of new AudioIODeviceType objects to the specified list, to
  27695. represent each available types of device.
  27696. You can override this if your app needs to do something specific, like avoid
  27697. using DirectSound devices, etc.
  27698. */
  27699. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  27700. /** Plays a beep through the current audio device.
  27701. This is here to allow the audio setup UI panels to easily include a "test"
  27702. button so that the user can check where the audio is coming from.
  27703. */
  27704. void playTestSound();
  27705. /** Turns on level-measuring.
  27706. When enabled, the device manager will measure the peak input level
  27707. across all channels, and you can get this level by calling getCurrentInputLevel().
  27708. This is mainly intended for audio setup UI panels to use to create a mic
  27709. level display, so that the user can check that they've selected the right
  27710. device.
  27711. A simple filter is used to make the level decay smoothly, but this is
  27712. only intended for giving rough feedback, and not for any kind of accurate
  27713. measurement.
  27714. */
  27715. void enableInputLevelMeasurement (bool enableMeasurement);
  27716. /** Returns the current input level.
  27717. To use this, you must first enable it by calling enableInputLevelMeasurement().
  27718. See enableInputLevelMeasurement() for more info.
  27719. */
  27720. double getCurrentInputLevel() const;
  27721. juce_UseDebuggingNewOperator
  27722. private:
  27723. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  27724. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  27725. AudioDeviceSetup currentSetup;
  27726. ScopedPointer <AudioIODevice> currentAudioDevice;
  27727. SortedSet <AudioIODeviceCallback*> callbacks;
  27728. int numInputChansNeeded, numOutputChansNeeded;
  27729. String currentDeviceType;
  27730. BigInteger inputChannels, outputChannels;
  27731. ScopedPointer <XmlElement> lastExplicitSettings;
  27732. mutable bool listNeedsScanning;
  27733. bool useInputNames;
  27734. int inputLevelMeasurementEnabledCount;
  27735. double inputLevel;
  27736. ScopedPointer <AudioSampleBuffer> testSound;
  27737. int testSoundPosition;
  27738. AudioSampleBuffer tempBuffer;
  27739. StringArray midiInsFromXml;
  27740. OwnedArray <MidiInput> enabledMidiInputs;
  27741. Array <MidiInputCallback*> midiCallbacks;
  27742. Array <MidiInput*> midiCallbackDevices;
  27743. String defaultMidiOutputName;
  27744. ScopedPointer <MidiOutput> defaultMidiOutput;
  27745. CriticalSection audioCallbackLock, midiCallbackLock;
  27746. double cpuUsageMs, timeToCpuScale;
  27747. class CallbackHandler : public AudioIODeviceCallback,
  27748. public MidiInputCallback
  27749. {
  27750. public:
  27751. AudioDeviceManager* owner;
  27752. void audioDeviceIOCallback (const float** inputChannelData,
  27753. int totalNumInputChannels,
  27754. float** outputChannelData,
  27755. int totalNumOutputChannels,
  27756. int numSamples);
  27757. void audioDeviceAboutToStart (AudioIODevice*);
  27758. void audioDeviceStopped();
  27759. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  27760. };
  27761. CallbackHandler callbackHandler;
  27762. friend class CallbackHandler;
  27763. void audioDeviceIOCallbackInt (const float** inputChannelData,
  27764. int totalNumInputChannels,
  27765. float** outputChannelData,
  27766. int totalNumOutputChannels,
  27767. int numSamples);
  27768. void audioDeviceAboutToStartInt (AudioIODevice* device);
  27769. void audioDeviceStoppedInt();
  27770. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  27771. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  27772. const BigInteger& ins, const BigInteger& outs);
  27773. void stopDevice();
  27774. void updateXml();
  27775. void createDeviceTypesIfNeeded();
  27776. void scanDevicesIfNeeded();
  27777. void deleteCurrentDevice();
  27778. double chooseBestSampleRate (double preferred) const;
  27779. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  27780. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  27781. AudioDeviceManager (const AudioDeviceManager&);
  27782. AudioDeviceManager& operator= (const AudioDeviceManager&);
  27783. };
  27784. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  27785. /*** End of inlined file: juce_AudioDeviceManager.h ***/
  27786. #endif
  27787. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  27788. #endif
  27789. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  27790. #endif
  27791. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  27792. #endif
  27793. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  27794. #endif
  27795. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  27796. /*** Start of inlined file: juce_AudioDataConverters.h ***/
  27797. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  27798. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  27799. /**
  27800. A set of routines to convert buffers of 32-bit floating point data to and from
  27801. various integer formats.
  27802. */
  27803. class JUCE_API AudioDataConverters
  27804. {
  27805. public:
  27806. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  27807. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  27808. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  27809. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  27810. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27811. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27812. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27813. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27814. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  27815. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  27816. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  27817. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  27818. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27819. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27820. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27821. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27822. enum DataFormat
  27823. {
  27824. int16LE,
  27825. int16BE,
  27826. int24LE,
  27827. int24BE,
  27828. int32LE,
  27829. int32BE,
  27830. float32LE,
  27831. float32BE,
  27832. };
  27833. static void convertFloatToFormat (DataFormat destFormat,
  27834. const float* source, void* dest, int numSamples);
  27835. static void convertFormatToFloat (DataFormat sourceFormat,
  27836. const void* source, float* dest, int numSamples);
  27837. static void interleaveSamples (const float** source, float* dest,
  27838. int numSamples, int numChannels);
  27839. static void deinterleaveSamples (const float* source, float** dest,
  27840. int numSamples, int numChannels);
  27841. private:
  27842. AudioDataConverters();
  27843. AudioDataConverters (const AudioDataConverters&);
  27844. AudioDataConverters& operator= (const AudioDataConverters&);
  27845. };
  27846. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  27847. /*** End of inlined file: juce_AudioDataConverters.h ***/
  27848. #endif
  27849. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27850. #endif
  27851. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  27852. #endif
  27853. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  27854. #endif
  27855. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  27856. /*** Start of inlined file: juce_MidiFile.h ***/
  27857. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  27858. #define __JUCE_MIDIFILE_JUCEHEADER__
  27859. /*** Start of inlined file: juce_MidiMessageSequence.h ***/
  27860. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  27861. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  27862. /**
  27863. A sequence of timestamped midi messages.
  27864. This allows the sequence to be manipulated, and also to be read from and
  27865. written to a standard midi file.
  27866. @see MidiMessage, MidiFile
  27867. */
  27868. class JUCE_API MidiMessageSequence
  27869. {
  27870. public:
  27871. /** Creates an empty midi sequence object. */
  27872. MidiMessageSequence();
  27873. /** Creates a copy of another sequence. */
  27874. MidiMessageSequence (const MidiMessageSequence& other);
  27875. /** Replaces this sequence with another one. */
  27876. MidiMessageSequence& operator= (const MidiMessageSequence& other);
  27877. /** Destructor. */
  27878. ~MidiMessageSequence();
  27879. /** Structure used to hold midi events in the sequence.
  27880. These structures act as 'handles' on the events as they are moved about in
  27881. the list, and make it quick to find the matching note-offs for note-on events.
  27882. @see MidiMessageSequence::getEventPointer
  27883. */
  27884. class MidiEventHolder
  27885. {
  27886. public:
  27887. /** Destructor. */
  27888. ~MidiEventHolder();
  27889. /** The message itself, whose timestamp is used to specify the event's time.
  27890. */
  27891. MidiMessage message;
  27892. /** The matching note-off event (if this is a note-on event).
  27893. If this isn't a note-on, this pointer will be null.
  27894. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  27895. note-offs up-to-date after events have been moved around in the sequence
  27896. or deleted.
  27897. */
  27898. MidiEventHolder* noteOffObject;
  27899. juce_UseDebuggingNewOperator
  27900. private:
  27901. friend class MidiMessageSequence;
  27902. MidiEventHolder (const MidiMessage& message);
  27903. };
  27904. /** Clears the sequence. */
  27905. void clear();
  27906. /** Returns the number of events in the sequence. */
  27907. int getNumEvents() const;
  27908. /** Returns a pointer to one of the events. */
  27909. MidiEventHolder* getEventPointer (int index) const;
  27910. /** Returns the time of the note-up that matches the note-on at this index.
  27911. If the event at this index isn't a note-on, it'll just return 0.
  27912. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  27913. */
  27914. double getTimeOfMatchingKeyUp (int index) const;
  27915. /** Returns the index of the note-up that matches the note-on at this index.
  27916. If the event at this index isn't a note-on, it'll just return -1.
  27917. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  27918. */
  27919. int getIndexOfMatchingKeyUp (int index) const;
  27920. /** Returns the index of an event. */
  27921. int getIndexOf (MidiEventHolder* event) const;
  27922. /** Returns the index of the first event on or after the given timestamp.
  27923. If the time is beyond the end of the sequence, this will return the
  27924. number of events.
  27925. */
  27926. int getNextIndexAtTime (double timeStamp) const;
  27927. /** Returns the timestamp of the first event in the sequence.
  27928. @see getEndTime
  27929. */
  27930. double getStartTime() const;
  27931. /** Returns the timestamp of the last event in the sequence.
  27932. @see getStartTime
  27933. */
  27934. double getEndTime() const;
  27935. /** Returns the timestamp of the event at a given index.
  27936. If the index is out-of-range, this will return 0.0
  27937. */
  27938. double getEventTime (int index) const;
  27939. /** Inserts a midi message into the sequence.
  27940. The index at which the new message gets inserted will depend on its timestamp,
  27941. because the sequence is kept sorted.
  27942. Remember to call updateMatchedPairs() after adding note-on events.
  27943. @param newMessage the new message to add (an internal copy will be made)
  27944. @param timeAdjustment an optional value to add to the timestamp of the message
  27945. that will be inserted
  27946. @see updateMatchedPairs
  27947. */
  27948. void addEvent (const MidiMessage& newMessage,
  27949. double timeAdjustment = 0);
  27950. /** Deletes one of the events in the sequence.
  27951. Remember to call updateMatchedPairs() after removing events.
  27952. @param index the index of the event to delete
  27953. @param deleteMatchingNoteUp whether to also remove the matching note-off
  27954. if the event you're removing is a note-on
  27955. */
  27956. void deleteEvent (int index, bool deleteMatchingNoteUp);
  27957. /** Merges another sequence into this one.
  27958. Remember to call updateMatchedPairs() after using this method.
  27959. @param other the sequence to add from
  27960. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  27961. as they are read from the other sequence
  27962. @param firstAllowableDestTime events will not be added if their time is earlier
  27963. than this time. (This is after their time has been adjusted
  27964. by the timeAdjustmentDelta)
  27965. @param endOfAllowableDestTimes events will not be added if their time is equal to
  27966. or greater than this time. (This is after their time has
  27967. been adjusted by the timeAdjustmentDelta)
  27968. */
  27969. void addSequence (const MidiMessageSequence& other,
  27970. double timeAdjustmentDelta,
  27971. double firstAllowableDestTime,
  27972. double endOfAllowableDestTimes);
  27973. /** Makes sure all the note-on and note-off pairs are up-to-date.
  27974. Call this after moving messages about or deleting/adding messages, and it
  27975. will scan the list and make sure all the note-offs in the MidiEventHolder
  27976. structures are pointing at the correct ones.
  27977. */
  27978. void updateMatchedPairs();
  27979. /** Copies all the messages for a particular midi channel to another sequence.
  27980. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  27981. @param destSequence the sequence that the chosen events should be copied to
  27982. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  27983. channel) will also be copied across.
  27984. @see extractSysExMessages
  27985. */
  27986. void extractMidiChannelMessages (int channelNumberToExtract,
  27987. MidiMessageSequence& destSequence,
  27988. bool alsoIncludeMetaEvents) const;
  27989. /** Copies all midi sys-ex messages to another sequence.
  27990. @param destSequence this is the sequence to which any sys-exes in this sequence
  27991. will be added
  27992. @see extractMidiChannelMessages
  27993. */
  27994. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  27995. /** Removes any messages in this sequence that have a specific midi channel.
  27996. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  27997. */
  27998. void deleteMidiChannelMessages (int channelNumberToRemove);
  27999. /** Removes any sys-ex messages from this sequence.
  28000. */
  28001. void deleteSysExMessages();
  28002. /** Adds an offset to the timestamps of all events in the sequence.
  28003. @param deltaTime the amount to add to each timestamp.
  28004. */
  28005. void addTimeToMessages (double deltaTime);
  28006. /** Scans through the sequence to determine the state of any midi controllers at
  28007. a given time.
  28008. This will create a sequence of midi controller changes that can be
  28009. used to set all midi controllers to the state they would be in at the
  28010. specified time within this sequence.
  28011. As well as controllers, it will also recreate the midi program number
  28012. and pitch bend position.
  28013. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  28014. for other channels will be ignored.
  28015. @param time the time at which you want to find out the state - there are
  28016. no explicit units for this time measurement, it's the same units
  28017. as used for the timestamps of the messages
  28018. @param resultMessages an array to which midi controller-change messages will be added. This
  28019. will be the minimum number of controller changes to recreate the
  28020. state at the required time.
  28021. */
  28022. void createControllerUpdatesForTime (int channelNumber, double time,
  28023. OwnedArray<MidiMessage>& resultMessages);
  28024. /** Swaps this sequence with another one. */
  28025. void swapWith (MidiMessageSequence& other) throw();
  28026. juce_UseDebuggingNewOperator
  28027. /** @internal */
  28028. static int compareElements (const MidiMessageSequence::MidiEventHolder* first,
  28029. const MidiMessageSequence::MidiEventHolder* second) throw();
  28030. private:
  28031. friend class MidiFile;
  28032. OwnedArray <MidiEventHolder> list;
  28033. void sort();
  28034. };
  28035. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  28036. /*** End of inlined file: juce_MidiMessageSequence.h ***/
  28037. /**
  28038. Reads/writes standard midi format files.
  28039. To read a midi file, create a MidiFile object and call its readFrom() method. You
  28040. can then get the individual midi tracks from it using the getTrack() method.
  28041. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  28042. to it using the addTrack() method, and then call its writeTo() method to stream
  28043. it out.
  28044. @see MidiMessageSequence
  28045. */
  28046. class JUCE_API MidiFile
  28047. {
  28048. public:
  28049. /** Creates an empty MidiFile object.
  28050. */
  28051. MidiFile();
  28052. /** Destructor. */
  28053. ~MidiFile();
  28054. /** Returns the number of tracks in the file.
  28055. @see getTrack, addTrack
  28056. */
  28057. int getNumTracks() const throw();
  28058. /** Returns a pointer to one of the tracks in the file.
  28059. @returns a pointer to the track, or 0 if the index is out-of-range
  28060. @see getNumTracks, addTrack
  28061. */
  28062. const MidiMessageSequence* getTrack (const int index) const throw();
  28063. /** Adds a midi track to the file.
  28064. This will make its own internal copy of the sequence that is passed-in.
  28065. @see getNumTracks, getTrack
  28066. */
  28067. void addTrack (const MidiMessageSequence& trackSequence);
  28068. /** Removes all midi tracks from the file.
  28069. @see getNumTracks
  28070. */
  28071. void clear();
  28072. /** Returns the raw time format code that will be written to a stream.
  28073. After reading a midi file, this method will return the time-format that
  28074. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  28075. or setSmpteTimeFormat() methods.
  28076. If the value returned is positive, it indicates the number of midi ticks
  28077. per quarter-note - see setTicksPerQuarterNote().
  28078. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  28079. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  28080. */
  28081. short getTimeFormat() const throw();
  28082. /** Sets the time format to use when this file is written to a stream.
  28083. If this is called, the file will be written as bars/beats using the
  28084. specified resolution, rather than SMPTE absolute times, as would be
  28085. used if setSmpteTimeFormat() had been called instead.
  28086. @param ticksPerQuarterNote e.g. 96, 960
  28087. @see setSmpteTimeFormat
  28088. */
  28089. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  28090. /** Sets the time format to use when this file is written to a stream.
  28091. If this is called, the file will be written using absolute times, rather
  28092. than bars/beats as would be the case if setTicksPerBeat() had been called
  28093. instead.
  28094. @param framesPerSecond must be 24, 25, 29 or 30
  28095. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  28096. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  28097. timing, setSmpteTimeFormat (25, 40)
  28098. @see setTicksPerBeat
  28099. */
  28100. void setSmpteTimeFormat (const int framesPerSecond,
  28101. const int subframeResolution) throw();
  28102. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  28103. Useful for finding the positions of all the tempo changes in a file.
  28104. @param tempoChangeEvents a list to which all the events will be added
  28105. */
  28106. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  28107. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  28108. Useful for finding the positions of all the tempo changes in a file.
  28109. @param timeSigEvents a list to which all the events will be added
  28110. */
  28111. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  28112. /** Returns the latest timestamp in any of the tracks.
  28113. (Useful for finding the length of the file).
  28114. */
  28115. double getLastTimestamp() const;
  28116. /** Reads a midi file format stream.
  28117. After calling this, you can get the tracks that were read from the file by using the
  28118. getNumTracks() and getTrack() methods.
  28119. The timestamps of the midi events in the tracks will represent their positions in
  28120. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  28121. method.
  28122. @returns true if the stream was read successfully
  28123. */
  28124. bool readFrom (InputStream& sourceStream);
  28125. /** Writes the midi tracks as a standard midi file.
  28126. @returns true if the operation succeeded.
  28127. */
  28128. bool writeTo (OutputStream& destStream);
  28129. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  28130. This will use the midi time format and tempo/time signature info in the
  28131. tracks to convert all the timestamps to absolute values in seconds.
  28132. */
  28133. void convertTimestampTicksToSeconds();
  28134. juce_UseDebuggingNewOperator
  28135. /** @internal */
  28136. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  28137. const MidiMessageSequence::MidiEventHolder* const second);
  28138. private:
  28139. OwnedArray <MidiMessageSequence> tracks;
  28140. short timeFormat;
  28141. MidiFile (const MidiFile&);
  28142. MidiFile& operator= (const MidiFile&);
  28143. void readNextTrack (const uint8* data, int size);
  28144. void writeTrack (OutputStream& mainOut, const int trackNum);
  28145. };
  28146. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  28147. /*** End of inlined file: juce_MidiFile.h ***/
  28148. #endif
  28149. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28150. /*** Start of inlined file: juce_MidiKeyboardState.h ***/
  28151. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28152. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28153. class MidiKeyboardState;
  28154. /**
  28155. Receives events from a MidiKeyboardState object.
  28156. @see MidiKeyboardState
  28157. */
  28158. class JUCE_API MidiKeyboardStateListener
  28159. {
  28160. public:
  28161. MidiKeyboardStateListener() throw() {}
  28162. virtual ~MidiKeyboardStateListener() {}
  28163. /** Called when one of the MidiKeyboardState's keys is pressed.
  28164. This will be called synchronously when the state is either processing a
  28165. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  28166. when a note is being played with its MidiKeyboardState::noteOn() method.
  28167. Note that this callback could happen from an audio callback thread, so be
  28168. careful not to block, and avoid any UI activity in the callback.
  28169. */
  28170. virtual void handleNoteOn (MidiKeyboardState* source,
  28171. int midiChannel, int midiNoteNumber, float velocity) = 0;
  28172. /** Called when one of the MidiKeyboardState's keys is released.
  28173. This will be called synchronously when the state is either processing a
  28174. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  28175. when a note is being played with its MidiKeyboardState::noteOff() method.
  28176. Note that this callback could happen from an audio callback thread, so be
  28177. careful not to block, and avoid any UI activity in the callback.
  28178. */
  28179. virtual void handleNoteOff (MidiKeyboardState* source,
  28180. int midiChannel, int midiNoteNumber) = 0;
  28181. };
  28182. /**
  28183. Represents a piano keyboard, keeping track of which keys are currently pressed.
  28184. This object can parse a stream of midi events, using them to update its idea
  28185. of which keys are pressed for each individiual midi channel.
  28186. When keys go up or down, it can broadcast these events to listener objects.
  28187. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  28188. methods, and midi messages for these events will be merged into the
  28189. midi stream that gets processed by processNextMidiBuffer().
  28190. */
  28191. class JUCE_API MidiKeyboardState
  28192. {
  28193. public:
  28194. MidiKeyboardState();
  28195. ~MidiKeyboardState();
  28196. /** Resets the state of the object.
  28197. All internal data for all the channels is reset, but no events are sent as a
  28198. result.
  28199. If you want to release any keys that are currently down, and to send out note-up
  28200. midi messages for this, use the allNotesOff() method instead.
  28201. */
  28202. void reset();
  28203. /** Returns true if the given midi key is currently held down for the given midi channel.
  28204. The channel number must be between 1 and 16. If you want to see if any notes are
  28205. on for a range of channels, use the isNoteOnForChannels() method.
  28206. */
  28207. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  28208. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  28209. The channel mask has a bit set for each midi channel you want to test for - bit
  28210. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  28211. If a note is on for at least one of the specified channels, this returns true.
  28212. */
  28213. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  28214. /** Turns a specified note on.
  28215. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  28216. next call to processNextMidiBuffer().
  28217. It will also trigger a synchronous callback to the listeners to tell them that the key has
  28218. gone down.
  28219. */
  28220. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  28221. /** Turns a specified note off.
  28222. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  28223. next call to processNextMidiBuffer().
  28224. It will also trigger a synchronous callback to the listeners to tell them that the key has
  28225. gone up.
  28226. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  28227. */
  28228. void noteOff (const int midiChannel, const int midiNoteNumber);
  28229. /** This will turn off any currently-down notes for the given midi channel.
  28230. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  28231. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  28232. and events being added to the midi stream.
  28233. */
  28234. void allNotesOff (const int midiChannel);
  28235. /** Looks at a key-up/down event and uses it to update the state of this object.
  28236. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  28237. instead.
  28238. */
  28239. void processNextMidiEvent (const MidiMessage& message);
  28240. /** Scans a midi stream for up/down events and adds its own events to it.
  28241. This will look for any up/down events and use them to update the internal state,
  28242. synchronously making suitable callbacks to the listeners.
  28243. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  28244. and noteOff() calls will be added into the buffer.
  28245. Only the section of the buffer whose timestamps are between startSample and
  28246. (startSample + numSamples) will be affected, and any events added will be placed
  28247. between these times.
  28248. If you're going to use this method, you'll need to keep calling it regularly for
  28249. it to work satisfactorily.
  28250. To process a single midi event at a time, use the processNextMidiEvent() method
  28251. instead.
  28252. */
  28253. void processNextMidiBuffer (MidiBuffer& buffer,
  28254. const int startSample,
  28255. const int numSamples,
  28256. const bool injectIndirectEvents);
  28257. /** Registers a listener for callbacks when keys go up or down.
  28258. @see removeListener
  28259. */
  28260. void addListener (MidiKeyboardStateListener* const listener) throw();
  28261. /** Deregisters a listener.
  28262. @see addListener
  28263. */
  28264. void removeListener (MidiKeyboardStateListener* const listener) throw();
  28265. juce_UseDebuggingNewOperator
  28266. private:
  28267. CriticalSection lock;
  28268. uint16 noteStates [128];
  28269. MidiBuffer eventsToAdd;
  28270. Array <MidiKeyboardStateListener*> listeners;
  28271. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  28272. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  28273. MidiKeyboardState (const MidiKeyboardState&);
  28274. MidiKeyboardState& operator= (const MidiKeyboardState&);
  28275. };
  28276. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28277. /*** End of inlined file: juce_MidiKeyboardState.h ***/
  28278. #endif
  28279. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  28280. #endif
  28281. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28282. /*** Start of inlined file: juce_MidiMessageCollector.h ***/
  28283. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28284. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28285. /**
  28286. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  28287. processing by a block-based audio callback.
  28288. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  28289. so it can easily use a midi input or keyboard component as its source.
  28290. @see MidiMessage, MidiInput
  28291. */
  28292. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  28293. public MidiInputCallback
  28294. {
  28295. public:
  28296. /** Creates a MidiMessageCollector. */
  28297. MidiMessageCollector();
  28298. /** Destructor. */
  28299. ~MidiMessageCollector();
  28300. /** Clears any messages from the queue.
  28301. You need to call this method before starting to use the collector, so that
  28302. it knows the correct sample rate to use.
  28303. */
  28304. void reset (double sampleRate);
  28305. /** Takes an incoming real-time message and adds it to the queue.
  28306. The message's timestamp is taken, and it will be ready for retrieval as part
  28307. of the block returned by the next call to removeNextBlockOfMessages().
  28308. This method is fully thread-safe when overlapping calls are made with
  28309. removeNextBlockOfMessages().
  28310. */
  28311. void addMessageToQueue (const MidiMessage& message);
  28312. /** Removes all the pending messages from the queue as a buffer.
  28313. This will also correct the messages' timestamps to make sure they're in
  28314. the range 0 to numSamples - 1.
  28315. This call should be made regularly by something like an audio processing
  28316. callback, because the time that it happens is used in calculating the
  28317. midi event positions.
  28318. This method is fully thread-safe when overlapping calls are made with
  28319. addMessageToQueue().
  28320. */
  28321. void removeNextBlockOfMessages (MidiBuffer& destBuffer, int numSamples);
  28322. /** @internal */
  28323. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  28324. /** @internal */
  28325. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  28326. /** @internal */
  28327. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  28328. juce_UseDebuggingNewOperator
  28329. private:
  28330. double lastCallbackTime;
  28331. CriticalSection midiCallbackLock;
  28332. MidiBuffer incomingMessages;
  28333. double sampleRate;
  28334. MidiMessageCollector (const MidiMessageCollector&);
  28335. MidiMessageCollector& operator= (const MidiMessageCollector&);
  28336. };
  28337. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28338. /*** End of inlined file: juce_MidiMessageCollector.h ***/
  28339. #endif
  28340. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  28341. #endif
  28342. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  28343. /*** Start of inlined file: juce_AudioUnitPluginFormat.h ***/
  28344. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  28345. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  28346. /*** Start of inlined file: juce_AudioPluginFormat.h ***/
  28347. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  28348. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  28349. /*** Start of inlined file: juce_AudioPluginInstance.h ***/
  28350. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  28351. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  28352. /*** Start of inlined file: juce_AudioProcessor.h ***/
  28353. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  28354. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  28355. /*** Start of inlined file: juce_AudioProcessorEditor.h ***/
  28356. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  28357. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  28358. class AudioProcessor;
  28359. /**
  28360. Base class for the component that acts as the GUI for an AudioProcessor.
  28361. Derive your editor component from this class, and create an instance of it
  28362. by overriding the AudioProcessor::createEditor() method.
  28363. @see AudioProcessor, GenericAudioProcessorEditor
  28364. */
  28365. class JUCE_API AudioProcessorEditor : public Component
  28366. {
  28367. protected:
  28368. /** Creates an editor for the specified processor.
  28369. */
  28370. AudioProcessorEditor (AudioProcessor* const owner);
  28371. public:
  28372. /** Destructor. */
  28373. ~AudioProcessorEditor();
  28374. /** Returns a pointer to the processor that this editor represents. */
  28375. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  28376. private:
  28377. AudioProcessor* const owner;
  28378. AudioProcessorEditor (const AudioProcessorEditor&);
  28379. AudioProcessorEditor& operator= (const AudioProcessorEditor&);
  28380. };
  28381. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  28382. /*** End of inlined file: juce_AudioProcessorEditor.h ***/
  28383. /*** Start of inlined file: juce_AudioProcessorListener.h ***/
  28384. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  28385. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  28386. class AudioProcessor;
  28387. /**
  28388. Base class for listeners that want to know about changes to an AudioProcessor.
  28389. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  28390. @see AudioProcessor
  28391. */
  28392. class JUCE_API AudioProcessorListener
  28393. {
  28394. public:
  28395. /** Destructor. */
  28396. virtual ~AudioProcessorListener() {}
  28397. /** Receives a callback when a parameter is changed.
  28398. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  28399. many audio processors will change their parameter during their audio callback.
  28400. This means that not only has your handler code got to be completely thread-safe,
  28401. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  28402. this event on your message thread, use this callback to trigger an AsyncUpdater
  28403. or ChangeBroadcaster which you can respond to on the message thread.
  28404. */
  28405. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  28406. int parameterIndex,
  28407. float newValue) = 0;
  28408. /** Called to indicate that something else in the plugin has changed, like its
  28409. program, number of parameters, etc.
  28410. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  28411. call it during their audio callback. This means that not only has your handler code
  28412. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  28413. blocking. If you need to handle this event on your message thread, use this callback
  28414. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  28415. message thread.
  28416. */
  28417. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  28418. /** Indicates that a parameter change gesture has started.
  28419. E.g. if the user is dragging a slider, this would be called when they first
  28420. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  28421. called when they release it.
  28422. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  28423. call it during their audio callback. This means that not only has your handler code
  28424. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  28425. blocking. If you need to handle this event on your message thread, use this callback
  28426. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  28427. message thread.
  28428. @see audioProcessorParameterChangeGestureEnd
  28429. */
  28430. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  28431. int parameterIndex);
  28432. /** Indicates that a parameter change gesture has finished.
  28433. E.g. if the user is dragging a slider, this would be called when they release
  28434. the mouse button.
  28435. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  28436. call it during their audio callback. This means that not only has your handler code
  28437. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  28438. blocking. If you need to handle this event on your message thread, use this callback
  28439. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  28440. message thread.
  28441. @see audioPluginParameterChangeGestureStart
  28442. */
  28443. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  28444. int parameterIndex);
  28445. };
  28446. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  28447. /*** End of inlined file: juce_AudioProcessorListener.h ***/
  28448. /*** Start of inlined file: juce_AudioPlayHead.h ***/
  28449. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28450. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28451. /**
  28452. A subclass of AudioPlayHead can supply information about the position and
  28453. status of a moving play head during audio playback.
  28454. One of these can be supplied to an AudioProcessor object so that it can find
  28455. out about the position of the audio that it is rendering.
  28456. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  28457. */
  28458. class JUCE_API AudioPlayHead
  28459. {
  28460. protected:
  28461. AudioPlayHead() {}
  28462. public:
  28463. virtual ~AudioPlayHead() {}
  28464. /** Frame rate types. */
  28465. enum FrameRateType
  28466. {
  28467. fps24 = 0,
  28468. fps25 = 1,
  28469. fps2997 = 2,
  28470. fps30 = 3,
  28471. fps2997drop = 4,
  28472. fps30drop = 5,
  28473. fpsUnknown = 99
  28474. };
  28475. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  28476. */
  28477. struct CurrentPositionInfo
  28478. {
  28479. /** The tempo in BPM */
  28480. double bpm;
  28481. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  28482. int timeSigNumerator;
  28483. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  28484. int timeSigDenominator;
  28485. /** The current play position, in seconds from the start of the edit. */
  28486. double timeInSeconds;
  28487. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  28488. double editOriginTime;
  28489. /** The current play position in pulses-per-quarter-note.
  28490. This is the number of quarter notes since the edit start.
  28491. */
  28492. double ppqPosition;
  28493. /** The position of the start of the last bar, in pulses-per-quarter-note.
  28494. This is the number of quarter notes from the start of the edit to the
  28495. start of the current bar.
  28496. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  28497. it's not available, the value will be 0.
  28498. */
  28499. double ppqPositionOfLastBarStart;
  28500. /** The video frame rate, if applicable. */
  28501. FrameRateType frameRate;
  28502. /** True if the transport is currently playing. */
  28503. bool isPlaying;
  28504. /** True if the transport is currently recording.
  28505. (When isRecording is true, then isPlaying will also be true).
  28506. */
  28507. bool isRecording;
  28508. bool operator== (const CurrentPositionInfo& other) const throw();
  28509. bool operator!= (const CurrentPositionInfo& other) const throw();
  28510. void resetToDefault();
  28511. };
  28512. /** Fills-in the given structure with details about the transport's
  28513. position at the start of the current processing block.
  28514. */
  28515. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  28516. };
  28517. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28518. /*** End of inlined file: juce_AudioPlayHead.h ***/
  28519. /**
  28520. Base class for audio processing filters or plugins.
  28521. This is intended to act as a base class of audio filter that is general enough to
  28522. be wrapped as a VST, AU, RTAS, etc, or used internally.
  28523. It is also used by the plugin hosting code as the wrapper around an instance
  28524. of a loaded plugin.
  28525. Derive your filter class from this base class, and if you're building a plugin,
  28526. you should implement a global function called createPluginFilter() which creates
  28527. and returns a new instance of your subclass.
  28528. */
  28529. class JUCE_API AudioProcessor
  28530. {
  28531. protected:
  28532. /** Constructor.
  28533. You can also do your initialisation tasks in the initialiseFilterInfo()
  28534. call, which will be made after this object has been created.
  28535. */
  28536. AudioProcessor();
  28537. public:
  28538. /** Destructor. */
  28539. virtual ~AudioProcessor();
  28540. /** Returns the name of this processor.
  28541. */
  28542. virtual const String getName() const = 0;
  28543. /** Called before playback starts, to let the filter prepare itself.
  28544. The sample rate is the target sample rate, and will remain constant until
  28545. playback stops.
  28546. The estimatedSamplesPerBlock value is a HINT about the typical number of
  28547. samples that will be processed for each callback, but isn't any kind
  28548. of guarantee. The actual block sizes that the host uses may be different
  28549. each time the callback happens, and may be more or less than this value.
  28550. */
  28551. virtual void prepareToPlay (double sampleRate,
  28552. int estimatedSamplesPerBlock) = 0;
  28553. /** Called after playback has stopped, to let the filter free up any resources it
  28554. no longer needs.
  28555. */
  28556. virtual void releaseResources() = 0;
  28557. /** Renders the next block.
  28558. When this method is called, the buffer contains a number of channels which is
  28559. at least as great as the maximum number of input and output channels that
  28560. this filter is using. It will be filled with the filter's input data and
  28561. should be replaced with the filter's output.
  28562. So for example if your filter has 2 input channels and 4 output channels, then
  28563. the buffer will contain 4 channels, the first two being filled with the
  28564. input data. Your filter should read these, do its processing, and replace
  28565. the contents of all 4 channels with its output.
  28566. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  28567. all filled with data, and your filter should overwrite the first 2 of these
  28568. with its output. But be VERY careful not to write anything to the last 3
  28569. channels, as these might be mapped to memory that the host assumes is read-only!
  28570. Note that if you have more outputs than inputs, then only those channels that
  28571. correspond to an input channel are guaranteed to contain sensible data - e.g.
  28572. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  28573. but the last two channels may contain garbage, so you should be careful not to
  28574. let this pass through without being overwritten or cleared.
  28575. Also note that the buffer may have more channels than are strictly necessary,
  28576. but your should only read/write from the ones that your filter is supposed to
  28577. be using.
  28578. The number of samples in these buffers is NOT guaranteed to be the same for every
  28579. callback, and may be more or less than the estimated value given to prepareToPlay().
  28580. Your code must be able to cope with variable-sized blocks, or you're going to get
  28581. clicks and crashes!
  28582. If the filter is receiving a midi input, then the midiMessages array will be filled
  28583. with the midi messages for this block. Each message's timestamp will indicate the
  28584. message's time, as a number of samples from the start of the block.
  28585. Any messages left in the midi buffer when this method has finished are assumed to
  28586. be the filter's midi output. This means that your filter should be careful to
  28587. clear any incoming messages from the array if it doesn't want them to be passed-on.
  28588. Be very careful about what you do in this callback - it's going to be called by
  28589. the audio thread, so any kind of interaction with the UI is absolutely
  28590. out of the question. If you change a parameter in here and need to tell your UI to
  28591. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  28592. the UI components register as listeners, and then call sendChangeMessage() inside the
  28593. processBlock() method to send out an asynchronous message. You could also use
  28594. the AsyncUpdater class in a similar way.
  28595. */
  28596. virtual void processBlock (AudioSampleBuffer& buffer,
  28597. MidiBuffer& midiMessages) = 0;
  28598. /** Returns the current AudioPlayHead object that should be used to find
  28599. out the state and position of the playhead.
  28600. You can call this from your processBlock() method, and use the AudioPlayHead
  28601. object to get the details about the time of the start of the block currently
  28602. being processed.
  28603. If the host hasn't supplied a playhead object, this will return 0.
  28604. */
  28605. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  28606. /** Returns the current sample rate.
  28607. This can be called from your processBlock() method - it's not guaranteed
  28608. to be valid at any other time, and may return 0 if it's unknown.
  28609. */
  28610. double getSampleRate() const throw() { return sampleRate; }
  28611. /** Returns the current typical block size that is being used.
  28612. This can be called from your processBlock() method - it's not guaranteed
  28613. to be valid at any other time.
  28614. Remember it's not the ONLY block size that may be used when calling
  28615. processBlock, it's just the normal one. The actual block sizes used may be
  28616. larger or smaller than this, and will vary between successive calls.
  28617. */
  28618. int getBlockSize() const throw() { return blockSize; }
  28619. /** Returns the number of input channels that the host will be sending the filter.
  28620. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  28621. number of channels that your filter would prefer to have, and this method lets
  28622. you know how many the host is actually using.
  28623. Note that this method is only valid during or after the prepareToPlay()
  28624. method call. Until that point, the number of channels will be unknown.
  28625. */
  28626. int getNumInputChannels() const throw() { return numInputChannels; }
  28627. /** Returns the number of output channels that the host will be sending the filter.
  28628. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  28629. number of channels that your filter would prefer to have, and this method lets
  28630. you know how many the host is actually using.
  28631. Note that this method is only valid during or after the prepareToPlay()
  28632. method call. Until that point, the number of channels will be unknown.
  28633. */
  28634. int getNumOutputChannels() const throw() { return numOutputChannels; }
  28635. /** Returns the name of one of the input channels, as returned by the host.
  28636. The host might not supply very useful names for channels, and this might be
  28637. something like "1", "2", "left", "right", etc.
  28638. */
  28639. virtual const String getInputChannelName (const int channelIndex) const = 0;
  28640. /** Returns the name of one of the output channels, as returned by the host.
  28641. The host might not supply very useful names for channels, and this might be
  28642. something like "1", "2", "left", "right", etc.
  28643. */
  28644. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  28645. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  28646. virtual bool isInputChannelStereoPair (int index) const = 0;
  28647. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  28648. virtual bool isOutputChannelStereoPair (int index) const = 0;
  28649. /** This returns the number of samples delay that the filter imposes on the audio
  28650. passing through it.
  28651. The host will call this to find the latency - the filter itself should set this value
  28652. by calling setLatencySamples() as soon as it can during its initialisation.
  28653. */
  28654. int getLatencySamples() const throw() { return latencySamples; }
  28655. /** The filter should call this to set the number of samples delay that it introduces.
  28656. The filter should call this as soon as it can during initialisation, and can call it
  28657. later if the value changes.
  28658. */
  28659. void setLatencySamples (const int newLatency);
  28660. /** Returns true if the processor wants midi messages. */
  28661. virtual bool acceptsMidi() const = 0;
  28662. /** Returns true if the processor produces midi messages. */
  28663. virtual bool producesMidi() const = 0;
  28664. /** This returns a critical section that will automatically be locked while the host
  28665. is calling the processBlock() method.
  28666. Use it from your UI or other threads to lock access to variables that are used
  28667. by the process callback, but obviously be careful not to keep it locked for
  28668. too long, because that could cause stuttering playback. If you need to do something
  28669. that'll take a long time and need the processing to stop while it happens, use the
  28670. suspendProcessing() method instead.
  28671. @see suspendProcessing
  28672. */
  28673. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  28674. /** Enables and disables the processing callback.
  28675. If you need to do something time-consuming on a thread and would like to make sure
  28676. the audio processing callback doesn't happen until you've finished, use this
  28677. to disable the callback and re-enable it again afterwards.
  28678. E.g.
  28679. @code
  28680. void loadNewPatch()
  28681. {
  28682. suspendProcessing (true);
  28683. ..do something that takes ages..
  28684. suspendProcessing (false);
  28685. }
  28686. @endcode
  28687. If the host tries to make an audio callback while processing is suspended, the
  28688. filter will return an empty buffer, but won't block the audio thread like it would
  28689. do if you use the getCallbackLock() critical section to synchronise access.
  28690. If you're going to use this, your processBlock() method must call isSuspended() and
  28691. check whether it's suspended or not. If it is, then it should skip doing any real
  28692. processing, either emitting silence or passing the input through unchanged.
  28693. @see getCallbackLock
  28694. */
  28695. void suspendProcessing (const bool shouldBeSuspended);
  28696. /** Returns true if processing is currently suspended.
  28697. @see suspendProcessing
  28698. */
  28699. bool isSuspended() const throw() { return suspended; }
  28700. /** A plugin can override this to be told when it should reset any playing voices.
  28701. The default implementation does nothing, but a host may call this to tell the
  28702. plugin that it should stop any tails or sounds that have been left running.
  28703. */
  28704. virtual void reset();
  28705. /** Returns true if the processor is being run in an offline mode for rendering.
  28706. If the processor is being run live on realtime signals, this returns false.
  28707. If the mode is unknown, this will assume it's realtime and return false.
  28708. This value may be unreliable until the prepareToPlay() method has been called,
  28709. and could change each time prepareToPlay() is called.
  28710. @see setNonRealtime()
  28711. */
  28712. bool isNonRealtime() const throw() { return nonRealtime; }
  28713. /** Called by the host to tell this processor whether it's being used in a non-realime
  28714. capacity for offline rendering or bouncing.
  28715. Whatever value is passed-in will be
  28716. */
  28717. void setNonRealtime (const bool isNonRealtime) throw();
  28718. /** Creates the filter's UI.
  28719. This can return 0 if you want a UI-less filter, in which case the host may create
  28720. a generic UI that lets the user twiddle the parameters directly.
  28721. If you do want to pass back a component, the component should be created and set to
  28722. the correct size before returning it.
  28723. Remember not to do anything silly like allowing your filter to keep a pointer to
  28724. the component that gets created - it could be deleted later without any warning, which
  28725. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  28726. The correct way to handle the connection between an editor component and its
  28727. filter is to use something like a ChangeBroadcaster so that the editor can
  28728. register itself as a listener, and be told when a change occurs. This lets them
  28729. safely unregister themselves when they are deleted.
  28730. Here are a few things to bear in mind when writing an editor:
  28731. - Initially there won't be an editor, until the user opens one, or they might
  28732. not open one at all. Your filter mustn't rely on it being there.
  28733. - An editor object may be deleted and a replacement one created again at any time.
  28734. - It's safe to assume that an editor will be deleted before its filter.
  28735. */
  28736. virtual AudioProcessorEditor* createEditor() = 0;
  28737. /** Returns the active editor, if there is one.
  28738. Bear in mind this can return 0, even if an editor has previously been
  28739. opened.
  28740. */
  28741. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  28742. /** Returns the active editor, or if there isn't one, it will create one.
  28743. This may call createEditor() internally to create the component.
  28744. */
  28745. AudioProcessorEditor* createEditorIfNeeded();
  28746. /** This must return the correct value immediately after the object has been
  28747. created, and mustn't change the number of parameters later.
  28748. */
  28749. virtual int getNumParameters() = 0;
  28750. /** Returns the name of a particular parameter. */
  28751. virtual const String getParameterName (int parameterIndex) = 0;
  28752. /** Called by the host to find out the value of one of the filter's parameters.
  28753. The host will expect the value returned to be between 0 and 1.0.
  28754. This could be called quite frequently, so try to make your code efficient.
  28755. It's also likely to be called by non-UI threads, so the code in here should
  28756. be thread-aware.
  28757. */
  28758. virtual float getParameter (int parameterIndex) = 0;
  28759. /** Returns the value of a parameter as a text string. */
  28760. virtual const String getParameterText (int parameterIndex) = 0;
  28761. /** The host will call this method to change the value of one of the filter's parameters.
  28762. The host may call this at any time, including during the audio processing
  28763. callback, so the filter has to process this very fast and avoid blocking.
  28764. If you want to set the value of a parameter internally, e.g. from your
  28765. editor component, then don't call this directly - instead, use the
  28766. setParameterNotifyingHost() method, which will also send a message to
  28767. the host telling it about the change. If the message isn't sent, the host
  28768. won't be able to automate your parameters properly.
  28769. The value passed will be between 0 and 1.0.
  28770. */
  28771. virtual void setParameter (int parameterIndex,
  28772. float newValue) = 0;
  28773. /** Your filter can call this when it needs to change one of its parameters.
  28774. This could happen when the editor or some other internal operation changes
  28775. a parameter. This method will call the setParameter() method to change the
  28776. value, and will then send a message to the host telling it about the change.
  28777. Note that to make sure the host correctly handles automation, you should call
  28778. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  28779. tell the host when the user has started and stopped changing the parameter.
  28780. */
  28781. void setParameterNotifyingHost (int parameterIndex,
  28782. float newValue);
  28783. /** Returns true if the host can automate this parameter.
  28784. By default, this returns true for all parameters.
  28785. */
  28786. virtual bool isParameterAutomatable (int parameterIndex) const;
  28787. /** Should return true if this parameter is a "meta" parameter.
  28788. A meta-parameter is a parameter that changes other params. It is used
  28789. by some hosts (e.g. AudioUnit hosts).
  28790. By default this returns false.
  28791. */
  28792. virtual bool isMetaParameter (int parameterIndex) const;
  28793. /** Sends a signal to the host to tell it that the user is about to start changing this
  28794. parameter.
  28795. This allows the host to know when a parameter is actively being held by the user, and
  28796. it may use this information to help it record automation.
  28797. If you call this, it must be matched by a later call to endParameterChangeGesture().
  28798. */
  28799. void beginParameterChangeGesture (int parameterIndex);
  28800. /** Tells the host that the user has finished changing this parameter.
  28801. This allows the host to know when a parameter is actively being held by the user, and
  28802. it may use this information to help it record automation.
  28803. A call to this method must follow a call to beginParameterChangeGesture().
  28804. */
  28805. void endParameterChangeGesture (int parameterIndex);
  28806. /** The filter can call this when something (apart from a parameter value) has changed.
  28807. It sends a hint to the host that something like the program, number of parameters,
  28808. etc, has changed, and that it should update itself.
  28809. */
  28810. void updateHostDisplay();
  28811. /** Returns the number of preset programs the filter supports.
  28812. The value returned must be valid as soon as this object is created, and
  28813. must not change over its lifetime.
  28814. This value shouldn't be less than 1.
  28815. */
  28816. virtual int getNumPrograms() = 0;
  28817. /** Returns the number of the currently active program.
  28818. */
  28819. virtual int getCurrentProgram() = 0;
  28820. /** Called by the host to change the current program.
  28821. */
  28822. virtual void setCurrentProgram (int index) = 0;
  28823. /** Must return the name of a given program. */
  28824. virtual const String getProgramName (int index) = 0;
  28825. /** Called by the host to rename a program.
  28826. */
  28827. virtual void changeProgramName (int index, const String& newName) = 0;
  28828. /** The host will call this method when it wants to save the filter's internal state.
  28829. This must copy any info about the filter's state into the block of memory provided,
  28830. so that the host can store this and later restore it using setStateInformation().
  28831. Note that there's also a getCurrentProgramStateInformation() method, which only
  28832. stores the current program, not the state of the entire filter.
  28833. See also the helper function copyXmlToBinary() for storing settings as XML.
  28834. @see getCurrentProgramStateInformation
  28835. */
  28836. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  28837. /** The host will call this method if it wants to save the state of just the filter's
  28838. current program.
  28839. Unlike getStateInformation, this should only return the current program's state.
  28840. Not all hosts support this, and if you don't implement it, the base class
  28841. method just calls getStateInformation() instead. If you do implement it, be
  28842. sure to also implement getCurrentProgramStateInformation.
  28843. @see getStateInformation, setCurrentProgramStateInformation
  28844. */
  28845. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  28846. /** This must restore the filter's state from a block of data previously created
  28847. using getStateInformation().
  28848. Note that there's also a setCurrentProgramStateInformation() method, which tries
  28849. to restore just the current program, not the state of the entire filter.
  28850. See also the helper function getXmlFromBinary() for loading settings as XML.
  28851. @see setCurrentProgramStateInformation
  28852. */
  28853. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  28854. /** The host will call this method if it wants to restore the state of just the filter's
  28855. current program.
  28856. Not all hosts support this, and if you don't implement it, the base class
  28857. method just calls setStateInformation() instead. If you do implement it, be
  28858. sure to also implement getCurrentProgramStateInformation.
  28859. @see setStateInformation, getCurrentProgramStateInformation
  28860. */
  28861. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  28862. /** Adds a listener that will be called when an aspect of this processor changes. */
  28863. void addListener (AudioProcessorListener* const newListener) throw();
  28864. /** Removes a previously added listener. */
  28865. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  28866. /** Not for public use - this is called before deleting an editor component. */
  28867. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  28868. /** Not for public use - this is called to initialise the processor. */
  28869. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  28870. /** Not for public use - this is called to initialise the processor before playing. */
  28871. void setPlayConfigDetails (const int numIns, const int numOuts,
  28872. const double sampleRate,
  28873. const int blockSize) throw();
  28874. juce_UseDebuggingNewOperator
  28875. protected:
  28876. /** Helper function that just converts an xml element into a binary blob.
  28877. Use this in your filter's getStateInformation() method if you want to
  28878. store its state as xml.
  28879. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  28880. from a binary blob.
  28881. */
  28882. static void copyXmlToBinary (const XmlElement& xml,
  28883. JUCE_NAMESPACE::MemoryBlock& destData);
  28884. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  28885. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  28886. an XmlElement object that the caller must delete when no longer needed.
  28887. */
  28888. static XmlElement* getXmlFromBinary (const void* data,
  28889. const int sizeInBytes);
  28890. /** @internal */
  28891. AudioPlayHead* playHead;
  28892. /** @internal */
  28893. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  28894. private:
  28895. Array <AudioProcessorListener*> listeners;
  28896. AudioProcessorEditor* activeEditor;
  28897. double sampleRate;
  28898. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  28899. bool suspended, nonRealtime;
  28900. CriticalSection callbackLock, listenerLock;
  28901. #if JUCE_DEBUG
  28902. BigInteger changingParams;
  28903. #endif
  28904. AudioProcessor (const AudioProcessor&);
  28905. AudioProcessor& operator= (const AudioProcessor&);
  28906. };
  28907. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  28908. /*** End of inlined file: juce_AudioProcessor.h ***/
  28909. /*** Start of inlined file: juce_PluginDescription.h ***/
  28910. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  28911. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  28912. /**
  28913. A small class to represent some facts about a particular type of plugin.
  28914. This class is for storing and managing the details about a plugin without
  28915. actually having to load an instance of it.
  28916. A KnownPluginList contains a list of PluginDescription objects.
  28917. @see KnownPluginList
  28918. */
  28919. class JUCE_API PluginDescription
  28920. {
  28921. public:
  28922. PluginDescription() throw();
  28923. PluginDescription (const PluginDescription& other) throw();
  28924. PluginDescription& operator= (const PluginDescription& other) throw();
  28925. ~PluginDescription() throw();
  28926. /** The name of the plugin. */
  28927. String name;
  28928. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  28929. */
  28930. String pluginFormatName;
  28931. /** A category, such as "Dynamics", "Reverbs", etc.
  28932. */
  28933. String category;
  28934. /** The manufacturer. */
  28935. String manufacturerName;
  28936. /** The version. This string doesn't have any particular format. */
  28937. String version;
  28938. /** Either the file containing the plugin module, or some other unique way
  28939. of identifying it.
  28940. E.g. for an AU, this would be an ID string that the component manager
  28941. could use to retrieve the plugin. For a VST, it's the file path.
  28942. */
  28943. String fileOrIdentifier;
  28944. /** The last time the plugin file was changed.
  28945. This is handy when scanning for new or changed plugins.
  28946. */
  28947. Time lastFileModTime;
  28948. /** A unique ID for the plugin.
  28949. Note that this might not be unique between formats, e.g. a VST and some
  28950. other format might actually have the same id.
  28951. @see createIdentifierString
  28952. */
  28953. int uid;
  28954. /** True if the plugin identifies itself as a synthesiser. */
  28955. bool isInstrument;
  28956. /** The number of inputs. */
  28957. int numInputChannels;
  28958. /** The number of outputs. */
  28959. int numOutputChannels;
  28960. /** Returns true if the two descriptions refer the the same plugin.
  28961. This isn't quite as simple as them just having the same file (because of
  28962. shell plugins).
  28963. */
  28964. bool isDuplicateOf (const PluginDescription& other) const;
  28965. /** Returns a string that can be saved and used to uniquely identify the
  28966. plugin again.
  28967. This contains less info than the XML encoding, and is independent of the
  28968. plugin's file location, so can be used to store a plugin ID for use
  28969. across different machines.
  28970. */
  28971. const String createIdentifierString() const throw();
  28972. /** Creates an XML object containing these details.
  28973. @see loadFromXml
  28974. */
  28975. XmlElement* createXml() const;
  28976. /** Reloads the info in this structure from an XML record that was previously
  28977. saved with createXML().
  28978. Returns true if the XML was a valid plugin description.
  28979. */
  28980. bool loadFromXml (const XmlElement& xml);
  28981. juce_UseDebuggingNewOperator
  28982. };
  28983. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  28984. /*** End of inlined file: juce_PluginDescription.h ***/
  28985. /**
  28986. Base class for an active instance of a plugin.
  28987. This derives from the AudioProcessor class, and adds some extra functionality
  28988. that helps when wrapping dynamically loaded plugins.
  28989. @see AudioProcessor, AudioPluginFormat
  28990. */
  28991. class JUCE_API AudioPluginInstance : public AudioProcessor
  28992. {
  28993. public:
  28994. /** Destructor.
  28995. Make sure that you delete any UI components that belong to this plugin before
  28996. deleting the plugin.
  28997. */
  28998. virtual ~AudioPluginInstance();
  28999. /** Fills-in the appropriate parts of this plugin description object.
  29000. */
  29001. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  29002. juce_UseDebuggingNewOperator
  29003. protected:
  29004. AudioPluginInstance();
  29005. AudioPluginInstance (const AudioPluginInstance&);
  29006. AudioPluginInstance& operator= (const AudioPluginInstance&);
  29007. };
  29008. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  29009. /*** End of inlined file: juce_AudioPluginInstance.h ***/
  29010. class PluginDescription;
  29011. /**
  29012. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  29013. Use the static getNumFormats() and getFormat() calls to find the types
  29014. of format that are available.
  29015. */
  29016. class JUCE_API AudioPluginFormat
  29017. {
  29018. public:
  29019. /** Destructor. */
  29020. virtual ~AudioPluginFormat();
  29021. /** Returns the format name.
  29022. E.g. "VST", "AudioUnit", etc.
  29023. */
  29024. virtual const String getName() const = 0;
  29025. /** This tries to create descriptions for all the plugin types available in
  29026. a binary module file.
  29027. The file will be some kind of DLL or bundle.
  29028. Normally there will only be one type returned, but some plugins
  29029. (e.g. VST shells) can use a single DLL to create a set of different plugin
  29030. subtypes, so in that case, each subtype is returned as a separate object.
  29031. */
  29032. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  29033. const String& fileOrIdentifier) = 0;
  29034. /** Tries to recreate a type from a previously generated PluginDescription.
  29035. @see PluginDescription::createInstance
  29036. */
  29037. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  29038. /** Should do a quick check to see if this file or directory might be a plugin of
  29039. this format.
  29040. This is for searching for potential files, so it shouldn't actually try to
  29041. load the plugin or do anything time-consuming.
  29042. */
  29043. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  29044. /** Returns a readable version of the name of the plugin that this identifier refers to.
  29045. */
  29046. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  29047. /** Checks whether this plugin could possibly be loaded.
  29048. It doesn't actually need to load it, just to check whether the file or component
  29049. still exists.
  29050. */
  29051. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  29052. /** Searches a suggested set of directories for any plugins in this format.
  29053. The path might be ignored, e.g. by AUs, which are found by the OS rather
  29054. than manually.
  29055. */
  29056. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  29057. bool recursive) = 0;
  29058. /** Returns the typical places to look for this kind of plugin.
  29059. Note that if this returns no paths, it means that the format can't be scanned-for
  29060. (i.e. it's an internal format that doesn't live in files)
  29061. */
  29062. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  29063. juce_UseDebuggingNewOperator
  29064. protected:
  29065. AudioPluginFormat() throw();
  29066. AudioPluginFormat (const AudioPluginFormat&);
  29067. AudioPluginFormat& operator= (const AudioPluginFormat&);
  29068. };
  29069. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  29070. /*** End of inlined file: juce_AudioPluginFormat.h ***/
  29071. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  29072. /**
  29073. Implements a plugin format manager for AudioUnits.
  29074. */
  29075. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  29076. {
  29077. public:
  29078. AudioUnitPluginFormat();
  29079. ~AudioUnitPluginFormat();
  29080. const String getName() const { return "AudioUnit"; }
  29081. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29082. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29083. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29084. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  29085. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  29086. bool doesPluginStillExist (const PluginDescription& desc);
  29087. const FileSearchPath getDefaultLocationsToSearch();
  29088. juce_UseDebuggingNewOperator
  29089. private:
  29090. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  29091. AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  29092. };
  29093. #endif
  29094. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  29095. /*** End of inlined file: juce_AudioUnitPluginFormat.h ***/
  29096. #endif
  29097. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29098. /*** Start of inlined file: juce_DirectXPluginFormat.h ***/
  29099. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29100. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29101. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  29102. // Sorry, this file is just a placeholder at the moment!...
  29103. /**
  29104. Implements a plugin format manager for DirectX plugins.
  29105. */
  29106. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  29107. {
  29108. public:
  29109. DirectXPluginFormat();
  29110. ~DirectXPluginFormat();
  29111. const String getName() const { return "DirectX"; }
  29112. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29113. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29114. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29115. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  29116. const FileSearchPath getDefaultLocationsToSearch();
  29117. juce_UseDebuggingNewOperator
  29118. private:
  29119. DirectXPluginFormat (const DirectXPluginFormat&);
  29120. DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  29121. };
  29122. #endif
  29123. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29124. /*** End of inlined file: juce_DirectXPluginFormat.h ***/
  29125. #endif
  29126. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29127. /*** Start of inlined file: juce_LADSPAPluginFormat.h ***/
  29128. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29129. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29130. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  29131. // Sorry, this file is just a placeholder at the moment!...
  29132. /**
  29133. Implements a plugin format manager for DirectX plugins.
  29134. */
  29135. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  29136. {
  29137. public:
  29138. LADSPAPluginFormat();
  29139. ~LADSPAPluginFormat();
  29140. const String getName() const { return "LADSPA"; }
  29141. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29142. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29143. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29144. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  29145. const FileSearchPath getDefaultLocationsToSearch();
  29146. juce_UseDebuggingNewOperator
  29147. private:
  29148. LADSPAPluginFormat (const LADSPAPluginFormat&);
  29149. LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  29150. };
  29151. #endif
  29152. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29153. /*** End of inlined file: juce_LADSPAPluginFormat.h ***/
  29154. #endif
  29155. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29156. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  29157. #ifdef __aeffect__
  29158. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29159. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29160. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  29161. events to the list.
  29162. This is used by both the VST hosting code and the plugin wrapper.
  29163. */
  29164. class VSTMidiEventList
  29165. {
  29166. public:
  29167. VSTMidiEventList()
  29168. : numEventsUsed (0), numEventsAllocated (0)
  29169. {
  29170. }
  29171. ~VSTMidiEventList()
  29172. {
  29173. freeEvents();
  29174. }
  29175. void clear()
  29176. {
  29177. numEventsUsed = 0;
  29178. if (events != 0)
  29179. events->numEvents = 0;
  29180. }
  29181. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  29182. {
  29183. ensureSize (numEventsUsed + 1);
  29184. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  29185. events->numEvents = ++numEventsUsed;
  29186. if (numBytes <= 4)
  29187. {
  29188. if (e->type == kVstSysExType)
  29189. {
  29190. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  29191. e->type = kVstMidiType;
  29192. e->byteSize = sizeof (VstMidiEvent);
  29193. e->noteLength = 0;
  29194. e->noteOffset = 0;
  29195. e->detune = 0;
  29196. e->noteOffVelocity = 0;
  29197. }
  29198. e->deltaFrames = frameOffset;
  29199. memcpy (e->midiData, midiData, numBytes);
  29200. }
  29201. else
  29202. {
  29203. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  29204. if (se->type == kVstSysExType)
  29205. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  29206. else
  29207. se->sysexDump = (char*) juce_malloc (numBytes);
  29208. memcpy (se->sysexDump, midiData, numBytes);
  29209. se->type = kVstSysExType;
  29210. se->byteSize = sizeof (VstMidiSysexEvent);
  29211. se->deltaFrames = frameOffset;
  29212. se->flags = 0;
  29213. se->dumpBytes = numBytes;
  29214. se->resvd1 = 0;
  29215. se->resvd2 = 0;
  29216. }
  29217. }
  29218. // Handy method to pull the events out of an event buffer supplied by the host
  29219. // or plugin.
  29220. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  29221. {
  29222. for (int i = 0; i < events->numEvents; ++i)
  29223. {
  29224. const VstEvent* const e = events->events[i];
  29225. if (e != 0)
  29226. {
  29227. if (e->type == kVstMidiType)
  29228. {
  29229. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  29230. 4, e->deltaFrames);
  29231. }
  29232. else if (e->type == kVstSysExType)
  29233. {
  29234. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  29235. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  29236. e->deltaFrames);
  29237. }
  29238. }
  29239. }
  29240. }
  29241. void ensureSize (int numEventsNeeded)
  29242. {
  29243. if (numEventsNeeded > numEventsAllocated)
  29244. {
  29245. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  29246. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  29247. if (events == 0)
  29248. events.calloc (size, 1);
  29249. else
  29250. events.realloc (size, 1);
  29251. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  29252. {
  29253. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  29254. (int) sizeof (VstMidiSysexEvent)));
  29255. e->type = kVstMidiType;
  29256. e->byteSize = sizeof (VstMidiEvent);
  29257. events->events[i] = (VstEvent*) e;
  29258. }
  29259. numEventsAllocated = numEventsNeeded;
  29260. }
  29261. }
  29262. void freeEvents()
  29263. {
  29264. if (events != 0)
  29265. {
  29266. for (int i = numEventsAllocated; --i >= 0;)
  29267. {
  29268. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  29269. if (e->type == kVstSysExType)
  29270. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  29271. juce_free (e);
  29272. }
  29273. events.free();
  29274. numEventsUsed = 0;
  29275. numEventsAllocated = 0;
  29276. }
  29277. }
  29278. HeapBlock <VstEvents> events;
  29279. private:
  29280. int numEventsUsed, numEventsAllocated;
  29281. };
  29282. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29283. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29284. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  29285. #endif
  29286. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29287. /*** Start of inlined file: juce_VSTPluginFormat.h ***/
  29288. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29289. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29290. #if JUCE_PLUGINHOST_VST
  29291. /**
  29292. Implements a plugin format manager for VSTs.
  29293. */
  29294. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  29295. {
  29296. public:
  29297. VSTPluginFormat();
  29298. ~VSTPluginFormat();
  29299. const String getName() const { return "VST"; }
  29300. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29301. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29302. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29303. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  29304. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  29305. bool doesPluginStillExist (const PluginDescription& desc);
  29306. const FileSearchPath getDefaultLocationsToSearch();
  29307. juce_UseDebuggingNewOperator
  29308. private:
  29309. VSTPluginFormat (const VSTPluginFormat&);
  29310. VSTPluginFormat& operator= (const VSTPluginFormat&);
  29311. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  29312. };
  29313. #endif
  29314. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29315. /*** End of inlined file: juce_VSTPluginFormat.h ***/
  29316. #endif
  29317. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  29318. #endif
  29319. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29320. /*** Start of inlined file: juce_AudioPluginFormatManager.h ***/
  29321. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29322. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29323. /**
  29324. This maintains a list of known AudioPluginFormats.
  29325. @see AudioPluginFormat
  29326. */
  29327. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  29328. {
  29329. public:
  29330. AudioPluginFormatManager() throw();
  29331. /** Destructor. */
  29332. ~AudioPluginFormatManager() throw();
  29333. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  29334. /** Adds any formats that it knows about, e.g. VST.
  29335. */
  29336. void addDefaultFormats();
  29337. /** Returns the number of types of format that are available.
  29338. Use getFormat() to get one of them.
  29339. */
  29340. int getNumFormats() throw();
  29341. /** Returns one of the available formats.
  29342. @see getNumFormats
  29343. */
  29344. AudioPluginFormat* getFormat (const int index) throw();
  29345. /** Adds a format to the list.
  29346. The object passed in will be owned and deleted by the manager.
  29347. */
  29348. void addFormat (AudioPluginFormat* const format) throw();
  29349. /** Tries to load the type for this description, by trying all the formats
  29350. that this manager knows about.
  29351. The caller is responsible for deleting the object that is returned.
  29352. If it can't load the plugin, it returns 0 and leaves a message in the
  29353. errorMessage string.
  29354. */
  29355. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  29356. String& errorMessage) const;
  29357. /** Checks that the file or component for this plugin actually still exists.
  29358. (This won't try to load the plugin)
  29359. */
  29360. bool doesPluginStillExist (const PluginDescription& description) const;
  29361. juce_UseDebuggingNewOperator
  29362. private:
  29363. OwnedArray <AudioPluginFormat> formats;
  29364. AudioPluginFormatManager (const AudioPluginFormatManager&);
  29365. AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  29366. };
  29367. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29368. /*** End of inlined file: juce_AudioPluginFormatManager.h ***/
  29369. #endif
  29370. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  29371. #endif
  29372. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29373. /*** Start of inlined file: juce_KnownPluginList.h ***/
  29374. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29375. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29376. /**
  29377. Manages a list of plugin types.
  29378. This can be easily edited, saved and loaded, and used to create instances of
  29379. the plugin types in it.
  29380. @see PluginListComponent
  29381. */
  29382. class JUCE_API KnownPluginList : public ChangeBroadcaster
  29383. {
  29384. public:
  29385. /** Creates an empty list.
  29386. */
  29387. KnownPluginList();
  29388. /** Destructor. */
  29389. ~KnownPluginList();
  29390. /** Clears the list. */
  29391. void clear();
  29392. /** Returns the number of types currently in the list.
  29393. @see getType
  29394. */
  29395. int getNumTypes() const throw() { return types.size(); }
  29396. /** Returns one of the types.
  29397. @see getNumTypes
  29398. */
  29399. PluginDescription* getType (int index) const throw() { return types [index]; }
  29400. /** Looks for a type in the list which comes from this file.
  29401. */
  29402. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const throw();
  29403. /** Looks for a type in the list which matches a plugin type ID.
  29404. The identifierString parameter must have been created by
  29405. PluginDescription::createIdentifierString().
  29406. */
  29407. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  29408. /** Adds a type manually from its description. */
  29409. bool addType (const PluginDescription& type);
  29410. /** Removes a type. */
  29411. void removeType (int index) throw();
  29412. /** Looks for all types that can be loaded from a given file, and adds them
  29413. to the list.
  29414. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  29415. re-tested if it's not already in the list, or if the file's modification
  29416. time has changed since the list was created. If dontRescanIfAlreadyInList is
  29417. false, the file will always be reloaded and tested.
  29418. Returns true if any new types were added, and all the types found in this
  29419. file (even if it was already known and hasn't been re-scanned) get returned
  29420. in the array.
  29421. */
  29422. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  29423. bool dontRescanIfAlreadyInList,
  29424. OwnedArray <PluginDescription>& typesFound,
  29425. AudioPluginFormat& formatToUse);
  29426. /** Returns true if the specified file is already known about and if it
  29427. hasn't been modified since our entry was created.
  29428. */
  29429. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const throw();
  29430. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  29431. If any types are found in the files, their descriptions are returned in the array.
  29432. */
  29433. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  29434. OwnedArray <PluginDescription>& typesFound);
  29435. /** Sort methods used to change the order of the plugins in the list.
  29436. */
  29437. enum SortMethod
  29438. {
  29439. defaultOrder = 0,
  29440. sortAlphabetically,
  29441. sortByCategory,
  29442. sortByManufacturer,
  29443. sortByFileSystemLocation
  29444. };
  29445. /** Adds all the plugin types to a popup menu so that the user can select one.
  29446. Depending on the sort method, it may add sub-menus for categories,
  29447. manufacturers, etc.
  29448. Use getIndexChosenByMenu() to find out the type that was chosen.
  29449. */
  29450. void addToMenu (PopupMenu& menu,
  29451. const SortMethod sortMethod) const;
  29452. /** Converts a menu item index that has been chosen into its index in this list.
  29453. Returns -1 if it's not an ID that was used.
  29454. @see addToMenu
  29455. */
  29456. int getIndexChosenByMenu (int menuResultCode) const;
  29457. /** Sorts the list. */
  29458. void sort (const SortMethod method);
  29459. /** Creates some XML that can be used to store the state of this list.
  29460. */
  29461. XmlElement* createXml() const;
  29462. /** Recreates the state of this list from its stored XML format.
  29463. */
  29464. void recreateFromXml (const XmlElement& xml);
  29465. juce_UseDebuggingNewOperator
  29466. private:
  29467. OwnedArray <PluginDescription> types;
  29468. KnownPluginList (const KnownPluginList&);
  29469. KnownPluginList& operator= (const KnownPluginList&);
  29470. };
  29471. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29472. /*** End of inlined file: juce_KnownPluginList.h ***/
  29473. #endif
  29474. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  29475. #endif
  29476. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29477. /*** Start of inlined file: juce_PluginDirectoryScanner.h ***/
  29478. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29479. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29480. /**
  29481. Scans a directory for plugins, and adds them to a KnownPluginList.
  29482. To use one of these, create it and call scanNextFile() repeatedly, until
  29483. it returns false.
  29484. */
  29485. class JUCE_API PluginDirectoryScanner
  29486. {
  29487. public:
  29488. /**
  29489. Creates a scanner.
  29490. @param listToAddResultsTo this will get the new types added to it.
  29491. @param formatToLookFor this is the type of format that you want to look for
  29492. @param directoriesToSearch the path to search
  29493. @param searchRecursively true to search recursively
  29494. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  29495. be used as a file to store the names of any plugins
  29496. that crash during initialisation. If there are
  29497. any plugins listed in it, then these will always
  29498. be scanned after all other possible files have
  29499. been tried - in this way, even if there's a few
  29500. dodgy plugins in your path, then a couple of rescans
  29501. will still manage to find all the proper plugins.
  29502. It's probably best to choose a file in the user's
  29503. application data directory (alongside your app's
  29504. settings file) for this. The file format it uses
  29505. is just a list of filenames of the modules that
  29506. failed.
  29507. */
  29508. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  29509. AudioPluginFormat& formatToLookFor,
  29510. FileSearchPath directoriesToSearch,
  29511. bool searchRecursively,
  29512. const File& deadMansPedalFile);
  29513. /** Destructor. */
  29514. ~PluginDirectoryScanner();
  29515. /** Tries the next likely-looking file.
  29516. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  29517. re-tested if it's not already in the list, or if the file's modification
  29518. time has changed since the list was created. If dontRescanIfAlreadyInList is
  29519. false, the file will always be reloaded and tested.
  29520. Returns false when there are no more files to try.
  29521. */
  29522. bool scanNextFile (bool dontRescanIfAlreadyInList);
  29523. /** Returns the description of the plugin that will be scanned during the next
  29524. call to scanNextFile().
  29525. This is handy if you want to show the user which file is currently getting
  29526. scanned.
  29527. */
  29528. const String getNextPluginFileThatWillBeScanned() const throw();
  29529. /** Returns the estimated progress, between 0 and 1.
  29530. */
  29531. float getProgress() const { return progress; }
  29532. /** This returns a list of all the filenames of things that looked like being
  29533. a plugin file, but which failed to open for some reason.
  29534. */
  29535. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  29536. juce_UseDebuggingNewOperator
  29537. private:
  29538. KnownPluginList& list;
  29539. AudioPluginFormat& format;
  29540. StringArray filesOrIdentifiersToScan;
  29541. File deadMansPedalFile;
  29542. StringArray failedFiles;
  29543. int nextIndex;
  29544. float progress;
  29545. const StringArray getDeadMansPedalFile() throw();
  29546. void setDeadMansPedalFile (const StringArray& newContents) throw();
  29547. PluginDirectoryScanner (const PluginDirectoryScanner&);
  29548. PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  29549. };
  29550. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29551. /*** End of inlined file: juce_PluginDirectoryScanner.h ***/
  29552. #endif
  29553. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29554. /*** Start of inlined file: juce_PluginListComponent.h ***/
  29555. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29556. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29557. /*** Start of inlined file: juce_ListBox.h ***/
  29558. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  29559. #define __JUCE_LISTBOX_JUCEHEADER__
  29560. class ListViewport;
  29561. /**
  29562. A subclass of this is used to drive a ListBox.
  29563. @see ListBox
  29564. */
  29565. class JUCE_API ListBoxModel
  29566. {
  29567. public:
  29568. /** Destructor. */
  29569. virtual ~ListBoxModel() {}
  29570. /** This has to return the number of items in the list.
  29571. @see ListBox::getNumRows()
  29572. */
  29573. virtual int getNumRows() = 0;
  29574. /** This method must be implemented to draw a row of the list.
  29575. */
  29576. virtual void paintListBoxItem (int rowNumber,
  29577. Graphics& g,
  29578. int width, int height,
  29579. bool rowIsSelected) = 0;
  29580. /** This is used to create or update a custom component to go in a row of the list.
  29581. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  29582. and handle mouse clicks with listBoxItemClicked().
  29583. This method will be called whenever a custom component might need to be updated - e.g.
  29584. when the table is changed, or TableListBox::updateContent() is called.
  29585. If you don't need a custom component for the specified row, then return 0.
  29586. If you do want a custom component, and the existingComponentToUpdate is null, then
  29587. this method must create a suitable new component and return it.
  29588. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  29589. by this method. In this case, the method must either update it to make sure it's correctly representing
  29590. the given row (which may be different from the one that the component was created for), or it can
  29591. delete this component and return a new one.
  29592. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  29593. */
  29594. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  29595. Component* existingComponentToUpdate);
  29596. /** This can be overridden to react to the user clicking on a row.
  29597. @see listBoxItemDoubleClicked
  29598. */
  29599. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  29600. /** This can be overridden to react to the user double-clicking on a row.
  29601. @see listBoxItemClicked
  29602. */
  29603. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  29604. /** This can be overridden to react to the user double-clicking on a part of the list where
  29605. there are no rows.
  29606. @see listBoxItemClicked
  29607. */
  29608. virtual void backgroundClicked();
  29609. /** Override this to be informed when rows are selected or deselected.
  29610. This will be called whenever a row is selected or deselected. If a range of
  29611. rows is selected all at once, this will just be called once for that event.
  29612. @param lastRowSelected the last row that the user selected. If no
  29613. rows are currently selected, this may be -1.
  29614. */
  29615. virtual void selectedRowsChanged (int lastRowSelected);
  29616. /** Override this to be informed when the delete key is pressed.
  29617. If no rows are selected when they press the key, this won't be called.
  29618. @param lastRowSelected the last row that had been selected when they pressed the
  29619. key - if there are multiple selections, this might not be
  29620. very useful
  29621. */
  29622. virtual void deleteKeyPressed (int lastRowSelected);
  29623. /** Override this to be informed when the return key is pressed.
  29624. If no rows are selected when they press the key, this won't be called.
  29625. @param lastRowSelected the last row that had been selected when they pressed the
  29626. key - if there are multiple selections, this might not be
  29627. very useful
  29628. */
  29629. virtual void returnKeyPressed (int lastRowSelected);
  29630. /** Override this to be informed when the list is scrolled.
  29631. This might be caused by the user moving the scrollbar, or by programmatic changes
  29632. to the list position.
  29633. */
  29634. virtual void listWasScrolled();
  29635. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  29636. If this returns a non-empty name then when the user drags a row, the listbox will
  29637. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  29638. a drag-and-drop operation, using this string as the source description, with the listbox
  29639. itself as the source component.
  29640. @see DragAndDropContainer::startDragging
  29641. */
  29642. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  29643. /** You can override this to provide tool tips for specific rows.
  29644. @see TooltipClient
  29645. */
  29646. virtual const String getTooltipForRow (int row);
  29647. };
  29648. /**
  29649. A list of items that can be scrolled vertically.
  29650. To create a list, you'll need to create a subclass of ListBoxModel. This can
  29651. either paint each row of the list and respond to events via callbacks, or for
  29652. more specialised tasks, it can supply a custom component to fill each row.
  29653. @see ComboBox, TableListBox
  29654. */
  29655. class JUCE_API ListBox : public Component,
  29656. public SettableTooltipClient
  29657. {
  29658. public:
  29659. /** Creates a ListBox.
  29660. The model pointer passed-in can be null, in which case you can set it later
  29661. with setModel().
  29662. */
  29663. ListBox (const String& componentName,
  29664. ListBoxModel* model);
  29665. /** Destructor. */
  29666. ~ListBox();
  29667. /** Changes the current data model to display. */
  29668. void setModel (ListBoxModel* newModel);
  29669. /** Returns the current list model. */
  29670. ListBoxModel* getModel() const throw() { return model; }
  29671. /** Causes the list to refresh its content.
  29672. Call this when the number of rows in the list changes, or if you want it
  29673. to call refreshComponentForRow() on all the row components.
  29674. Be careful not to call it from a different thread, though, as it's not
  29675. thread-safe.
  29676. */
  29677. void updateContent();
  29678. /** Turns on multiple-selection of rows.
  29679. By default this is disabled.
  29680. When your row component gets clicked you'll need to call the
  29681. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  29682. clicked and to get it to do the appropriate selection based on whether
  29683. the ctrl/shift keys are held down.
  29684. */
  29685. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  29686. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  29687. This function is here primarily for the ComboBox class to use, but might be
  29688. useful for some other purpose too.
  29689. */
  29690. void setMouseMoveSelectsRows (bool shouldSelect);
  29691. /** Selects a row.
  29692. If the row is already selected, this won't do anything.
  29693. @param rowNumber the row to select
  29694. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  29695. the selected row is off-screen, it'll scroll to make
  29696. sure that row is on-screen
  29697. @param deselectOthersFirst if true and there are multiple selections, these will
  29698. first be deselected before this item is selected
  29699. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  29700. deselectAllRows, selectRangeOfRows
  29701. */
  29702. void selectRow (int rowNumber,
  29703. bool dontScrollToShowThisRow = false,
  29704. bool deselectOthersFirst = true);
  29705. /** Selects a set of rows.
  29706. This will add these rows to the current selection, so you might need to
  29707. clear the current selection first with deselectAllRows()
  29708. @param firstRow the first row to select (inclusive)
  29709. @param lastRow the last row to select (inclusive)
  29710. */
  29711. void selectRangeOfRows (int firstRow,
  29712. int lastRow);
  29713. /** Deselects a row.
  29714. If it's not currently selected, this will do nothing.
  29715. @see selectRow, deselectAllRows
  29716. */
  29717. void deselectRow (int rowNumber);
  29718. /** Deselects any currently selected rows.
  29719. @see deselectRow
  29720. */
  29721. void deselectAllRows();
  29722. /** Selects or deselects a row.
  29723. If the row's currently selected, this deselects it, and vice-versa.
  29724. */
  29725. void flipRowSelection (int rowNumber);
  29726. /** Returns a sparse set indicating the rows that are currently selected.
  29727. @see setSelectedRows
  29728. */
  29729. const SparseSet<int> getSelectedRows() const;
  29730. /** Sets the rows that should be selected, based on an explicit set of ranges.
  29731. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  29732. method will be called. If it's false, no notification will be sent to the model.
  29733. @see getSelectedRows
  29734. */
  29735. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  29736. bool sendNotificationEventToModel = true);
  29737. /** Checks whether a row is selected.
  29738. */
  29739. bool isRowSelected (int rowNumber) const;
  29740. /** Returns the number of rows that are currently selected.
  29741. @see getSelectedRow, isRowSelected, getLastRowSelected
  29742. */
  29743. int getNumSelectedRows() const;
  29744. /** Returns the row number of a selected row.
  29745. This will return the row number of the Nth selected row. The row numbers returned will
  29746. be sorted in order from low to high.
  29747. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  29748. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  29749. selected
  29750. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  29751. */
  29752. int getSelectedRow (int index = 0) const;
  29753. /** Returns the last row that the user selected.
  29754. This isn't the same as the highest row number that is currently selected - if the user
  29755. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  29756. If nothing is selected, it will return -1.
  29757. */
  29758. int getLastRowSelected() const;
  29759. /** Multiply-selects rows based on the modifier keys.
  29760. If no modifier keys are down, this will select the given row and
  29761. deselect any others.
  29762. If the ctrl (or command on the Mac) key is down, it'll flip the
  29763. state of the selected row.
  29764. If the shift key is down, it'll select up to the given row from the
  29765. last row selected.
  29766. @see selectRow
  29767. */
  29768. void selectRowsBasedOnModifierKeys (int rowThatWasClickedOn,
  29769. const ModifierKeys& modifiers);
  29770. /** Scrolls the list to a particular position.
  29771. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  29772. 1.0 scrolls to the bottom.
  29773. If the total number of rows all fit onto the screen at once, then this
  29774. method won't do anything.
  29775. @see getVerticalPosition
  29776. */
  29777. void setVerticalPosition (double newProportion);
  29778. /** Returns the current vertical position as a proportion of the total.
  29779. This can be used in conjunction with setVerticalPosition() to save and restore
  29780. the list's position. It returns a value in the range 0 to 1.
  29781. @see setVerticalPosition
  29782. */
  29783. double getVerticalPosition() const;
  29784. /** Scrolls if necessary to make sure that a particular row is visible.
  29785. */
  29786. void scrollToEnsureRowIsOnscreen (int row);
  29787. /** Returns a pointer to the scrollbar.
  29788. (Unlikely to be useful for most people).
  29789. */
  29790. ScrollBar* getVerticalScrollBar() const throw();
  29791. /** Returns a pointer to the scrollbar.
  29792. (Unlikely to be useful for most people).
  29793. */
  29794. ScrollBar* getHorizontalScrollBar() const throw();
  29795. /** Finds the row index that contains a given x,y position.
  29796. The position is relative to the ListBox's top-left.
  29797. If no row exists at this position, the method will return -1.
  29798. @see getComponentForRowNumber
  29799. */
  29800. int getRowContainingPosition (int x, int y) const throw();
  29801. /** Finds a row index that would be the most suitable place to insert a new
  29802. item for a given position.
  29803. This is useful when the user is e.g. dragging and dropping onto the listbox,
  29804. because it lets you easily choose the best position to insert the item that
  29805. they drop, based on where they drop it.
  29806. If the position is out of range, this will return -1. If the position is
  29807. beyond the end of the list, it will return getNumRows() to indicate the end
  29808. of the list.
  29809. @see getComponentForRowNumber
  29810. */
  29811. int getInsertionIndexForPosition (int x, int y) const throw();
  29812. /** Returns the position of one of the rows, relative to the top-left of
  29813. the listbox.
  29814. This may be off-screen, and the range of the row number that is passed-in is
  29815. not checked to see if it's a valid row.
  29816. */
  29817. const Rectangle<int> getRowPosition (int rowNumber,
  29818. bool relativeToComponentTopLeft) const throw();
  29819. /** Finds the row component for a given row in the list.
  29820. The component returned will have been created using createRowComponent().
  29821. If the component for this row is off-screen or if the row is out-of-range,
  29822. this will return 0.
  29823. @see getRowContainingPosition
  29824. */
  29825. Component* getComponentForRowNumber (int rowNumber) const throw();
  29826. /** Returns the row number that the given component represents.
  29827. If the component isn't one of the list's rows, this will return -1.
  29828. */
  29829. int getRowNumberOfComponent (Component* rowComponent) const throw();
  29830. /** Returns the width of a row (which may be less than the width of this component
  29831. if there's a scrollbar).
  29832. */
  29833. int getVisibleRowWidth() const throw();
  29834. /** Sets the height of each row in the list.
  29835. The default height is 22 pixels.
  29836. @see getRowHeight
  29837. */
  29838. void setRowHeight (int newHeight);
  29839. /** Returns the height of a row in the list.
  29840. @see setRowHeight
  29841. */
  29842. int getRowHeight() const throw() { return rowHeight; }
  29843. /** Returns the number of rows actually visible.
  29844. This is the number of whole rows which will fit on-screen, so the value might
  29845. be more than the actual number of rows in the list.
  29846. */
  29847. int getNumRowsOnScreen() const throw();
  29848. /** A set of colour IDs to use to change the colour of various aspects of the label.
  29849. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  29850. methods.
  29851. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  29852. */
  29853. enum ColourIds
  29854. {
  29855. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  29856. Make this transparent if you don't want the background to be filled. */
  29857. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  29858. Make this transparent to not have an outline. */
  29859. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  29860. };
  29861. /** Sets the thickness of a border that will be drawn around the box.
  29862. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  29863. @see outlineColourId
  29864. */
  29865. void setOutlineThickness (int outlineThickness);
  29866. /** Returns the thickness of outline that will be drawn around the listbox.
  29867. @see setOutlineColour
  29868. */
  29869. int getOutlineThickness() const throw() { return outlineThickness; }
  29870. /** Sets a component that the list should use as a header.
  29871. This will position the given component at the top of the list, maintaining the
  29872. height of the component passed-in, but rescaling it horizontally to match the
  29873. width of the items in the listbox.
  29874. The component will be deleted when setHeaderComponent() is called with a
  29875. different component, or when the listbox is deleted.
  29876. */
  29877. void setHeaderComponent (Component* newHeaderComponent);
  29878. /** Changes the width of the rows in the list.
  29879. This can be used to make the list's row components wider than the list itself - the
  29880. width of the rows will be either the width of the list or this value, whichever is
  29881. greater, and if the rows become wider than the list, a horizontal scrollbar will
  29882. appear.
  29883. The default value for this is 0, which means that the rows will always
  29884. be the same width as the list.
  29885. */
  29886. void setMinimumContentWidth (int newMinimumWidth);
  29887. /** Returns the space currently available for the row items, taking into account
  29888. borders, scrollbars, etc.
  29889. */
  29890. int getVisibleContentWidth() const throw();
  29891. /** Repaints one of the rows.
  29892. This is a lightweight alternative to calling updateContent, and just causes a
  29893. repaint of the row's area.
  29894. */
  29895. void repaintRow (int rowNumber) throw();
  29896. /** This fairly obscure method creates an image that just shows the currently
  29897. selected row components.
  29898. It's a handy method for doing drag-and-drop, as it can be passed to the
  29899. DragAndDropContainer for use as the drag image.
  29900. Note that it will make the row components temporarily invisible, so if you're
  29901. using custom components this could affect them if they're sensitive to that
  29902. sort of thing.
  29903. @see Component::createComponentSnapshot
  29904. */
  29905. const Image createSnapshotOfSelectedRows (int& x, int& y);
  29906. /** Returns the viewport that this ListBox uses.
  29907. You may need to use this to change parameters such as whether scrollbars
  29908. are shown, etc.
  29909. */
  29910. Viewport* getViewport() const throw();
  29911. /** @internal */
  29912. bool keyPressed (const KeyPress& key);
  29913. /** @internal */
  29914. bool keyStateChanged (bool isKeyDown);
  29915. /** @internal */
  29916. void paint (Graphics& g);
  29917. /** @internal */
  29918. void paintOverChildren (Graphics& g);
  29919. /** @internal */
  29920. void resized();
  29921. /** @internal */
  29922. void visibilityChanged();
  29923. /** @internal */
  29924. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  29925. /** @internal */
  29926. void mouseMove (const MouseEvent&);
  29927. /** @internal */
  29928. void mouseExit (const MouseEvent&);
  29929. /** @internal */
  29930. void mouseUp (const MouseEvent&);
  29931. /** @internal */
  29932. void colourChanged();
  29933. /** @internal */
  29934. void startDragAndDrop (const MouseEvent& e, const String& dragDescription);
  29935. juce_UseDebuggingNewOperator
  29936. private:
  29937. friend class ListViewport;
  29938. friend class TableListBox;
  29939. ListBoxModel* model;
  29940. ListViewport* viewport;
  29941. Component* headerComponent;
  29942. int totalItems, rowHeight, minimumRowWidth;
  29943. int outlineThickness;
  29944. int lastRowSelected;
  29945. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  29946. SparseSet <int> selected;
  29947. void selectRowInternal (int rowNumber,
  29948. bool dontScrollToShowThisRow,
  29949. bool deselectOthersFirst,
  29950. bool isMouseClick);
  29951. ListBox (const ListBox&);
  29952. ListBox& operator= (const ListBox&);
  29953. };
  29954. #endif // __JUCE_LISTBOX_JUCEHEADER__
  29955. /*** End of inlined file: juce_ListBox.h ***/
  29956. /*** Start of inlined file: juce_TextButton.h ***/
  29957. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  29958. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  29959. /**
  29960. A button that uses the standard lozenge-shaped background with a line of
  29961. text on it.
  29962. @see Button, DrawableButton
  29963. */
  29964. class JUCE_API TextButton : public Button
  29965. {
  29966. public:
  29967. /** Creates a TextButton.
  29968. @param buttonName the text to put in the button (the component's name is also
  29969. initially set to this string, but these can be changed later
  29970. using the setName() and setButtonText() methods)
  29971. @param toolTip an optional string to use as a toolip
  29972. @see Button
  29973. */
  29974. TextButton (const String& buttonName = String::empty,
  29975. const String& toolTip = String::empty);
  29976. /** Destructor. */
  29977. ~TextButton();
  29978. /** A set of colour IDs to use to change the colour of various aspects of the button.
  29979. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  29980. methods.
  29981. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  29982. */
  29983. enum ColourIds
  29984. {
  29985. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  29986. 'off'). The look-and-feel class might re-interpret this to add
  29987. effects, etc. */
  29988. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  29989. 'on'). The look-and-feel class might re-interpret this to add
  29990. effects, etc. */
  29991. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  29992. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  29993. };
  29994. /** Resizes the button to fit neatly around its current text.
  29995. If newHeight is >= 0, the button's height will be changed to this
  29996. value. If it's less than zero, its height will be unaffected.
  29997. */
  29998. void changeWidthToFitText (int newHeight = -1);
  29999. /** This can be overridden to use different fonts than the default one.
  30000. Note that you'll need to set the font's size appropriately, too.
  30001. */
  30002. virtual const Font getFont();
  30003. juce_UseDebuggingNewOperator
  30004. protected:
  30005. /** @internal */
  30006. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  30007. /** @internal */
  30008. void colourChanged();
  30009. private:
  30010. TextButton (const TextButton&);
  30011. TextButton& operator= (const TextButton&);
  30012. };
  30013. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  30014. /*** End of inlined file: juce_TextButton.h ***/
  30015. /**
  30016. A component displaying a list of plugins, with options to scan for them,
  30017. add, remove and sort them.
  30018. */
  30019. class JUCE_API PluginListComponent : public Component,
  30020. public ListBoxModel,
  30021. public ChangeListener,
  30022. public ButtonListener,
  30023. public Timer
  30024. {
  30025. public:
  30026. /**
  30027. Creates the list component.
  30028. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  30029. The properties file, if supplied, is used to store the user's last search paths.
  30030. */
  30031. PluginListComponent (KnownPluginList& listToRepresent,
  30032. const File& deadMansPedalFile,
  30033. PropertiesFile* propertiesToUse);
  30034. /** Destructor. */
  30035. ~PluginListComponent();
  30036. /** @internal */
  30037. void resized();
  30038. /** @internal */
  30039. bool isInterestedInFileDrag (const StringArray& files);
  30040. /** @internal */
  30041. void filesDropped (const StringArray& files, int, int);
  30042. /** @internal */
  30043. int getNumRows();
  30044. /** @internal */
  30045. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  30046. /** @internal */
  30047. void deleteKeyPressed (int lastRowSelected);
  30048. /** @internal */
  30049. void buttonClicked (Button* b);
  30050. /** @internal */
  30051. void changeListenerCallback (void*);
  30052. /** @internal */
  30053. void timerCallback();
  30054. juce_UseDebuggingNewOperator
  30055. private:
  30056. KnownPluginList& list;
  30057. File deadMansPedalFile;
  30058. ListBox* listBox;
  30059. TextButton* optionsButton;
  30060. PropertiesFile* propertiesToUse;
  30061. int typeToScan;
  30062. void scanFor (AudioPluginFormat* format);
  30063. PluginListComponent (const PluginListComponent&);
  30064. PluginListComponent& operator= (const PluginListComponent&);
  30065. };
  30066. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  30067. /*** End of inlined file: juce_PluginListComponent.h ***/
  30068. #endif
  30069. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  30070. #endif
  30071. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  30072. #endif
  30073. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  30074. #endif
  30075. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30076. /*** Start of inlined file: juce_AudioProcessorGraph.h ***/
  30077. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30078. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30079. /**
  30080. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  30081. Use one of these objects if you want to wire-up a set of AudioProcessors
  30082. and play back the result.
  30083. Processors can be added to the graph as "nodes" using addNode(), and once
  30084. added, you can connect any of their input or output channels to other
  30085. nodes using addConnection().
  30086. To play back a graph through an audio device, you might want to use an
  30087. AudioProcessorPlayer object.
  30088. */
  30089. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  30090. public AsyncUpdater
  30091. {
  30092. public:
  30093. /** Creates an empty graph.
  30094. */
  30095. AudioProcessorGraph();
  30096. /** Destructor.
  30097. Any processor objects that have been added to the graph will also be deleted.
  30098. */
  30099. ~AudioProcessorGraph();
  30100. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  30101. To create a node, call AudioProcessorGraph::addNode().
  30102. */
  30103. class JUCE_API Node : public ReferenceCountedObject
  30104. {
  30105. public:
  30106. /** Destructor.
  30107. */
  30108. ~Node();
  30109. /** The ID number assigned to this node.
  30110. This is assigned by the graph that owns it, and can't be changed.
  30111. */
  30112. const uint32 id;
  30113. /** The actual processor object that this node represents.
  30114. */
  30115. AudioProcessor* const processor;
  30116. /** A set of user-definable properties that are associated with this node.
  30117. This can be used to attach values to the node for whatever purpose seems
  30118. useful. For example, you might store an x and y position if your application
  30119. is displaying the nodes on-screen.
  30120. */
  30121. NamedValueSet properties;
  30122. /** A convenient typedef for referring to a pointer to a node object.
  30123. */
  30124. typedef ReferenceCountedObjectPtr <Node> Ptr;
  30125. juce_UseDebuggingNewOperator
  30126. private:
  30127. friend class AudioProcessorGraph;
  30128. bool isPrepared;
  30129. Node (uint32 id, AudioProcessor* processor);
  30130. void prepare (double sampleRate, int blockSize, AudioProcessorGraph* graph);
  30131. void unprepare();
  30132. Node (const Node&);
  30133. Node& operator= (const Node&);
  30134. };
  30135. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  30136. To create a connection, use AudioProcessorGraph::addConnection().
  30137. */
  30138. struct JUCE_API Connection
  30139. {
  30140. public:
  30141. /** The ID number of the node which is the input source for this connection.
  30142. @see AudioProcessorGraph::getNodeForId
  30143. */
  30144. uint32 sourceNodeId;
  30145. /** The index of the output channel of the source node from which this
  30146. connection takes its data.
  30147. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  30148. it is referring to the source node's midi output. Otherwise, it is the zero-based
  30149. index of an audio output channel in the source node.
  30150. */
  30151. int sourceChannelIndex;
  30152. /** The ID number of the node which is the destination for this connection.
  30153. @see AudioProcessorGraph::getNodeForId
  30154. */
  30155. uint32 destNodeId;
  30156. /** The index of the input channel of the destination node to which this
  30157. connection delivers its data.
  30158. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  30159. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  30160. index of an audio input channel in the destination node.
  30161. */
  30162. int destChannelIndex;
  30163. juce_UseDebuggingNewOperator
  30164. private:
  30165. };
  30166. /** Deletes all nodes and connections from this graph.
  30167. Any processor objects in the graph will be deleted.
  30168. */
  30169. void clear();
  30170. /** Returns the number of nodes in the graph. */
  30171. int getNumNodes() const { return nodes.size(); }
  30172. /** Returns a pointer to one of the nodes in the graph.
  30173. This will return 0 if the index is out of range.
  30174. @see getNodeForId
  30175. */
  30176. Node* getNode (const int index) const { return nodes [index]; }
  30177. /** Searches the graph for a node with the given ID number and returns it.
  30178. If no such node was found, this returns 0.
  30179. @see getNode
  30180. */
  30181. Node* getNodeForId (const uint32 nodeId) const;
  30182. /** Adds a node to the graph.
  30183. This creates a new node in the graph, for the specified processor. Once you have
  30184. added a processor to the graph, the graph owns it and will delete it later when
  30185. it is no longer needed.
  30186. The optional nodeId parameter lets you specify an ID to use for the node, but
  30187. if the value is already in use, this new node will overwrite the old one.
  30188. If this succeeds, it returns a pointer to the newly-created node.
  30189. */
  30190. Node* addNode (AudioProcessor* newProcessor, uint32 nodeId = 0);
  30191. /** Deletes a node within the graph which has the specified ID.
  30192. This will also delete any connections that are attached to this node.
  30193. */
  30194. bool removeNode (uint32 nodeId);
  30195. /** Returns the number of connections in the graph. */
  30196. int getNumConnections() const { return connections.size(); }
  30197. /** Returns a pointer to one of the connections in the graph. */
  30198. const Connection* getConnection (int index) const { return connections [index]; }
  30199. /** Searches for a connection between some specified channels.
  30200. If no such connection is found, this returns 0.
  30201. */
  30202. const Connection* getConnectionBetween (uint32 sourceNodeId,
  30203. int sourceChannelIndex,
  30204. uint32 destNodeId,
  30205. int destChannelIndex) const;
  30206. /** Returns true if there is a connection between any of the channels of
  30207. two specified nodes.
  30208. */
  30209. bool isConnected (uint32 possibleSourceNodeId,
  30210. uint32 possibleDestNodeId) const;
  30211. /** Returns true if it would be legal to connect the specified points.
  30212. */
  30213. bool canConnect (uint32 sourceNodeId, int sourceChannelIndex,
  30214. uint32 destNodeId, int destChannelIndex) const;
  30215. /** Attempts to connect two specified channels of two nodes.
  30216. If this isn't allowed (e.g. because you're trying to connect a midi channel
  30217. to an audio one or other such nonsense), then it'll return false.
  30218. */
  30219. bool addConnection (uint32 sourceNodeId, int sourceChannelIndex,
  30220. uint32 destNodeId, int destChannelIndex);
  30221. /** Deletes the connection with the specified index.
  30222. Returns true if a connection was actually deleted.
  30223. */
  30224. void removeConnection (int index);
  30225. /** Deletes any connection between two specified points.
  30226. Returns true if a connection was actually deleted.
  30227. */
  30228. bool removeConnection (uint32 sourceNodeId, int sourceChannelIndex,
  30229. uint32 destNodeId, int destChannelIndex);
  30230. /** Removes all connections from the specified node.
  30231. */
  30232. bool disconnectNode (uint32 nodeId);
  30233. /** Performs a sanity checks of all the connections.
  30234. This might be useful if some of the processors are doing things like changing
  30235. their channel counts, which could render some connections obsolete.
  30236. */
  30237. bool removeIllegalConnections();
  30238. /** A special number that represents the midi channel of a node.
  30239. This is used as a channel index value if you want to refer to the midi input
  30240. or output instead of an audio channel.
  30241. */
  30242. static const int midiChannelIndex;
  30243. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  30244. in order to use the audio that comes into and out of the graph itself.
  30245. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  30246. node in the graph which delivers the audio that is coming into the parent
  30247. graph. This allows you to stream the data to other nodes and process the
  30248. incoming audio.
  30249. Likewise, one of these in "output" mode can be sent data which it will add to
  30250. the sum of data being sent to the graph's output.
  30251. @see AudioProcessorGraph
  30252. */
  30253. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  30254. {
  30255. public:
  30256. /** Specifies the mode in which this processor will operate.
  30257. */
  30258. enum IODeviceType
  30259. {
  30260. audioInputNode, /**< In this mode, the processor has output channels
  30261. representing all the audio input channels that are
  30262. coming into its parent audio graph. */
  30263. audioOutputNode, /**< In this mode, the processor has input channels
  30264. representing all the audio output channels that are
  30265. going out of its parent audio graph. */
  30266. midiInputNode, /**< In this mode, the processor has a midi output which
  30267. delivers the same midi data that is arriving at its
  30268. parent graph. */
  30269. midiOutputNode /**< In this mode, the processor has a midi input and
  30270. any data sent to it will be passed out of the parent
  30271. graph. */
  30272. };
  30273. /** Returns the mode of this processor. */
  30274. IODeviceType getType() const { return type; }
  30275. /** Returns the parent graph to which this processor belongs, or 0 if it
  30276. hasn't yet been added to one. */
  30277. AudioProcessorGraph* getParentGraph() const { return graph; }
  30278. /** True if this is an audio or midi input. */
  30279. bool isInput() const;
  30280. /** True if this is an audio or midi output. */
  30281. bool isOutput() const;
  30282. AudioGraphIOProcessor (const IODeviceType type);
  30283. ~AudioGraphIOProcessor();
  30284. const String getName() const;
  30285. void fillInPluginDescription (PluginDescription& d) const;
  30286. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  30287. void releaseResources();
  30288. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  30289. const String getInputChannelName (const int channelIndex) const;
  30290. const String getOutputChannelName (const int channelIndex) const;
  30291. bool isInputChannelStereoPair (int index) const;
  30292. bool isOutputChannelStereoPair (int index) const;
  30293. bool acceptsMidi() const;
  30294. bool producesMidi() const;
  30295. AudioProcessorEditor* createEditor();
  30296. int getNumParameters();
  30297. const String getParameterName (int);
  30298. float getParameter (int);
  30299. const String getParameterText (int);
  30300. void setParameter (int, float);
  30301. int getNumPrograms();
  30302. int getCurrentProgram();
  30303. void setCurrentProgram (int);
  30304. const String getProgramName (int);
  30305. void changeProgramName (int, const String&);
  30306. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  30307. void setStateInformation (const void* data, int sizeInBytes);
  30308. /** @internal */
  30309. void setParentGraph (AudioProcessorGraph* graph);
  30310. juce_UseDebuggingNewOperator
  30311. private:
  30312. const IODeviceType type;
  30313. AudioProcessorGraph* graph;
  30314. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  30315. AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  30316. };
  30317. // AudioProcessor methods:
  30318. const String getName() const;
  30319. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  30320. void releaseResources();
  30321. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  30322. const String getInputChannelName (const int channelIndex) const;
  30323. const String getOutputChannelName (const int channelIndex) const;
  30324. bool isInputChannelStereoPair (int index) const;
  30325. bool isOutputChannelStereoPair (int index) const;
  30326. bool acceptsMidi() const;
  30327. bool producesMidi() const;
  30328. AudioProcessorEditor* createEditor() { return 0; }
  30329. int getNumParameters() { return 0; }
  30330. const String getParameterName (int) { return String::empty; }
  30331. float getParameter (int) { return 0; }
  30332. const String getParameterText (int) { return String::empty; }
  30333. void setParameter (int, float) { }
  30334. int getNumPrograms() { return 0; }
  30335. int getCurrentProgram() { return 0; }
  30336. void setCurrentProgram (int) { }
  30337. const String getProgramName (int) { return String::empty; }
  30338. void changeProgramName (int, const String&) { }
  30339. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  30340. void setStateInformation (const void* data, int sizeInBytes);
  30341. /** @internal */
  30342. void handleAsyncUpdate();
  30343. juce_UseDebuggingNewOperator
  30344. private:
  30345. ReferenceCountedArray <Node> nodes;
  30346. OwnedArray <Connection> connections;
  30347. int lastNodeId;
  30348. AudioSampleBuffer renderingBuffers;
  30349. OwnedArray <MidiBuffer> midiBuffers;
  30350. CriticalSection renderLock;
  30351. Array<void*> renderingOps;
  30352. friend class AudioGraphIOProcessor;
  30353. AudioSampleBuffer* currentAudioInputBuffer;
  30354. AudioSampleBuffer currentAudioOutputBuffer;
  30355. MidiBuffer* currentMidiInputBuffer;
  30356. MidiBuffer currentMidiOutputBuffer;
  30357. void clearRenderingSequence();
  30358. void buildRenderingSequence();
  30359. bool isAnInputTo (uint32 possibleInputId, uint32 possibleDestinationId, int recursionCheck) const;
  30360. AudioProcessorGraph (const AudioProcessorGraph&);
  30361. AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  30362. };
  30363. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30364. /*** End of inlined file: juce_AudioProcessorGraph.h ***/
  30365. #endif
  30366. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  30367. #endif
  30368. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30369. /*** Start of inlined file: juce_AudioProcessorPlayer.h ***/
  30370. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30371. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30372. /**
  30373. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  30374. To use one of these, just make it the callback used by your AudioIODevice, and
  30375. give it a processor to use by calling setProcessor().
  30376. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  30377. input to send both streams through the processor.
  30378. @see AudioProcessor, AudioProcessorGraph
  30379. */
  30380. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  30381. public MidiInputCallback
  30382. {
  30383. public:
  30384. /**
  30385. */
  30386. AudioProcessorPlayer();
  30387. /** Destructor. */
  30388. virtual ~AudioProcessorPlayer();
  30389. /** Sets the processor that should be played.
  30390. The processor that is passed in will not be deleted or owned by this object.
  30391. To stop anything playing, pass in 0 to this method.
  30392. */
  30393. void setProcessor (AudioProcessor* const processorToPlay);
  30394. /** Returns the current audio processor that is being played.
  30395. */
  30396. AudioProcessor* getCurrentProcessor() const { return processor; }
  30397. /** Returns a midi message collector that you can pass midi messages to if you
  30398. want them to be injected into the midi stream that is being sent to the
  30399. processor.
  30400. */
  30401. MidiMessageCollector& getMidiMessageCollector() { return messageCollector; }
  30402. /** @internal */
  30403. void audioDeviceIOCallback (const float** inputChannelData,
  30404. int totalNumInputChannels,
  30405. float** outputChannelData,
  30406. int totalNumOutputChannels,
  30407. int numSamples);
  30408. /** @internal */
  30409. void audioDeviceAboutToStart (AudioIODevice* device);
  30410. /** @internal */
  30411. void audioDeviceStopped();
  30412. /** @internal */
  30413. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  30414. juce_UseDebuggingNewOperator
  30415. private:
  30416. AudioProcessor* processor;
  30417. CriticalSection lock;
  30418. double sampleRate;
  30419. int blockSize;
  30420. bool isPrepared;
  30421. int numInputChans, numOutputChans;
  30422. float* channels [128];
  30423. AudioSampleBuffer tempBuffer;
  30424. MidiBuffer incomingMidi;
  30425. MidiMessageCollector messageCollector;
  30426. AudioProcessorPlayer (const AudioProcessorPlayer&);
  30427. AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  30428. };
  30429. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30430. /*** End of inlined file: juce_AudioProcessorPlayer.h ***/
  30431. #endif
  30432. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30433. /*** Start of inlined file: juce_GenericAudioProcessorEditor.h ***/
  30434. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30435. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30436. /*** Start of inlined file: juce_PropertyPanel.h ***/
  30437. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  30438. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  30439. /*** Start of inlined file: juce_PropertyComponent.h ***/
  30440. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  30441. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  30442. class EditableProperty;
  30443. /**
  30444. A base class for a component that goes in a PropertyPanel and displays one of
  30445. an item's properties.
  30446. Subclasses of this are used to display a property in various forms, e.g. a
  30447. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  30448. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  30449. A subclass must implement the refresh() method which will be called to tell the
  30450. component to update itself, and is also responsible for calling this it when the
  30451. item that it refers to is changed.
  30452. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  30453. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  30454. */
  30455. class JUCE_API PropertyComponent : public Component,
  30456. public SettableTooltipClient
  30457. {
  30458. public:
  30459. /** Creates a PropertyComponent.
  30460. @param propertyName the name is stored as this component's name, and is
  30461. used as the name displayed next to this component in
  30462. a property panel
  30463. @param preferredHeight the height that the component should be given - some
  30464. items may need to be larger than a normal row height.
  30465. This value can also be set if a subclass changes the
  30466. preferredHeight member variable.
  30467. */
  30468. PropertyComponent (const String& propertyName,
  30469. int preferredHeight = 25);
  30470. /** Destructor. */
  30471. ~PropertyComponent();
  30472. /** Returns this item's preferred height.
  30473. This value is specified either in the constructor or by a subclass changing the
  30474. preferredHeight member variable.
  30475. */
  30476. int getPreferredHeight() const throw() { return preferredHeight; }
  30477. void setPreferredHeight (int newHeight) throw() { preferredHeight = newHeight; }
  30478. /** Updates the property component if the item it refers to has changed.
  30479. A subclass must implement this method, and other objects may call it to
  30480. force it to refresh itself.
  30481. The subclass should be economical in the amount of work is done, so for
  30482. example it should check whether it really needs to do a repaint rather than
  30483. just doing one every time this method is called, as it may be called when
  30484. the value being displayed hasn't actually changed.
  30485. */
  30486. virtual void refresh() = 0;
  30487. /** The default paint method fills the background and draws a label for the
  30488. item's name.
  30489. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  30490. */
  30491. void paint (Graphics& g);
  30492. /** The default resize method positions any child component to the right of this
  30493. one, based on the look and feel's default label size.
  30494. */
  30495. void resized();
  30496. /** By default, this just repaints the component. */
  30497. void enablementChanged();
  30498. juce_UseDebuggingNewOperator
  30499. protected:
  30500. /** Used by the PropertyPanel to determine how high this component needs to be.
  30501. A subclass can update this value in its constructor but shouldn't alter it later
  30502. as changes won't necessarily be picked up.
  30503. */
  30504. int preferredHeight;
  30505. };
  30506. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  30507. /*** End of inlined file: juce_PropertyComponent.h ***/
  30508. /**
  30509. A panel that holds a list of PropertyComponent objects.
  30510. This panel displays a list of PropertyComponents, and allows them to be organised
  30511. into collapsible sections.
  30512. To use, simply create one of these and add your properties to it with addProperties()
  30513. or addSection().
  30514. @see PropertyComponent
  30515. */
  30516. class JUCE_API PropertyPanel : public Component
  30517. {
  30518. public:
  30519. /** Creates an empty property panel. */
  30520. PropertyPanel();
  30521. /** Destructor. */
  30522. ~PropertyPanel();
  30523. /** Deletes all property components from the panel.
  30524. */
  30525. void clear();
  30526. /** Adds a set of properties to the panel.
  30527. The components in the list will be owned by this object and will be automatically
  30528. deleted later on when no longer needed.
  30529. These properties are added without them being inside a named section. If you
  30530. want them to be kept together in a collapsible section, use addSection() instead.
  30531. */
  30532. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  30533. /** Adds a set of properties to the panel.
  30534. These properties are added at the bottom of the list, under a section heading with
  30535. a plus/minus button that allows it to be opened and closed.
  30536. The components in the list will be owned by this object and will be automatically
  30537. deleted later on when no longer needed.
  30538. To add properies without them being in a section, use addProperties().
  30539. */
  30540. void addSection (const String& sectionTitle,
  30541. const Array <PropertyComponent*>& newPropertyComponents,
  30542. bool shouldSectionInitiallyBeOpen = true);
  30543. /** Calls the refresh() method of all PropertyComponents in the panel */
  30544. void refreshAll() const;
  30545. /** Returns a list of all the names of sections in the panel.
  30546. These are the sections that have been added with addSection().
  30547. */
  30548. const StringArray getSectionNames() const;
  30549. /** Returns true if the section at this index is currently open.
  30550. The index is from 0 up to the number of items returned by getSectionNames().
  30551. */
  30552. bool isSectionOpen (int sectionIndex) const;
  30553. /** Opens or closes one of the sections.
  30554. The index is from 0 up to the number of items returned by getSectionNames().
  30555. */
  30556. void setSectionOpen (int sectionIndex, bool shouldBeOpen);
  30557. /** Enables or disables one of the sections.
  30558. The index is from 0 up to the number of items returned by getSectionNames().
  30559. */
  30560. void setSectionEnabled (int sectionIndex, bool shouldBeEnabled);
  30561. /** Saves the current state of open/closed sections so it can be restored later.
  30562. The caller is responsible for deleting the object that is returned.
  30563. To restore this state, use restoreOpennessState().
  30564. @see restoreOpennessState
  30565. */
  30566. XmlElement* getOpennessState() const;
  30567. /** Restores a previously saved arrangement of open/closed sections.
  30568. This will try to restore a snapshot of the panel's state that was created by
  30569. the getOpennessState() method. If any of the sections named in the original
  30570. XML aren't present, they will be ignored.
  30571. @see getOpennessState
  30572. */
  30573. void restoreOpennessState (const XmlElement& newState);
  30574. /** Sets a message to be displayed when there are no properties in the panel.
  30575. The default message is "nothing selected".
  30576. */
  30577. void setMessageWhenEmpty (const String& newMessage);
  30578. /** Returns the message that is displayed when there are no properties.
  30579. @see setMessageWhenEmpty
  30580. */
  30581. const String& getMessageWhenEmpty() const;
  30582. /** @internal */
  30583. void paint (Graphics& g);
  30584. /** @internal */
  30585. void resized();
  30586. juce_UseDebuggingNewOperator
  30587. private:
  30588. Viewport viewport;
  30589. class PropertyHolderComponent;
  30590. PropertyHolderComponent* propertyHolderComponent;
  30591. String messageWhenEmpty;
  30592. void updatePropHolderLayout() const;
  30593. void updatePropHolderLayout (int width) const;
  30594. };
  30595. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  30596. /*** End of inlined file: juce_PropertyPanel.h ***/
  30597. /**
  30598. A type of UI component that displays the parameters of an AudioProcessor as
  30599. a simple list of sliders.
  30600. This can be used for showing an editor for a processor that doesn't supply
  30601. its own custom editor.
  30602. @see AudioProcessor
  30603. */
  30604. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  30605. {
  30606. public:
  30607. GenericAudioProcessorEditor (AudioProcessor* const owner);
  30608. ~GenericAudioProcessorEditor();
  30609. void paint (Graphics& g);
  30610. void resized();
  30611. juce_UseDebuggingNewOperator
  30612. private:
  30613. PropertyPanel* panel;
  30614. GenericAudioProcessorEditor (const GenericAudioProcessorEditor&);
  30615. GenericAudioProcessorEditor& operator= (const GenericAudioProcessorEditor&);
  30616. };
  30617. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30618. /*** End of inlined file: juce_GenericAudioProcessorEditor.h ***/
  30619. #endif
  30620. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  30621. /*** Start of inlined file: juce_Sampler.h ***/
  30622. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  30623. #define __JUCE_SAMPLER_JUCEHEADER__
  30624. /*** Start of inlined file: juce_Synthesiser.h ***/
  30625. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  30626. #define __JUCE_SYNTHESISER_JUCEHEADER__
  30627. /**
  30628. Describes one of the sounds that a Synthesiser can play.
  30629. A synthesiser can contain one or more sounds, and a sound can choose which
  30630. midi notes and channels can trigger it.
  30631. The SynthesiserSound is a passive class that just describes what the sound is -
  30632. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  30633. more than one SynthesiserVoice to play the same sound at the same time.
  30634. @see Synthesiser, SynthesiserVoice
  30635. */
  30636. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  30637. {
  30638. protected:
  30639. SynthesiserSound();
  30640. public:
  30641. /** Destructor. */
  30642. virtual ~SynthesiserSound();
  30643. /** Returns true if this sound should be played when a given midi note is pressed.
  30644. The Synthesiser will use this information when deciding which sounds to trigger
  30645. for a given note.
  30646. */
  30647. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  30648. /** Returns true if the sound should be triggered by midi events on a given channel.
  30649. The Synthesiser will use this information when deciding which sounds to trigger
  30650. for a given note.
  30651. */
  30652. virtual bool appliesToChannel (const int midiChannel) = 0;
  30653. /**
  30654. */
  30655. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  30656. juce_UseDebuggingNewOperator
  30657. };
  30658. /**
  30659. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  30660. A voice plays a single sound at a time, and a synthesiser holds an array of
  30661. voices so that it can play polyphonically.
  30662. @see Synthesiser, SynthesiserSound
  30663. */
  30664. class JUCE_API SynthesiserVoice
  30665. {
  30666. public:
  30667. /** Creates a voice. */
  30668. SynthesiserVoice();
  30669. /** Destructor. */
  30670. virtual ~SynthesiserVoice();
  30671. /** Returns the midi note that this voice is currently playing.
  30672. Returns a value less than 0 if no note is playing.
  30673. */
  30674. int getCurrentlyPlayingNote() const { return currentlyPlayingNote; }
  30675. /** Returns the sound that this voice is currently playing.
  30676. Returns 0 if it's not playing.
  30677. */
  30678. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const { return currentlyPlayingSound; }
  30679. /** Must return true if this voice object is capable of playing the given sound.
  30680. If there are different classes of sound, and different classes of voice, a voice can
  30681. choose which ones it wants to take on.
  30682. A typical implementation of this method may just return true if there's only one type
  30683. of voice and sound, or it might check the type of the sound object passed-in and
  30684. see if it's one that it understands.
  30685. */
  30686. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  30687. /** Called to start a new note.
  30688. This will be called during the rendering callback, so must be fast and thread-safe.
  30689. */
  30690. virtual void startNote (const int midiNoteNumber,
  30691. const float velocity,
  30692. SynthesiserSound* sound,
  30693. const int currentPitchWheelPosition) = 0;
  30694. /** Called to stop a note.
  30695. This will be called during the rendering callback, so must be fast and thread-safe.
  30696. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  30697. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  30698. and allow the synth to reassign it another sound.
  30699. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  30700. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  30701. finishes playing (during the rendering callback), it must make sure that it calls
  30702. clearCurrentNote().
  30703. */
  30704. virtual void stopNote (const bool allowTailOff) = 0;
  30705. /** Called to let the voice know that the pitch wheel has been moved.
  30706. This will be called during the rendering callback, so must be fast and thread-safe.
  30707. */
  30708. virtual void pitchWheelMoved (const int newValue) = 0;
  30709. /** Called to let the voice know that a midi controller has been moved.
  30710. This will be called during the rendering callback, so must be fast and thread-safe.
  30711. */
  30712. virtual void controllerMoved (const int controllerNumber,
  30713. const int newValue) = 0;
  30714. /** Renders the next block of data for this voice.
  30715. The output audio data must be added to the current contents of the buffer provided.
  30716. Only the region of the buffer between startSample and (startSample + numSamples)
  30717. should be altered by this method.
  30718. If the voice is currently silent, it should just return without doing anything.
  30719. If the sound that the voice is playing finishes during the course of this rendered
  30720. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  30721. The size of the blocks that are rendered can change each time it is called, and may
  30722. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  30723. the voice's methods will be called to tell it about note and controller events.
  30724. */
  30725. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  30726. int startSample,
  30727. int numSamples) = 0;
  30728. /** Returns true if the voice is currently playing a sound which is mapped to the given
  30729. midi channel.
  30730. If it's not currently playing, this will return false.
  30731. */
  30732. bool isPlayingChannel (int midiChannel) const;
  30733. /** Changes the voice's reference sample rate.
  30734. The rate is set so that subclasses know the output rate and can set their pitch
  30735. accordingly.
  30736. This method is called by the synth, and subclasses can access the current rate with
  30737. the currentSampleRate member.
  30738. */
  30739. void setCurrentPlaybackSampleRate (double newRate);
  30740. juce_UseDebuggingNewOperator
  30741. protected:
  30742. /** Returns the current target sample rate at which rendering is being done.
  30743. This is available for subclasses so they can pitch things correctly.
  30744. */
  30745. double getSampleRate() const { return currentSampleRate; }
  30746. /** Resets the state of this voice after a sound has finished playing.
  30747. The subclass must call this when it finishes playing a note and becomes available
  30748. to play new ones.
  30749. It must either call it in the stopNote() method, or if the voice is tailing off,
  30750. then it should call it later during the renderNextBlock method, as soon as it
  30751. finishes its tail-off.
  30752. It can also be called at any time during the render callback if the sound happens
  30753. to have finished, e.g. if it's playing a sample and the sample finishes.
  30754. */
  30755. void clearCurrentNote();
  30756. private:
  30757. friend class Synthesiser;
  30758. double currentSampleRate;
  30759. int currentlyPlayingNote;
  30760. uint32 noteOnTime;
  30761. SynthesiserSound::Ptr currentlyPlayingSound;
  30762. };
  30763. /**
  30764. Base class for a musical device that can play sounds.
  30765. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  30766. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  30767. which can play back one of these sounds.
  30768. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  30769. set of sounds, and a set of voices it can use to play them. If you only give it
  30770. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  30771. have available.
  30772. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  30773. events that go in will be scanned for note on/off messages, and these are used to
  30774. start and stop the voices playing the appropriate sounds.
  30775. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  30776. noteOff() and other controller methods.
  30777. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  30778. what the target playback rate is. This value is passed on to the voices so that
  30779. they can pitch their output correctly.
  30780. */
  30781. class JUCE_API Synthesiser
  30782. {
  30783. public:
  30784. /** Creates a new synthesiser.
  30785. You'll need to add some sounds and voices before it'll make any sound..
  30786. */
  30787. Synthesiser();
  30788. /** Destructor. */
  30789. virtual ~Synthesiser();
  30790. /** Deletes all voices. */
  30791. void clearVoices();
  30792. /** Returns the number of voices that have been added. */
  30793. int getNumVoices() const { return voices.size(); }
  30794. /** Returns one of the voices that have been added. */
  30795. SynthesiserVoice* getVoice (int index) const;
  30796. /** Adds a new voice to the synth.
  30797. All the voices should be the same class of object and are treated equally.
  30798. The object passed in will be managed by the synthesiser, which will delete
  30799. it later on when no longer needed. The caller should not retain a pointer to the
  30800. voice.
  30801. */
  30802. void addVoice (SynthesiserVoice* newVoice);
  30803. /** Deletes one of the voices. */
  30804. void removeVoice (int index);
  30805. /** Deletes all sounds. */
  30806. void clearSounds();
  30807. /** Returns the number of sounds that have been added to the synth. */
  30808. int getNumSounds() const { return sounds.size(); }
  30809. /** Returns one of the sounds. */
  30810. SynthesiserSound* getSound (int index) const { return sounds [index]; }
  30811. /** Adds a new sound to the synthesiser.
  30812. The object passed in is reference counted, so will be deleted when it is removed
  30813. from the synthesiser, and when no voices are still using it.
  30814. */
  30815. void addSound (const SynthesiserSound::Ptr& newSound);
  30816. /** Removes and deletes one of the sounds. */
  30817. void removeSound (int index);
  30818. /** If set to true, then the synth will try to take over an existing voice if
  30819. it runs out and needs to play another note.
  30820. The value of this boolean is passed into findFreeVoice(), so the result will
  30821. depend on the implementation of this method.
  30822. */
  30823. void setNoteStealingEnabled (bool shouldStealNotes);
  30824. /** Returns true if note-stealing is enabled.
  30825. @see setNoteStealingEnabled
  30826. */
  30827. bool isNoteStealingEnabled() const { return shouldStealNotes; }
  30828. /** Triggers a note-on event.
  30829. The default method here will find all the sounds that want to be triggered by
  30830. this note/channel. For each sound, it'll try to find a free voice, and use the
  30831. voice to start playing the sound.
  30832. Subclasses might want to override this if they need a more complex algorithm.
  30833. This method will be called automatically according to the midi data passed into
  30834. renderNextBlock(), but may be called explicitly too.
  30835. */
  30836. virtual void noteOn (const int midiChannel,
  30837. const int midiNoteNumber,
  30838. const float velocity);
  30839. /** Triggers a note-off event.
  30840. This will turn off any voices that are playing a sound for the given note/channel.
  30841. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  30842. (if they can do). If this is false, the notes will all be cut off immediately.
  30843. This method will be called automatically according to the midi data passed into
  30844. renderNextBlock(), but may be called explicitly too.
  30845. */
  30846. virtual void noteOff (const int midiChannel,
  30847. const int midiNoteNumber,
  30848. const bool allowTailOff);
  30849. /** Turns off all notes.
  30850. This will turn off any voices that are playing a sound on the given midi channel.
  30851. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  30852. which channel they're playing.
  30853. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  30854. (if they can do). If this is false, the notes will all be cut off immediately.
  30855. This method will be called automatically according to the midi data passed into
  30856. renderNextBlock(), but may be called explicitly too.
  30857. */
  30858. virtual void allNotesOff (const int midiChannel,
  30859. const bool allowTailOff);
  30860. /** Sends a pitch-wheel message.
  30861. This will send a pitch-wheel message to any voices that are playing sounds on
  30862. the given midi channel.
  30863. This method will be called automatically according to the midi data passed into
  30864. renderNextBlock(), but may be called explicitly too.
  30865. @param midiChannel the midi channel for the event
  30866. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  30867. */
  30868. virtual void handlePitchWheel (const int midiChannel,
  30869. const int wheelValue);
  30870. /** Sends a midi controller message.
  30871. This will send a midi controller message to any voices that are playing sounds on
  30872. the given midi channel.
  30873. This method will be called automatically according to the midi data passed into
  30874. renderNextBlock(), but may be called explicitly too.
  30875. @param midiChannel the midi channel for the event
  30876. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  30877. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  30878. */
  30879. virtual void handleController (const int midiChannel,
  30880. const int controllerNumber,
  30881. const int controllerValue);
  30882. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  30883. render.
  30884. This value is propagated to the voices so that they can use it to render the correct
  30885. pitches.
  30886. */
  30887. void setCurrentPlaybackSampleRate (const double sampleRate);
  30888. /** Creates the next block of audio output.
  30889. This will process the next numSamples of data from all the voices, and add that output
  30890. to the audio block supplied, starting from the offset specified. Note that the
  30891. data will be added to the current contents of the buffer, so you should clear it
  30892. before calling this method if necessary.
  30893. The midi events in the inputMidi buffer are parsed for note and controller events,
  30894. and these are used to trigger the voices. Note that the startSample offset applies
  30895. both to the audio output buffer and the midi input buffer, so any midi events
  30896. with timestamps outside the specified region will be ignored.
  30897. */
  30898. void renderNextBlock (AudioSampleBuffer& outputAudio,
  30899. const MidiBuffer& inputMidi,
  30900. int startSample,
  30901. int numSamples);
  30902. juce_UseDebuggingNewOperator
  30903. protected:
  30904. /** This is used to control access to the rendering callback and the note trigger methods. */
  30905. CriticalSection lock;
  30906. OwnedArray <SynthesiserVoice> voices;
  30907. ReferenceCountedArray <SynthesiserSound> sounds;
  30908. /** The last pitch-wheel values for each midi channel. */
  30909. int lastPitchWheelValues [16];
  30910. /** Searches through the voices to find one that's not currently playing, and which
  30911. can play the given sound.
  30912. Returns 0 if all voices are busy and stealing isn't enabled.
  30913. This can be overridden to implement custom voice-stealing algorithms.
  30914. */
  30915. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  30916. const bool stealIfNoneAvailable) const;
  30917. /** Starts a specified voice playing a particular sound.
  30918. You'll probably never need to call this, it's used internally by noteOn(), but
  30919. may be needed by subclasses for custom behaviours.
  30920. */
  30921. void startVoice (SynthesiserVoice* voice,
  30922. SynthesiserSound* sound,
  30923. int midiChannel,
  30924. int midiNoteNumber,
  30925. float velocity);
  30926. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  30927. int findFreeVoice (const bool) const { return 0; }
  30928. private:
  30929. double sampleRate;
  30930. uint32 lastNoteOnCounter;
  30931. bool shouldStealNotes;
  30932. Synthesiser (const Synthesiser&);
  30933. Synthesiser& operator= (const Synthesiser&);
  30934. };
  30935. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  30936. /*** End of inlined file: juce_Synthesiser.h ***/
  30937. /**
  30938. A subclass of SynthesiserSound that represents a sampled audio clip.
  30939. This is a pretty basic sampler, and just attempts to load the whole audio stream
  30940. into memory.
  30941. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  30942. give it some SampledSound objects to play.
  30943. @see SamplerVoice, Synthesiser, SynthesiserSound
  30944. */
  30945. class JUCE_API SamplerSound : public SynthesiserSound
  30946. {
  30947. public:
  30948. /** Creates a sampled sound from an audio reader.
  30949. This will attempt to load the audio from the source into memory and store
  30950. it in this object.
  30951. @param name a name for the sample
  30952. @param source the audio to load. This object can be safely deleted by the
  30953. caller after this constructor returns
  30954. @param midiNotes the set of midi keys that this sound should be played on. This
  30955. is used by the SynthesiserSound::appliesToNote() method
  30956. @param midiNoteForNormalPitch the midi note at which the sample should be played
  30957. with its natural rate. All other notes will be pitched
  30958. up or down relative to this one
  30959. @param attackTimeSecs the attack (fade-in) time, in seconds
  30960. @param releaseTimeSecs the decay (fade-out) time, in seconds
  30961. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  30962. source, in seconds
  30963. */
  30964. SamplerSound (const String& name,
  30965. AudioFormatReader& source,
  30966. const BigInteger& midiNotes,
  30967. int midiNoteForNormalPitch,
  30968. double attackTimeSecs,
  30969. double releaseTimeSecs,
  30970. double maxSampleLengthSeconds);
  30971. /** Destructor. */
  30972. ~SamplerSound();
  30973. /** Returns the sample's name */
  30974. const String& getName() const { return name; }
  30975. /** Returns the audio sample data.
  30976. This could be 0 if there was a problem loading it.
  30977. */
  30978. AudioSampleBuffer* getAudioData() const { return data; }
  30979. bool appliesToNote (const int midiNoteNumber);
  30980. bool appliesToChannel (const int midiChannel);
  30981. juce_UseDebuggingNewOperator
  30982. private:
  30983. friend class SamplerVoice;
  30984. String name;
  30985. ScopedPointer <AudioSampleBuffer> data;
  30986. double sourceSampleRate;
  30987. BigInteger midiNotes;
  30988. int length, attackSamples, releaseSamples;
  30989. int midiRootNote;
  30990. };
  30991. /**
  30992. A subclass of SynthesiserVoice that can play a SamplerSound.
  30993. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  30994. give it some SampledSound objects to play.
  30995. @see SamplerSound, Synthesiser, SynthesiserVoice
  30996. */
  30997. class JUCE_API SamplerVoice : public SynthesiserVoice
  30998. {
  30999. public:
  31000. /** Creates a SamplerVoice.
  31001. */
  31002. SamplerVoice();
  31003. /** Destructor. */
  31004. ~SamplerVoice();
  31005. bool canPlaySound (SynthesiserSound* sound);
  31006. void startNote (const int midiNoteNumber,
  31007. const float velocity,
  31008. SynthesiserSound* sound,
  31009. const int currentPitchWheelPosition);
  31010. void stopNote (const bool allowTailOff);
  31011. void pitchWheelMoved (const int newValue);
  31012. void controllerMoved (const int controllerNumber,
  31013. const int newValue);
  31014. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  31015. juce_UseDebuggingNewOperator
  31016. private:
  31017. double pitchRatio;
  31018. double sourceSamplePosition;
  31019. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  31020. bool isInAttack, isInRelease;
  31021. };
  31022. #endif // __JUCE_SAMPLER_JUCEHEADER__
  31023. /*** End of inlined file: juce_Sampler.h ***/
  31024. #endif
  31025. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  31026. #endif
  31027. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31028. /*** Start of inlined file: juce_ActionBroadcaster.h ***/
  31029. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31030. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31031. /*** Start of inlined file: juce_ActionListenerList.h ***/
  31032. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31033. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31034. /**
  31035. A set of ActionListeners.
  31036. Listeners can be added and removed from the list, and messages can be
  31037. broadcast to all the listeners.
  31038. @see ActionListener, ActionBroadcaster
  31039. */
  31040. class JUCE_API ActionListenerList : public MessageListener
  31041. {
  31042. public:
  31043. /** Creates an empty list. */
  31044. ActionListenerList() throw();
  31045. /** Destructor. */
  31046. ~ActionListenerList() throw();
  31047. /** Adds a listener to the list.
  31048. (Trying to add a listener that's already on the list will have no effect).
  31049. */
  31050. void addActionListener (ActionListener* listener) throw();
  31051. /** Removes a listener from the list.
  31052. If the listener isn't on the list, this won't have any effect.
  31053. */
  31054. void removeActionListener (ActionListener* listener) throw();
  31055. /** Removes all listeners from the list. */
  31056. void removeAllActionListeners() throw();
  31057. /** Broadcasts a message to all the registered listeners.
  31058. This sends the message asynchronously.
  31059. If a listener is on the list when this method is called but is removed from
  31060. the list before the message arrives, it won't receive the message. Similarly
  31061. listeners that are added to the list after the message is sent but before it
  31062. arrives won't get the message either.
  31063. */
  31064. void sendActionMessage (const String& message) const;
  31065. /** @internal */
  31066. void handleMessage (const Message&);
  31067. juce_UseDebuggingNewOperator
  31068. private:
  31069. SortedSet <void*> actionListeners_;
  31070. CriticalSection actionListenerLock_;
  31071. ActionListenerList (const ActionListenerList&);
  31072. ActionListenerList& operator= (const ActionListenerList&);
  31073. };
  31074. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31075. /*** End of inlined file: juce_ActionListenerList.h ***/
  31076. /** Manages a list of ActionListeners, and can send them messages.
  31077. To quickly add methods to your class that can add/remove action
  31078. listeners and broadcast to them, you can derive from this.
  31079. @see ActionListenerList, ActionListener
  31080. */
  31081. class JUCE_API ActionBroadcaster
  31082. {
  31083. public:
  31084. /** Creates an ActionBroadcaster. */
  31085. ActionBroadcaster() throw();
  31086. /** Destructor. */
  31087. virtual ~ActionBroadcaster();
  31088. /** Adds a listener to the list.
  31089. (Trying to add a listener that's already on the list will have no effect).
  31090. */
  31091. void addActionListener (ActionListener* listener);
  31092. /** Removes a listener from the list.
  31093. If the listener isn't on the list, this won't have any effect.
  31094. */
  31095. void removeActionListener (ActionListener* listener);
  31096. /** Removes all listeners from the list. */
  31097. void removeAllActionListeners();
  31098. /** Broadcasts a message to all the registered listeners.
  31099. @see ActionListenerList::sendActionMessage
  31100. */
  31101. void sendActionMessage (const String& message) const;
  31102. private:
  31103. ActionListenerList actionListenerList;
  31104. ActionBroadcaster (const ActionBroadcaster&);
  31105. ActionBroadcaster& operator= (const ActionBroadcaster&);
  31106. };
  31107. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31108. /*** End of inlined file: juce_ActionBroadcaster.h ***/
  31109. #endif
  31110. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  31111. #endif
  31112. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31113. #endif
  31114. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  31115. #endif
  31116. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31117. /*** Start of inlined file: juce_CallbackMessage.h ***/
  31118. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31119. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31120. /**
  31121. A message that calls a custom function when it gets delivered.
  31122. You can use this class to fire off actions that you want to be performed later
  31123. on the message thread.
  31124. Unlike other Message objects, these don't get sent to a MessageListener, you
  31125. just call the post() method to send them, and when they arrive, your
  31126. messageCallback() method will automatically be invoked.
  31127. @see MessageListener, MessageManager, ActionListener, ChangeListener
  31128. */
  31129. class JUCE_API CallbackMessage : public Message
  31130. {
  31131. public:
  31132. CallbackMessage() throw();
  31133. /** Destructor. */
  31134. ~CallbackMessage() throw();
  31135. /** Called when the message is delivered.
  31136. You should implement this method and make it do whatever action you want
  31137. to perform.
  31138. Note that like all other messages, this object will be deleted immediately
  31139. after this method has been invoked.
  31140. */
  31141. virtual void messageCallback() = 0;
  31142. /** Instead of sending this message to a MessageListener, just call this method
  31143. to post it to the event queue.
  31144. After you've called this, this object will belong to the MessageManager,
  31145. which will delete it later. So make sure you don't delete the object yourself,
  31146. call post() more than once, or call post() on a stack-based obect!
  31147. */
  31148. void post();
  31149. juce_UseDebuggingNewOperator
  31150. private:
  31151. CallbackMessage (const CallbackMessage&);
  31152. CallbackMessage& operator= (const CallbackMessage&);
  31153. };
  31154. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31155. /*** End of inlined file: juce_CallbackMessage.h ***/
  31156. #endif
  31157. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  31158. #endif
  31159. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  31160. #endif
  31161. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  31162. #endif
  31163. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31164. /*** Start of inlined file: juce_InterprocessConnection.h ***/
  31165. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31166. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31167. class InterprocessConnectionServer;
  31168. /**
  31169. Manages a simple two-way messaging connection to another process, using either
  31170. a socket or a named pipe as the transport medium.
  31171. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  31172. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  31173. and incoming messages will result in a callback via the messageReceived()
  31174. method.
  31175. To open a pipe and wait for another client to connect to it, use the createPipe()
  31176. method.
  31177. To act as a socket server and create connections for one or more client, see the
  31178. InterprocessConnectionServer class.
  31179. @see InterprocessConnectionServer, Socket, NamedPipe
  31180. */
  31181. class JUCE_API InterprocessConnection : public Thread,
  31182. private MessageListener
  31183. {
  31184. public:
  31185. /** Creates a connection.
  31186. Connections are created manually, connecting them with the connectToSocket()
  31187. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  31188. when a client wants to connect.
  31189. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  31190. connectionLost() and messageReceived() methods will
  31191. always be made using the message thread; if false,
  31192. these will be called immediately on the connection's
  31193. own thread.
  31194. @param magicMessageHeaderNumber a magic number to use in the header to check the
  31195. validity of the data blocks being sent and received. This
  31196. can be any number, but the sender and receiver must obviously
  31197. use matching values or they won't recognise each other.
  31198. */
  31199. InterprocessConnection (bool callbacksOnMessageThread = true,
  31200. uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  31201. /** Destructor. */
  31202. ~InterprocessConnection();
  31203. /** Tries to connect this object to a socket.
  31204. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  31205. object waiting to receive client connections on this port number.
  31206. @param hostName the host computer, either a network address or name
  31207. @param portNumber the socket port number to try to connect to
  31208. @param timeOutMillisecs how long to keep trying before giving up
  31209. @returns true if the connection is established successfully
  31210. @see Socket
  31211. */
  31212. bool connectToSocket (const String& hostName,
  31213. int portNumber,
  31214. int timeOutMillisecs);
  31215. /** Tries to connect the object to an existing named pipe.
  31216. For this to work, another process on the same computer must already have opened
  31217. an InterprocessConnection object and used createPipe() to create a pipe for this
  31218. to connect to.
  31219. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  31220. @returns true if it connects successfully.
  31221. @see createPipe, NamedPipe
  31222. */
  31223. bool connectToPipe (const String& pipeName,
  31224. int pipeReceiveMessageTimeoutMs = -1);
  31225. /** Tries to create a new pipe for other processes to connect to.
  31226. This creates a pipe with the given name, so that other processes can use
  31227. connectToPipe() to connect to the other end.
  31228. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  31229. If another process is already using this pipe, this will fail and return false.
  31230. */
  31231. bool createPipe (const String& pipeName,
  31232. int pipeReceiveMessageTimeoutMs = -1);
  31233. /** Disconnects and closes any currently-open sockets or pipes. */
  31234. void disconnect();
  31235. /** True if a socket or pipe is currently active. */
  31236. bool isConnected() const;
  31237. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  31238. StreamingSocket* getSocket() const throw() { return socket; }
  31239. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  31240. NamedPipe* getPipe() const throw() { return pipe; }
  31241. /** Returns the name of the machine at the other end of this connection.
  31242. This will return an empty string if the other machine isn't known for
  31243. some reason.
  31244. */
  31245. const String getConnectedHostName() const;
  31246. /** Tries to send a message to the other end of this connection.
  31247. This will fail if it's not connected, or if there's some kind of write error. If
  31248. it succeeds, the connection object at the other end will receive the message by
  31249. a callback to its messageReceived() method.
  31250. @see messageReceived
  31251. */
  31252. bool sendMessage (const MemoryBlock& message);
  31253. /** Called when the connection is first connected.
  31254. If the connection was created with the callbacksOnMessageThread flag set, then
  31255. this will be called on the message thread; otherwise it will be called on a server
  31256. thread.
  31257. */
  31258. virtual void connectionMade() = 0;
  31259. /** Called when the connection is broken.
  31260. If the connection was created with the callbacksOnMessageThread flag set, then
  31261. this will be called on the message thread; otherwise it will be called on a server
  31262. thread.
  31263. */
  31264. virtual void connectionLost() = 0;
  31265. /** Called when a message arrives.
  31266. When the object at the other end of this connection sends us a message with sendMessage(),
  31267. this callback is used to deliver it to us.
  31268. If the connection was created with the callbacksOnMessageThread flag set, then
  31269. this will be called on the message thread; otherwise it will be called on a server
  31270. thread.
  31271. @see sendMessage
  31272. */
  31273. virtual void messageReceived (const MemoryBlock& message) = 0;
  31274. juce_UseDebuggingNewOperator
  31275. private:
  31276. CriticalSection pipeAndSocketLock;
  31277. ScopedPointer <StreamingSocket> socket;
  31278. ScopedPointer <NamedPipe> pipe;
  31279. bool callbackConnectionState;
  31280. const bool useMessageThread;
  31281. const uint32 magicMessageHeader;
  31282. int pipeReceiveMessageTimeout;
  31283. friend class InterprocessConnectionServer;
  31284. void initialiseWithSocket (StreamingSocket* socket_);
  31285. void initialiseWithPipe (NamedPipe* pipe_);
  31286. void handleMessage (const Message& message);
  31287. void connectionMadeInt();
  31288. void connectionLostInt();
  31289. void deliverDataInt (const MemoryBlock& data);
  31290. bool readNextMessageInt();
  31291. void run();
  31292. InterprocessConnection (const InterprocessConnection&);
  31293. InterprocessConnection& operator= (const InterprocessConnection&);
  31294. };
  31295. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31296. /*** End of inlined file: juce_InterprocessConnection.h ***/
  31297. #endif
  31298. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31299. /*** Start of inlined file: juce_InterprocessConnectionServer.h ***/
  31300. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31301. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31302. /**
  31303. An object that waits for client sockets to connect to a port on this host, and
  31304. creates InterprocessConnection objects for each one.
  31305. To use this, create a class derived from it which implements the createConnectionObject()
  31306. method, so that it creates suitable connection objects for each client that tries
  31307. to connect.
  31308. @see InterprocessConnection
  31309. */
  31310. class JUCE_API InterprocessConnectionServer : private Thread
  31311. {
  31312. public:
  31313. /** Creates an uninitialised server object.
  31314. */
  31315. InterprocessConnectionServer();
  31316. /** Destructor. */
  31317. ~InterprocessConnectionServer();
  31318. /** Starts an internal thread which listens on the given port number.
  31319. While this is running, in another process tries to connect with the
  31320. InterprocessConnection::connectToSocket() method, this object will call
  31321. createConnectionObject() to create a connection to that client.
  31322. Use stop() to stop the thread running.
  31323. @see createConnectionObject, stop
  31324. */
  31325. bool beginWaitingForSocket (int portNumber);
  31326. /** Terminates the listener thread, if it's active.
  31327. @see beginWaitingForSocket
  31328. */
  31329. void stop();
  31330. protected:
  31331. /** Creates a suitable connection object for a client process that wants to
  31332. connect to this one.
  31333. This will be called by the listener thread when a client process tries
  31334. to connect, and must return a new InterprocessConnection object that will
  31335. then run as this end of the connection.
  31336. @see InterprocessConnection
  31337. */
  31338. virtual InterprocessConnection* createConnectionObject() = 0;
  31339. public:
  31340. juce_UseDebuggingNewOperator
  31341. private:
  31342. ScopedPointer <StreamingSocket> socket;
  31343. void run();
  31344. InterprocessConnectionServer (const InterprocessConnectionServer&);
  31345. InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  31346. };
  31347. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31348. /*** End of inlined file: juce_InterprocessConnectionServer.h ***/
  31349. #endif
  31350. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  31351. #endif
  31352. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  31353. #endif
  31354. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  31355. #endif
  31356. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31357. /*** Start of inlined file: juce_MessageManager.h ***/
  31358. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31359. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31360. class Component;
  31361. class MessageManagerLock;
  31362. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  31363. */
  31364. typedef void* (MessageCallbackFunction) (void* userData);
  31365. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  31366. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  31367. */
  31368. class JUCE_API MessageManager
  31369. {
  31370. public:
  31371. /** Returns the global instance of the MessageManager. */
  31372. static MessageManager* getInstance() throw();
  31373. /** Runs the event dispatch loop until a stop message is posted.
  31374. This method is only intended to be run by the application's startup routine,
  31375. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  31376. @see stopDispatchLoop
  31377. */
  31378. void runDispatchLoop();
  31379. /** Sends a signal that the dispatch loop should terminate.
  31380. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  31381. will be interrupted and will return.
  31382. @see runDispatchLoop
  31383. */
  31384. void stopDispatchLoop();
  31385. /** Returns true if the stopDispatchLoop() method has been called.
  31386. */
  31387. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  31388. /** Synchronously dispatches messages until a given time has elapsed.
  31389. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  31390. otherwise returns true.
  31391. */
  31392. bool runDispatchLoopUntil (int millisecondsToRunFor);
  31393. /** Calls a function using the message-thread.
  31394. This can be used by any thread to cause this function to be called-back
  31395. by the message thread. If it's the message-thread that's calling this method,
  31396. then the function will just be called; if another thread is calling, a message
  31397. will be posted to the queue, and this method will block until that message
  31398. is delivered, the function is called, and the result is returned.
  31399. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  31400. thread has a critical section locked, which an unrelated message callback then tries to lock
  31401. before the message thread gets round to processing this callback.
  31402. @param callback the function to call - its signature must be @code
  31403. void* myCallbackFunction (void*) @endcode
  31404. @param userData a user-defined pointer that will be passed to the function that gets called
  31405. @returns the value that the callback function returns.
  31406. @see MessageManagerLock
  31407. */
  31408. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  31409. void* userData);
  31410. /** Returns true if the caller-thread is the message thread. */
  31411. bool isThisTheMessageThread() const throw();
  31412. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  31413. (Best to ignore this method unless you really know what you're doing..)
  31414. @see getCurrentMessageThread
  31415. */
  31416. void setCurrentThreadAsMessageThread();
  31417. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  31418. (Best to ignore this method unless you really know what you're doing..)
  31419. @see setCurrentMessageThread
  31420. */
  31421. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  31422. /** Returns true if the caller thread has currenltly got the message manager locked.
  31423. see the MessageManagerLock class for more info about this.
  31424. This will be true if the caller is the message thread, because that automatically
  31425. gains a lock while a message is being dispatched.
  31426. */
  31427. bool currentThreadHasLockedMessageManager() const throw();
  31428. /** Sends a message to all other JUCE applications that are running.
  31429. @param messageText the string that will be passed to the actionListenerCallback()
  31430. method of the broadcast listeners in the other app.
  31431. @see registerBroadcastListener, ActionListener
  31432. */
  31433. static void broadcastMessage (const String& messageText) throw();
  31434. /** Registers a listener to get told about broadcast messages.
  31435. The actionListenerCallback() callback's string parameter
  31436. is the message passed into broadcastMessage().
  31437. @see broadcastMessage
  31438. */
  31439. void registerBroadcastListener (ActionListener* listener) throw();
  31440. /** Deregisters a broadcast listener. */
  31441. void deregisterBroadcastListener (ActionListener* listener) throw();
  31442. /** @internal */
  31443. void deliverMessage (void*);
  31444. /** @internal */
  31445. void deliverBroadcastMessage (const String&);
  31446. /** @internal */
  31447. ~MessageManager() throw();
  31448. juce_UseDebuggingNewOperator
  31449. private:
  31450. MessageManager() throw();
  31451. friend class MessageListener;
  31452. friend class ChangeBroadcaster;
  31453. friend class ActionBroadcaster;
  31454. friend class CallbackMessage;
  31455. static MessageManager* instance;
  31456. SortedSet <const MessageListener*> messageListeners;
  31457. ScopedPointer <ActionListenerList> broadcastListeners;
  31458. friend class JUCEApplication;
  31459. bool quitMessagePosted, quitMessageReceived;
  31460. Thread::ThreadID messageThreadId;
  31461. static void* exitModalLoopCallback (void*);
  31462. void postMessageToQueue (Message* message);
  31463. void postCallbackMessage (Message* message);
  31464. static void doPlatformSpecificInitialisation();
  31465. static void doPlatformSpecificShutdown();
  31466. friend class MessageManagerLock;
  31467. Thread::ThreadID volatile threadWithLock;
  31468. CriticalSection lockingLock;
  31469. MessageManager (const MessageManager&);
  31470. MessageManager& operator= (const MessageManager&);
  31471. };
  31472. /** Used to make sure that the calling thread has exclusive access to the message loop.
  31473. Because it's not thread-safe to call any of the Component or other UI classes
  31474. from threads other than the message thread, one of these objects can be used to
  31475. lock the message loop and allow this to be done. The message thread will be
  31476. suspended for the lifetime of the MessageManagerLock object, so create one on
  31477. the stack like this: @code
  31478. void MyThread::run()
  31479. {
  31480. someData = 1234;
  31481. const MessageManagerLock mmLock;
  31482. // the event loop will now be locked so it's safe to make a few calls..
  31483. myComponent->setBounds (newBounds);
  31484. myComponent->repaint();
  31485. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  31486. }
  31487. @endcode
  31488. Obviously be careful not to create one of these and leave it lying around, or
  31489. your app will grind to a halt!
  31490. Another caveat is that using this in conjunction with other CriticalSections
  31491. can create lots of interesting ways of producing a deadlock! In particular, if
  31492. your message thread calls stopThread() for a thread that uses these locks,
  31493. you'll get an (occasional) deadlock..
  31494. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  31495. */
  31496. class JUCE_API MessageManagerLock
  31497. {
  31498. public:
  31499. /** Tries to acquire a lock on the message manager.
  31500. The constructor attempts to gain a lock on the message loop, and the lock will be
  31501. kept for the lifetime of this object.
  31502. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  31503. this method will keep checking whether the thread has been given the
  31504. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  31505. without gaining the lock. If you pass a thread, you must check whether the lock was
  31506. successful by calling lockWasGained(). If this is false, your thread is being told to
  31507. die, so you should take evasive action.
  31508. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  31509. careful when doing this, because it's very easy to deadlock if your message thread
  31510. attempts to call stopThread() on a thread just as that thread attempts to get the
  31511. message lock.
  31512. If the calling thread already has the lock, nothing will be done, so it's safe and
  31513. quick to use these locks recursively.
  31514. E.g.
  31515. @code
  31516. void run()
  31517. {
  31518. ...
  31519. while (! threadShouldExit())
  31520. {
  31521. MessageManagerLock mml (Thread::getCurrentThread());
  31522. if (! mml.lockWasGained())
  31523. return; // another thread is trying to kill us!
  31524. ..do some locked stuff here..
  31525. }
  31526. ..and now the MM is now unlocked..
  31527. }
  31528. @endcode
  31529. */
  31530. MessageManagerLock (Thread* threadToCheckForExitSignal = 0) throw();
  31531. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  31532. instead of a thread.
  31533. See the MessageManagerLock (Thread*) constructor for details on how this works.
  31534. */
  31535. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal) throw();
  31536. /** Releases the current thread's lock on the message manager.
  31537. Make sure this object is created and deleted by the same thread,
  31538. otherwise there are no guarantees what will happen!
  31539. */
  31540. ~MessageManagerLock() throw();
  31541. /** Returns true if the lock was successfully acquired.
  31542. (See the constructor that takes a Thread for more info).
  31543. */
  31544. bool lockWasGained() const throw() { return locked; }
  31545. private:
  31546. class SharedEvents;
  31547. class BlockingMessage;
  31548. friend class SharedEvents;
  31549. friend class BlockingMessage;
  31550. SharedEvents* sharedEvents;
  31551. bool locked;
  31552. void init (Thread* thread, ThreadPoolJob* job) throw();
  31553. MessageManagerLock (const MessageManagerLock&);
  31554. MessageManagerLock& operator= (const MessageManagerLock&);
  31555. };
  31556. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31557. /*** End of inlined file: juce_MessageManager.h ***/
  31558. #endif
  31559. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  31560. /*** Start of inlined file: juce_MultiTimer.h ***/
  31561. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  31562. #define __JUCE_MULTITIMER_JUCEHEADER__
  31563. /**
  31564. A type of timer class that can run multiple timers with different frequencies,
  31565. all of which share a single callback.
  31566. This class is very similar to the Timer class, but allows you run multiple
  31567. separate timers, where each one has a unique ID number. The methods in this
  31568. class are exactly equivalent to those in Timer, but with the addition of
  31569. this ID number.
  31570. To use it, you need to create a subclass of MultiTimer, implementing the
  31571. timerCallback() method. Then you can start timers with startTimer(), and
  31572. each time the callback is triggered, it passes in the ID of the timer that
  31573. caused it.
  31574. @see Timer
  31575. */
  31576. class JUCE_API MultiTimer
  31577. {
  31578. protected:
  31579. /** Creates a MultiTimer.
  31580. When created, no timers are running, so use startTimer() to start things off.
  31581. */
  31582. MultiTimer() throw();
  31583. /** Creates a copy of another timer.
  31584. Note that this timer will not contain any running timers, even if the one you're
  31585. copying from was running.
  31586. */
  31587. MultiTimer (const MultiTimer& other) throw();
  31588. public:
  31589. /** Destructor. */
  31590. virtual ~MultiTimer();
  31591. /** The user-defined callback routine that actually gets called by each of the
  31592. timers that are running.
  31593. It's perfectly ok to call startTimer() or stopTimer() from within this
  31594. callback to change the subsequent intervals.
  31595. */
  31596. virtual void timerCallback (int timerId) = 0;
  31597. /** Starts a timer and sets the length of interval required.
  31598. If the timer is already started, this will reset it, so the
  31599. time between calling this method and the next timer callback
  31600. will not be less than the interval length passed in.
  31601. @param timerId a unique Id number that identifies the timer to
  31602. start. This is the id that will be passed back
  31603. to the timerCallback() method when this timer is
  31604. triggered
  31605. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  31606. rounded up to 1)
  31607. */
  31608. void startTimer (int timerId, int intervalInMilliseconds) throw();
  31609. /** Stops a timer.
  31610. If a timer has been started with the given ID number, it will be cancelled.
  31611. No more callbacks will be made for the specified timer after this method returns.
  31612. If this is called from a different thread, any callbacks that may
  31613. be currently executing may be allowed to finish before the method
  31614. returns.
  31615. */
  31616. void stopTimer (int timerId) throw();
  31617. /** Checks whether a timer has been started for a specified ID.
  31618. @returns true if a timer with the given ID is running.
  31619. */
  31620. bool isTimerRunning (int timerId) const throw();
  31621. /** Returns the interval for a specified timer ID.
  31622. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  31623. is running for the ID number specified.
  31624. */
  31625. int getTimerInterval (int timerId) const throw();
  31626. private:
  31627. class MultiTimerCallback;
  31628. CriticalSection timerListLock;
  31629. OwnedArray <MultiTimerCallback> timers;
  31630. MultiTimer& operator= (const MultiTimer&);
  31631. };
  31632. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  31633. /*** End of inlined file: juce_MultiTimer.h ***/
  31634. #endif
  31635. #ifndef __JUCE_TIMER_JUCEHEADER__
  31636. #endif
  31637. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31638. /*** Start of inlined file: juce_ArrowButton.h ***/
  31639. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31640. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  31641. /*** Start of inlined file: juce_DropShadowEffect.h ***/
  31642. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31643. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31644. /**
  31645. An effect filter that adds a drop-shadow behind the image's content.
  31646. (This will only work on images/components that aren't opaque, of course).
  31647. When added to a component, this effect will draw a soft-edged
  31648. shadow based on what gets drawn inside it. The shadow will also
  31649. be applied to the component's children.
  31650. For speed, this doesn't use a proper gaussian blur, but cheats by
  31651. using a simple bilinear filter. If you need a really high-quality
  31652. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  31653. @see Component::setComponentEffect
  31654. */
  31655. class JUCE_API DropShadowEffect : public ImageEffectFilter
  31656. {
  31657. public:
  31658. /** Creates a default drop-shadow effect.
  31659. To customise the shadow's appearance, use the setShadowProperties()
  31660. method.
  31661. */
  31662. DropShadowEffect();
  31663. /** Destructor. */
  31664. ~DropShadowEffect();
  31665. /** Sets up parameters affecting the shadow's appearance.
  31666. @param newRadius the (approximate) radius of the blur used
  31667. @param newOpacity the opacity with which the shadow is rendered
  31668. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  31669. component's contents
  31670. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  31671. component's contents
  31672. */
  31673. void setShadowProperties (float newRadius,
  31674. float newOpacity,
  31675. int newShadowOffsetX,
  31676. int newShadowOffsetY);
  31677. /** @internal */
  31678. void applyEffect (Image& sourceImage, Graphics& destContext);
  31679. juce_UseDebuggingNewOperator
  31680. private:
  31681. int offsetX, offsetY;
  31682. float radius, opacity;
  31683. };
  31684. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31685. /*** End of inlined file: juce_DropShadowEffect.h ***/
  31686. /**
  31687. A button with an arrow in it.
  31688. @see Button
  31689. */
  31690. class JUCE_API ArrowButton : public Button
  31691. {
  31692. public:
  31693. /** Creates an ArrowButton.
  31694. @param buttonName the name to give the button
  31695. @param arrowDirection the direction the arrow should point in, where 0.0 is
  31696. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  31697. @param arrowColour the colour to use for the arrow
  31698. */
  31699. ArrowButton (const String& buttonName,
  31700. float arrowDirection,
  31701. const Colour& arrowColour);
  31702. /** Destructor. */
  31703. ~ArrowButton();
  31704. juce_UseDebuggingNewOperator
  31705. protected:
  31706. /** @internal */
  31707. void paintButton (Graphics& g,
  31708. bool isMouseOverButton,
  31709. bool isButtonDown);
  31710. /** @internal */
  31711. void buttonStateChanged();
  31712. private:
  31713. Colour colour;
  31714. DropShadowEffect shadow;
  31715. Path path;
  31716. int offset;
  31717. ArrowButton (const ArrowButton&);
  31718. ArrowButton& operator= (const ArrowButton&);
  31719. };
  31720. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  31721. /*** End of inlined file: juce_ArrowButton.h ***/
  31722. #endif
  31723. #ifndef __JUCE_BUTTON_JUCEHEADER__
  31724. #endif
  31725. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31726. /*** Start of inlined file: juce_DrawableButton.h ***/
  31727. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31728. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31729. /*** Start of inlined file: juce_Drawable.h ***/
  31730. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  31731. #define __JUCE_DRAWABLE_JUCEHEADER__
  31732. /*** Start of inlined file: juce_RelativeCoordinate.h ***/
  31733. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  31734. #define __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  31735. /**
  31736. Expresses a coordinate as an absolute or proportional distance from other
  31737. named coordinates.
  31738. A RelativeCoordinate represents a position as either:
  31739. - an absolute distance from the origin
  31740. - an absolute distance from another named RelativeCoordinate
  31741. - a proportion of the distance between two other named RelativeCoordinates
  31742. Of course, the coordinates that this one is relative to may themselves be relative
  31743. to other coordinates, so complex arrangements can be built up (as long as you're careful
  31744. not to create recursive loops!)
  31745. Rather than keeping pointers to the coordinates that this one is dependent on, it
  31746. stores their names, and when resolving this coordinate to an absolute value, a
  31747. NamedCoordinateFinder class is required to retrieve these coordinates by name.
  31748. @see RelativePoint, RelativeRectangle
  31749. */
  31750. class JUCE_API RelativeCoordinate
  31751. {
  31752. public:
  31753. /** Creates a zero coordinate. */
  31754. RelativeCoordinate();
  31755. /** Creates an absolute position from the parent origin on either the X or Y axis.
  31756. @param absoluteDistanceFromOrigin the distance from the origin
  31757. @param isHorizontal this must be true if this is an X coordinate, or false if it's on the Y axis.
  31758. */
  31759. RelativeCoordinate (double absoluteDistanceFromOrigin, bool isHorizontal);
  31760. /** Creates an absolute position relative to a named coordinate.
  31761. @param absoluteDistanceFromAnchor the distance to add to the named anchor point
  31762. @param anchorPoint the name of the coordinate from which this one will be relative. See the constructor
  31763. notes for a description of the syntax for coordinate names.
  31764. */
  31765. RelativeCoordinate (double absoluteDistanceFromAnchor, const String& anchorPoint);
  31766. /** Creates a relative position between two named points.
  31767. @param relativeProportionBetweenAnchors a value between 0 and 1 indicating this coordinate's relative position
  31768. between anchorPoint1 and anchorPoint2.
  31769. @param anchorPoint1 the name of the first coordinate from which this one will be relative. See the constructor
  31770. notes for a description of the syntax for coordinate names.
  31771. @param anchorPoint2 the name of the first coordinate from which this one will be relative. See the constructor
  31772. notes for a description of the syntax for coordinate names.
  31773. */
  31774. RelativeCoordinate (double relativeProportionBetweenAnchors, const String& anchorPoint1, const String& anchorPoint2);
  31775. /** Recreates a coordinate from a string description.
  31776. The string can be in one of the following formats:
  31777. - "123" = 123 pixels from parent origin (this is equivalent to "parent.left + 123"
  31778. or "parent.top + 123", depending on which axis the coordinate is using)
  31779. - "anchor" = the same position as the coordinate named "anchor"
  31780. - "anchor + 123" = the coordinate named "anchor" + 123 pixels
  31781. - "anchor - 123" = the coordinate named "anchor" - 123 pixels
  31782. - "50%" = 50% of the distance between the coordinate space's top-left origin and its extent
  31783. (this is equivalent to "50% * parent.left -> parent.right" or "50% * parent.top -> parent.bottom")
  31784. - "50% * anchor" = 50% of the distance between the coordinate space's origin and the coordinate named "anchor"
  31785. (this is equivalent to "50% * parent.left -> anchor" or "50% * parent.top -> anchor")
  31786. - "50% * anchor1 -> anchor2" = 50% of the distance between the coordinate "anchor1" and the coordinate "anchor2"
  31787. An anchor name can either be just a single identifier (letters, digits and underscores only - no spaces),
  31788. e.g. "marker1", or it can be a two-part name in the form "objectName.edge". For example "parent.left" is
  31789. the origin, or "myComponent.top" is the top edge of a component called "myComponent". The exact names that
  31790. will be recognised are dependent on the NamedCoordinateFinder that you provide for looking them up, but
  31791. "parent.left" and "parent.top" are always available, meaning the origin. "parent.right" and "parent.bottom"
  31792. may also be available if the coordinate space has a fixed size.
  31793. @param stringVersion the string to parse
  31794. @param isHorizontal this must be true if this is an X coordinate, or false if it's on the Y axis.
  31795. @see toString
  31796. */
  31797. RelativeCoordinate (const String& stringVersion, bool isHorizontal);
  31798. /** Destructor. */
  31799. ~RelativeCoordinate();
  31800. bool operator== (const RelativeCoordinate& other) const throw();
  31801. bool operator!= (const RelativeCoordinate& other) const throw();
  31802. /**
  31803. Provides an interface for looking up the position of a named anchor when resolving a RelativeCoordinate.
  31804. When using RelativeCoordinates, to resolve their names you need to provide a subclass of this which
  31805. can retrieve a coordinate by name.
  31806. */
  31807. class JUCE_API NamedCoordinateFinder
  31808. {
  31809. public:
  31810. /** Destructor. */
  31811. virtual ~NamedCoordinateFinder() {}
  31812. /** Returns the coordinate for a given name.
  31813. The objectName parameter will be the first section of the name, and the edge the name of the second part.
  31814. E.g. for "parent.right", objectName would be "parent" and edge would be "right". If the name
  31815. has no dot, the edge parameter will be an empty string.
  31816. This method must be able to resolve "parent.left", "parent.top", "parent.right" and "parent.bottom", as
  31817. well as any other objects that your application uses.
  31818. */
  31819. virtual const RelativeCoordinate findNamedCoordinate (const String& objectName, const String& edge) const = 0;
  31820. };
  31821. /** Calculates the absolute position of this coordinate.
  31822. You'll need to provide a suitable NamedCoordinateFinder for looking up any coordinates that may
  31823. be needed to calculate the result.
  31824. */
  31825. double resolve (const NamedCoordinateFinder* nameFinder) const;
  31826. /** Returns true if this coordinate uses the specified coord name at any level in its evaluation.
  31827. This will recursively check any coordinates upon which this one depends.
  31828. */
  31829. bool references (const String& coordName, const NamedCoordinateFinder* nameFinder) const;
  31830. /** Returns true if there's a recursive loop when trying to resolve this coordinate's position. */
  31831. bool isRecursive (const NamedCoordinateFinder* nameFinder) const;
  31832. /** Returns true if this coordinate depends on any other coordinates for its position. */
  31833. bool isDynamic() const;
  31834. /** Changes the value of this coord to make it resolve to the specified position.
  31835. Calling this will leave the anchor points unchanged, but will set this coordinate's absolute
  31836. or relative position to whatever value is necessary to make its resultant position
  31837. match the position that is provided.
  31838. */
  31839. void moveToAbsolute (double absoluteTargetPosition, const NamedCoordinateFinder* nameFinder);
  31840. /** Returns true if the coordinate is calculated as a proportion of the distance between two other points.
  31841. @see toggleProportionality
  31842. */
  31843. bool isProportional() const throw() { return anchor2.isNotEmpty(); }
  31844. /** Toggles the coordinate between using a proportional or absolute position.
  31845. Note that calling this will reset the names of any anchor points, and just make the
  31846. coordinate relative to the parent origin and parent size.
  31847. */
  31848. void toggleProportionality (const NamedCoordinateFinder* nameFinder, bool isHorizontal);
  31849. /** Returns a value that can be edited to set this coordinate's position.
  31850. The meaning of this number depends on the coordinate's mode. If the coordinate is
  31851. proportional, the number will be a percentage between 0 and 100. If the
  31852. coordinate is absolute, then it will be the number of pixels from its anchor point.
  31853. @see setEditableNumber
  31854. */
  31855. const double getEditableNumber() const;
  31856. /** Sets the value that controls this coordinate's position.
  31857. The meaning of this number depends on the coordinate's mode. If the coordinate is
  31858. proportional, the number must be a percentage between 0 and 100. If the
  31859. coordinate is absolute, then it indicates the number of pixels from its anchor point.
  31860. @see setEditableNumber
  31861. */
  31862. void setEditableNumber (const double newValue);
  31863. /** Returns the name of the first anchor point from which this coordinate is relative.
  31864. */
  31865. const String getAnchorName1() const { return anchor1; }
  31866. /** Returns the name of the second anchor point from which this coordinate is relative.
  31867. The second anchor is only valid if the coordinate is in proportional mode.
  31868. */
  31869. const String getAnchorName2() const { return anchor2; }
  31870. /** Returns the first anchor point as a coordinate. */
  31871. const RelativeCoordinate getAnchorCoordinate1() const;
  31872. /** Returns the first anchor point as a coordinate.
  31873. The second anchor is only valid if the coordinate is in proportional mode.
  31874. */
  31875. const RelativeCoordinate getAnchorCoordinate2() const;
  31876. /** Changes the first anchor point, keeping the resultant position of this coordinate in
  31877. the same place it was previously.
  31878. */
  31879. void changeAnchor1 (const String& newAnchor, const NamedCoordinateFinder* nameFinder);
  31880. /** Changes the second anchor point, keeping the resultant position of this coordinate in
  31881. the same place it was previously.
  31882. */
  31883. void changeAnchor2 (const String& newAnchor, const NamedCoordinateFinder* nameFinder);
  31884. /** Tells the coordinate that an object is changing its name or being deleted.
  31885. If either of this coordinates anchor points match this name, they will be replaced.
  31886. If the newName string is empty, it indicates that the object is being removed, so if
  31887. this coordinate was using it, the coordinate is changed to be relative to the origin
  31888. instead.
  31889. */
  31890. void renameAnchorIfUsed (const String& oldName, const String& newName,
  31891. const NamedCoordinateFinder* nameFinder);
  31892. /** Returns a string which represents this coordinate.
  31893. For details of the string syntax, see the constructor notes.
  31894. */
  31895. const String toString() const;
  31896. /** A set of static strings that are commonly used by the RelativeCoordinate class.
  31897. As well as avoiding using string literals in your code, using these preset values
  31898. has the advantage that all instances of the same string will share the same, reference-counted
  31899. String object, so if you have thousands of points which all refer to the same
  31900. anchor points, this can save a significant amount of memory allocation.
  31901. */
  31902. struct Strings
  31903. {
  31904. static const String parent; /**< "parent" */
  31905. static const String left; /**< "left" */
  31906. static const String right; /**< "right" */
  31907. static const String top; /**< "top" */
  31908. static const String bottom; /**< "bottom" */
  31909. static const String parentLeft; /**< "parent.left" */
  31910. static const String parentTop; /**< "parent.top" */
  31911. static const String parentRight; /**< "parent.right" */
  31912. static const String parentBottom; /**< "parent.bottom" */
  31913. };
  31914. private:
  31915. String anchor1, anchor2;
  31916. double value;
  31917. double resolve (const NamedCoordinateFinder* nameFinder, int recursionCounter) const;
  31918. static double resolveAnchor (const String& anchorName, const NamedCoordinateFinder* nameFinder, int recursionCounter);
  31919. };
  31920. /**
  31921. An X-Y position stored as a pair of RelativeCoordinate values.
  31922. @see RelativeCoordinate, RelativeRectangle
  31923. */
  31924. class JUCE_API RelativePoint
  31925. {
  31926. public:
  31927. /** Creates a point at the origin. */
  31928. RelativePoint();
  31929. /** Creates an absolute point, relative to the origin. */
  31930. RelativePoint (const Point<float>& absolutePoint);
  31931. /** Creates an absolute point, relative to the origin. */
  31932. RelativePoint (float absoluteX, float absoluteY);
  31933. /** Creates an absolute point from two coordinates. */
  31934. RelativePoint (const RelativeCoordinate& x, const RelativeCoordinate& y);
  31935. /** Creates a point from a stringified representation.
  31936. The string must contain a pair of coordinates, separated by space or a comma. The syntax for the coordinate
  31937. strings is explained in the RelativeCoordinate class.
  31938. @see toString
  31939. */
  31940. RelativePoint (const String& stringVersion);
  31941. bool operator== (const RelativePoint& other) const throw();
  31942. bool operator!= (const RelativePoint& other) const throw();
  31943. /** Calculates the absolute position of this point.
  31944. You'll need to provide a suitable NamedCoordinateFinder for looking up any coordinates that may
  31945. be needed to calculate the result.
  31946. */
  31947. const Point<float> resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const;
  31948. /** Changes the values of this point's coordinates to make it resolve to the specified position.
  31949. Calling this will leave any anchor points unchanged, but will set any absolute
  31950. or relative positions to whatever values are necessary to make the resultant position
  31951. match the position that is provided.
  31952. */
  31953. void moveToAbsolute (const Point<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  31954. /** Returns a string which represents this point.
  31955. This returns a comma-separated pair of coordinates. For details of the string syntax used by the
  31956. coordinates, see the RelativeCoordinate constructor notes.
  31957. The string that is returned can be passed to the RelativePoint constructor to recreate the point.
  31958. */
  31959. const String toString() const;
  31960. /** Tells the point that an object is changing its name or being deleted.
  31961. This calls RelativeCoordinate::renameAnchorIfUsed() on its X and Y coordinates.
  31962. */
  31963. void renameAnchorIfUsed (const String& oldName, const String& newName,
  31964. const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  31965. /** Returns true if this point depends on any other coordinates for its position. */
  31966. bool isDynamic() const;
  31967. // The actual X and Y coords...
  31968. RelativeCoordinate x, y;
  31969. };
  31970. /**
  31971. An rectangle stored as a set of RelativeCoordinate values.
  31972. The rectangle's top, left, bottom and right edge positions are each stored as a RelativeCoordinate.
  31973. @see RelativeCoordinate, RelativePoint
  31974. */
  31975. class JUCE_API RelativeRectangle
  31976. {
  31977. public:
  31978. /** Creates a zero-size rectangle at the origin. */
  31979. RelativeRectangle();
  31980. /** Creates an absolute rectangle, relative to the origin. */
  31981. explicit RelativeRectangle (const Rectangle<float>& rect, const String& componentName);
  31982. /** Creates a rectangle from four coordinates. */
  31983. RelativeRectangle (const RelativeCoordinate& left, const RelativeCoordinate& right,
  31984. const RelativeCoordinate& top, const RelativeCoordinate& bottom);
  31985. /** Creates a rectangle from a stringified representation.
  31986. The string must contain a sequence of 4 coordinates, separated by commas, in the order
  31987. left, top, right, bottom. The syntax for the coordinate strings is explained in the
  31988. RelativeCoordinate class.
  31989. @see toString
  31990. */
  31991. explicit RelativeRectangle (const String& stringVersion);
  31992. bool operator== (const RelativeRectangle& other) const throw();
  31993. bool operator!= (const RelativeRectangle& other) const throw();
  31994. /** Calculates the absolute position of this rectangle.
  31995. You'll need to provide a suitable NamedCoordinateFinder for looking up any coordinates that may
  31996. be needed to calculate the result.
  31997. */
  31998. const Rectangle<float> resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const;
  31999. /** Changes the values of this rectangle's coordinates to make it resolve to the specified position.
  32000. Calling this will leave any anchor points unchanged, but will set any absolute
  32001. or relative positions to whatever values are necessary to make the resultant position
  32002. match the position that is provided.
  32003. */
  32004. void moveToAbsolute (const Rectangle<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  32005. /** Returns a string which represents this point.
  32006. This returns a comma-separated list of coordinates, in the order left, top, right, bottom. For details of
  32007. the string syntax used by the coordinates, see the RelativeCoordinate constructor notes.
  32008. The string that is returned can be passed to the RelativeRectangle constructor to recreate the rectangle.
  32009. */
  32010. const String toString() const;
  32011. /** Tells the rectangle that an object is changing its name or being deleted.
  32012. This calls RelativeCoordinate::renameAnchorIfUsed() on the rectangle's coordinates.
  32013. */
  32014. void renameAnchorIfUsed (const String& oldName, const String& newName,
  32015. const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  32016. // The actual rectangle coords...
  32017. RelativeCoordinate left, right, top, bottom;
  32018. };
  32019. /**
  32020. A path object that consists of RelativePoint coordinates rather than the normal fixed ones.
  32021. One of these paths can be converted into a Path object for drawing and manipulation, but
  32022. unlike a Path, its points can be dynamic instead of just fixed.
  32023. @see RelativePoint, RelativeCoordinate
  32024. */
  32025. class JUCE_API RelativePointPath
  32026. {
  32027. public:
  32028. RelativePointPath();
  32029. RelativePointPath (const RelativePointPath& other);
  32030. RelativePointPath (const ValueTree& drawable);
  32031. RelativePointPath (const Path& path);
  32032. ~RelativePointPath();
  32033. /** Resolves this points in this path and adds them to a normal Path object. */
  32034. void createPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder);
  32035. /** Returns true if the path contains any non-fixed points. */
  32036. bool containsAnyDynamicPoints() const;
  32037. /** Writes the path to this drawable encoding. */
  32038. void writeTo (ValueTree state, UndoManager* undoManager) const;
  32039. /** Quickly swaps the contents of this path with another. */
  32040. void swapWith (RelativePointPath& other) throw();
  32041. /** The types of element that may be contained in this path.
  32042. @see RelativePointPath::ElementBase
  32043. */
  32044. enum ElementType
  32045. {
  32046. nullElement,
  32047. startSubPathElement,
  32048. closeSubPathElement,
  32049. lineToElement,
  32050. quadraticToElement,
  32051. cubicToElement
  32052. };
  32053. /** Base class for the elements that make up a RelativePointPath.
  32054. */
  32055. class JUCE_API ElementBase
  32056. {
  32057. public:
  32058. ElementBase (ElementType type);
  32059. virtual ~ElementBase() {}
  32060. virtual const ValueTree createTree() const = 0;
  32061. virtual void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const = 0;
  32062. virtual RelativePoint* getControlPoints (int& numPoints) = 0;
  32063. const ElementType type;
  32064. private:
  32065. ElementBase (const ElementBase&);
  32066. ElementBase& operator= (const ElementBase&);
  32067. };
  32068. class JUCE_API StartSubPath : public ElementBase
  32069. {
  32070. public:
  32071. StartSubPath (const RelativePoint& pos);
  32072. ~StartSubPath() {}
  32073. const ValueTree createTree() const;
  32074. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32075. RelativePoint* getControlPoints (int& numPoints);
  32076. RelativePoint startPos;
  32077. private:
  32078. StartSubPath (const StartSubPath&);
  32079. StartSubPath& operator= (const StartSubPath&);
  32080. };
  32081. class JUCE_API CloseSubPath : public ElementBase
  32082. {
  32083. public:
  32084. CloseSubPath();
  32085. ~CloseSubPath() {}
  32086. const ValueTree createTree() const;
  32087. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32088. RelativePoint* getControlPoints (int& numPoints);
  32089. private:
  32090. CloseSubPath (const CloseSubPath&);
  32091. CloseSubPath& operator= (const CloseSubPath&);
  32092. };
  32093. class JUCE_API LineTo : public ElementBase
  32094. {
  32095. public:
  32096. LineTo (const RelativePoint& endPoint);
  32097. ~LineTo() {}
  32098. const ValueTree createTree() const;
  32099. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32100. RelativePoint* getControlPoints (int& numPoints);
  32101. RelativePoint endPoint;
  32102. private:
  32103. LineTo (const LineTo&);
  32104. LineTo& operator= (const LineTo&);
  32105. };
  32106. class JUCE_API QuadraticTo : public ElementBase
  32107. {
  32108. public:
  32109. QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint);
  32110. ~QuadraticTo() {}
  32111. const ValueTree createTree() const;
  32112. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32113. RelativePoint* getControlPoints (int& numPoints);
  32114. RelativePoint controlPoints[2];
  32115. private:
  32116. QuadraticTo (const QuadraticTo&);
  32117. QuadraticTo& operator= (const QuadraticTo&);
  32118. };
  32119. class JUCE_API CubicTo : public ElementBase
  32120. {
  32121. public:
  32122. CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint);
  32123. ~CubicTo() {}
  32124. const ValueTree createTree() const;
  32125. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32126. RelativePoint* getControlPoints (int& numPoints);
  32127. RelativePoint controlPoints[3];
  32128. private:
  32129. CubicTo (const CubicTo&);
  32130. CubicTo& operator= (const CubicTo&);
  32131. };
  32132. OwnedArray <ElementBase> elements;
  32133. bool usesNonZeroWinding;
  32134. private:
  32135. bool containsDynamicPoints;
  32136. void parse (const ValueTree& state);
  32137. RelativePointPath& operator= (const RelativePointPath&);
  32138. };
  32139. /**
  32140. A parallelogram defined by three RelativePoint positions.
  32141. @see RelativePoint, RelativeCoordinate
  32142. */
  32143. class JUCE_API RelativeParallelogram
  32144. {
  32145. public:
  32146. RelativeParallelogram();
  32147. RelativeParallelogram (const RelativePoint& topLeft, const RelativePoint& topRight, const RelativePoint& bottomLeft);
  32148. RelativeParallelogram (const String& topLeft, const String& topRight, const String& bottomLeft);
  32149. ~RelativeParallelogram();
  32150. void resolveThreePoints (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32151. void resolveFourCorners (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32152. const Rectangle<float> getBounds (RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32153. void getPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32154. const AffineTransform resetToPerpendicular (RelativeCoordinate::NamedCoordinateFinder* coordFinder);
  32155. bool operator== (const RelativeParallelogram& other) const throw();
  32156. bool operator!= (const RelativeParallelogram& other) const throw();
  32157. static const Point<float> getInternalCoordForPoint (const Point<float>* parallelogramCorners, Point<float> point) throw();
  32158. static const Point<float> getPointForInternalCoord (const Point<float>* parallelogramCorners, const Point<float>& internalPoint) throw();
  32159. RelativePoint topLeft, topRight, bottomLeft;
  32160. };
  32161. #endif // __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  32162. /*** End of inlined file: juce_RelativeCoordinate.h ***/
  32163. class DrawableComposite;
  32164. /**
  32165. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  32166. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  32167. */
  32168. class JUCE_API Drawable
  32169. {
  32170. protected:
  32171. /** The base class can't be instantiated directly.
  32172. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  32173. */
  32174. Drawable();
  32175. public:
  32176. /** Destructor. */
  32177. virtual ~Drawable();
  32178. /** Creates a deep copy of this Drawable object.
  32179. Use this to create a new copy of this and any sub-objects in the tree.
  32180. */
  32181. virtual Drawable* createCopy() const = 0;
  32182. /** Renders this Drawable object.
  32183. @see drawWithin
  32184. */
  32185. void draw (Graphics& g, float opacity,
  32186. const AffineTransform& transform = AffineTransform::identity) const;
  32187. /** Renders the Drawable at a given offset within the Graphics context.
  32188. The co-ordinates passed-in are used to translate the object relative to its own
  32189. origin before drawing it - this is basically a quick way of saying:
  32190. @code
  32191. draw (g, AffineTransform::translation (x, y)).
  32192. @endcode
  32193. */
  32194. void drawAt (Graphics& g,
  32195. float x, float y,
  32196. float opacity) const;
  32197. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  32198. changing its aspect-ratio.
  32199. The object can placed arbitrarily within the rectangle based on a Justification type,
  32200. and can either be made as big as possible, or just reduced to fit.
  32201. @param g the graphics context to render onto
  32202. @param destX top-left of the target rectangle to fit it into
  32203. @param destY top-left of the target rectangle to fit it into
  32204. @param destWidth size of the target rectangle to fit the image into
  32205. @param destHeight size of the target rectangle to fit the image into
  32206. @param placement defines the alignment and rescaling to use to fit
  32207. this object within the target rectangle.
  32208. @param opacity the opacity to use, in the range 0 to 1.0
  32209. */
  32210. void drawWithin (Graphics& g,
  32211. int destX,
  32212. int destY,
  32213. int destWidth,
  32214. int destHeight,
  32215. const RectanglePlacement& placement,
  32216. float opacity) const;
  32217. /** Holds the information needed when telling a drawable to render itself.
  32218. @see Drawable::draw
  32219. */
  32220. class RenderingContext
  32221. {
  32222. public:
  32223. RenderingContext (Graphics& g, const AffineTransform& transform, float opacity) throw();
  32224. Graphics& g;
  32225. AffineTransform transform;
  32226. float opacity;
  32227. private:
  32228. RenderingContext& operator= (const RenderingContext&);
  32229. };
  32230. /** Renders this Drawable object.
  32231. @see draw
  32232. */
  32233. virtual void render (const RenderingContext& context) const = 0;
  32234. /** Returns the smallest rectangle that can contain this Drawable object.
  32235. Co-ordinates are relative to the object's own origin.
  32236. */
  32237. virtual const Rectangle<float> getBounds() const = 0;
  32238. /** Returns true if the given point is somewhere inside this Drawable.
  32239. Co-ordinates are relative to the object's own origin.
  32240. */
  32241. virtual bool hitTest (float x, float y) const = 0;
  32242. /** Returns the name given to this drawable.
  32243. @see setName
  32244. */
  32245. const String& getName() const throw() { return name; }
  32246. /** Assigns a name to this drawable. */
  32247. void setName (const String& newName) throw() { name = newName; }
  32248. /** Returns the DrawableComposite that contains this object, if there is one. */
  32249. DrawableComposite* getParent() const throw() { return parent; }
  32250. /** Tries to turn some kind of image file into a drawable.
  32251. The data could be an image that the ImageFileFormat class understands, or it
  32252. could be SVG.
  32253. */
  32254. static Drawable* createFromImageData (const void* data, size_t numBytes);
  32255. /** Tries to turn a stream containing some kind of image data into a drawable.
  32256. The data could be an image that the ImageFileFormat class understands, or it
  32257. could be SVG.
  32258. */
  32259. static Drawable* createFromImageDataStream (InputStream& dataSource);
  32260. /** Tries to turn a file containing some kind of image data into a drawable.
  32261. The data could be an image that the ImageFileFormat class understands, or it
  32262. could be SVG.
  32263. */
  32264. static Drawable* createFromImageFile (const File& file);
  32265. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  32266. into a Drawable tree.
  32267. The object returned must be deleted by the caller. If something goes wrong
  32268. while parsing, it may return 0.
  32269. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  32270. implementation, but it can return the basic vector objects.
  32271. */
  32272. static Drawable* createFromSVG (const XmlElement& svgDocument);
  32273. /** This class is used when loading Drawables that contain images, and retrieves
  32274. the image for a stored identifier.
  32275. @see Drawable::createFromValueTree
  32276. */
  32277. class JUCE_API ImageProvider
  32278. {
  32279. public:
  32280. ImageProvider() {}
  32281. virtual ~ImageProvider() {}
  32282. /** Retrieves the image associated with this identifier, which could be any
  32283. kind of string, number, filename, etc.
  32284. The image that is returned will be owned by the caller, but it may come
  32285. from the ImageCache.
  32286. */
  32287. virtual const Image getImageForIdentifier (const var& imageIdentifier) = 0;
  32288. /** Returns an identifier to be used to refer to a given image.
  32289. This is used when converting a drawable into a ValueTree, so if you're
  32290. only loading drawables, you can just return a var::null here.
  32291. */
  32292. virtual const var getIdentifierForImage (const Image& image) = 0;
  32293. };
  32294. /** Tries to create a Drawable from a previously-saved ValueTree.
  32295. The ValueTree must have been created by the createValueTree() method.
  32296. If there are any images used within the drawable, you'll need to provide a valid
  32297. ImageProvider object that can be used to retrieve these images from whatever type
  32298. of identifier is used to represent them.
  32299. */
  32300. static Drawable* createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  32301. /** Tries to refresh a Drawable from the same ValueTree that was used to create it.
  32302. @returns the damage rectangle that will need repainting due to any changes that were made.
  32303. */
  32304. virtual const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider) = 0;
  32305. /** Creates a ValueTree to represent this Drawable.
  32306. The VarTree that is returned can be turned back into a Drawable with
  32307. createFromValueTree().
  32308. If there are any images used in this drawable, you'll need to provide a valid
  32309. ImageProvider object that can be used to create storable representations of them.
  32310. */
  32311. virtual const ValueTree createValueTree (ImageProvider* imageProvider) const = 0;
  32312. /** Returns the tag ID that is used for a ValueTree that stores this type of drawable. */
  32313. virtual const Identifier getValueTreeType() const = 0;
  32314. /** Internal class used to manage ValueTrees that represent Drawables. */
  32315. class ValueTreeWrapperBase
  32316. {
  32317. public:
  32318. ValueTreeWrapperBase (const ValueTree& state);
  32319. ~ValueTreeWrapperBase();
  32320. ValueTree& getState() throw() { return state; }
  32321. const String getID() const;
  32322. void setID (const String& newID, UndoManager* undoManager);
  32323. static const Identifier idProperty;
  32324. static const FillType readFillType (const ValueTree& v, RelativePoint* gradientPoint1, RelativePoint* gradientPoint2,
  32325. RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  32326. ImageProvider* imageProvider);
  32327. static void writeFillType (ValueTree& v, const FillType& fillType,
  32328. const RelativePoint* gradientPoint1, const RelativePoint* gradientPoint2,
  32329. ImageProvider* imageProvider,
  32330. UndoManager* undoManager);
  32331. ValueTree state;
  32332. static const Identifier type, gradientPoint1, gradientPoint2, colour, radial, colours, imageId, imageOpacity;
  32333. };
  32334. juce_UseDebuggingNewOperator
  32335. protected:
  32336. friend class DrawableComposite;
  32337. DrawableComposite* parent;
  32338. virtual void invalidatePoints() = 0;
  32339. static Drawable* createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider);
  32340. private:
  32341. String name;
  32342. Drawable (const Drawable&);
  32343. Drawable& operator= (const Drawable&);
  32344. };
  32345. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  32346. /*** End of inlined file: juce_Drawable.h ***/
  32347. /**
  32348. A button that displays a Drawable.
  32349. Up to three Drawable objects can be given to this button, to represent the
  32350. 'normal', 'over' and 'down' states.
  32351. @see Button
  32352. */
  32353. class JUCE_API DrawableButton : public Button
  32354. {
  32355. public:
  32356. enum ButtonStyle
  32357. {
  32358. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  32359. ImageRaw, /**< The button will just display the images in their normal size and position.
  32360. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  32361. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  32362. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  32363. };
  32364. /** Creates a DrawableButton.
  32365. After creating one of these, use setImages() to specify the drawables to use.
  32366. @param buttonName the name to give the component
  32367. @param buttonStyle the layout to use
  32368. @see ButtonStyle, setButtonStyle, setImages
  32369. */
  32370. DrawableButton (const String& buttonName,
  32371. ButtonStyle buttonStyle);
  32372. /** Destructor. */
  32373. ~DrawableButton();
  32374. /** Sets up the images to draw for the various button states.
  32375. The button will keep its own internal copies of these drawables.
  32376. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  32377. will be made of the object passed-in if it is non-zero.
  32378. @param overImage the thing to draw for the button's 'over' state - if this is
  32379. zero, the button's normal image will be used when the mouse is
  32380. over it. An internal copy will be made of the object passed-in
  32381. if it is non-zero.
  32382. @param downImage the thing to draw for the button's 'down' state - if this is
  32383. zero, the 'over' image will be used instead (or the normal image
  32384. as a last resort). An internal copy will be made of the object
  32385. passed-in if it is non-zero.
  32386. @param disabledImage an image to draw when the button is disabled. If this is zero,
  32387. the normal image will be drawn with a reduced opacity instead.
  32388. An internal copy will be made of the object passed-in if it is
  32389. non-zero.
  32390. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  32391. state is 'on'. If this is 0, the normal image is used instead
  32392. @param overImageOn same as the overImage, but this is used when the button's toggle
  32393. state is 'on'. If this is 0, the normalImageOn is drawn instead
  32394. @param downImageOn same as the downImage, but this is used when the button's toggle
  32395. state is 'on'. If this is 0, the overImageOn is drawn instead
  32396. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  32397. state is 'on'. If this is 0, the normal image will be drawn instead
  32398. with a reduced opacity
  32399. */
  32400. void setImages (const Drawable* normalImage,
  32401. const Drawable* overImage = 0,
  32402. const Drawable* downImage = 0,
  32403. const Drawable* disabledImage = 0,
  32404. const Drawable* normalImageOn = 0,
  32405. const Drawable* overImageOn = 0,
  32406. const Drawable* downImageOn = 0,
  32407. const Drawable* disabledImageOn = 0);
  32408. /** Changes the button's style.
  32409. @see ButtonStyle
  32410. */
  32411. void setButtonStyle (ButtonStyle newStyle);
  32412. /** Changes the button's background colours.
  32413. The toggledOffColour is the colour to use when the button's toggle state
  32414. is off, and toggledOnColour when it's on.
  32415. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  32416. used to fill the background of the component.
  32417. For an ImageOnButtonBackground style, the colour is used to draw the
  32418. button's lozenge shape and exactly how the colour's used will depend
  32419. on the LookAndFeel.
  32420. */
  32421. void setBackgroundColours (const Colour& toggledOffColour,
  32422. const Colour& toggledOnColour);
  32423. /** Returns the current background colour being used.
  32424. @see setBackgroundColour
  32425. */
  32426. const Colour& getBackgroundColour() const throw();
  32427. /** Gives the button an optional amount of space around the edge of the drawable.
  32428. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  32429. ones on a button background. If the button is too small for the given gap, a
  32430. smaller gap will be used.
  32431. By default there's a gap of about 3 pixels.
  32432. */
  32433. void setEdgeIndent (int numPixelsIndent);
  32434. /** Returns the image that the button is currently displaying. */
  32435. const Drawable* getCurrentImage() const throw();
  32436. const Drawable* getNormalImage() const throw();
  32437. const Drawable* getOverImage() const throw();
  32438. const Drawable* getDownImage() const throw();
  32439. juce_UseDebuggingNewOperator
  32440. protected:
  32441. /** @internal */
  32442. void paintButton (Graphics& g,
  32443. bool isMouseOverButton,
  32444. bool isButtonDown);
  32445. private:
  32446. ButtonStyle style;
  32447. ScopedPointer <Drawable> normalImage, overImage, downImage, disabledImage;
  32448. ScopedPointer <Drawable> normalImageOn, overImageOn, downImageOn, disabledImageOn;
  32449. Colour backgroundOff, backgroundOn;
  32450. int edgeIndent;
  32451. void deleteImages();
  32452. DrawableButton (const DrawableButton&);
  32453. DrawableButton& operator= (const DrawableButton&);
  32454. };
  32455. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  32456. /*** End of inlined file: juce_DrawableButton.h ***/
  32457. #endif
  32458. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32459. /*** Start of inlined file: juce_HyperlinkButton.h ***/
  32460. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32461. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32462. /**
  32463. A button showing an underlined weblink, that will launch the link
  32464. when it's clicked.
  32465. @see Button
  32466. */
  32467. class JUCE_API HyperlinkButton : public Button
  32468. {
  32469. public:
  32470. /** Creates a HyperlinkButton.
  32471. @param linkText the text that will be displayed in the button - this is
  32472. also set as the Component's name, but the text can be
  32473. changed later with the Button::getButtonText() method
  32474. @param linkURL the URL to launch when the user clicks the button
  32475. */
  32476. HyperlinkButton (const String& linkText,
  32477. const URL& linkURL);
  32478. /** Destructor. */
  32479. ~HyperlinkButton();
  32480. /** Changes the font to use for the text.
  32481. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  32482. to match the size of the component.
  32483. */
  32484. void setFont (const Font& newFont,
  32485. bool resizeToMatchComponentHeight,
  32486. const Justification& justificationType = Justification::horizontallyCentred);
  32487. /** A set of colour IDs to use to change the colour of various aspects of the link.
  32488. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32489. methods.
  32490. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32491. */
  32492. enum ColourIds
  32493. {
  32494. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  32495. };
  32496. /** Changes the URL that the button will trigger. */
  32497. void setURL (const URL& newURL) throw();
  32498. /** Returns the URL that the button will trigger. */
  32499. const URL& getURL() const throw() { return url; }
  32500. /** Resizes the button horizontally to fit snugly around the text.
  32501. This won't affect the button's height.
  32502. */
  32503. void changeWidthToFitText();
  32504. juce_UseDebuggingNewOperator
  32505. protected:
  32506. /** @internal */
  32507. void clicked();
  32508. /** @internal */
  32509. void colourChanged();
  32510. /** @internal */
  32511. void paintButton (Graphics& g,
  32512. bool isMouseOverButton,
  32513. bool isButtonDown);
  32514. private:
  32515. URL url;
  32516. Font font;
  32517. bool resizeFont;
  32518. Justification justification;
  32519. const Font getFontToUse() const;
  32520. HyperlinkButton (const HyperlinkButton&);
  32521. HyperlinkButton& operator= (const HyperlinkButton&);
  32522. };
  32523. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32524. /*** End of inlined file: juce_HyperlinkButton.h ***/
  32525. #endif
  32526. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  32527. /*** Start of inlined file: juce_ImageButton.h ***/
  32528. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  32529. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  32530. /**
  32531. As the title suggests, this is a button containing an image.
  32532. The colour and transparency of the image can be set to vary when the
  32533. button state changes.
  32534. @see Button, ShapeButton, TextButton
  32535. */
  32536. class JUCE_API ImageButton : public Button
  32537. {
  32538. public:
  32539. /** Creates an ImageButton.
  32540. Use setImage() to specify the image to use. The colours and opacities that
  32541. are specified here can be changed later using setDrawingOptions().
  32542. @param name the name to give the component
  32543. */
  32544. explicit ImageButton (const String& name);
  32545. /** Destructor. */
  32546. ~ImageButton();
  32547. /** Sets up the images to draw in various states.
  32548. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  32549. resized to the same dimensions as the normal image
  32550. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  32551. button when the button's size changes
  32552. @param preserveImageProportions if true then any rescaling of the image to fit
  32553. the button will keep the image's x and y proportions
  32554. correct - i.e. it won't distort its shape, although
  32555. this might create gaps around the edges
  32556. @param normalImage the image to use when the button is in its normal state.
  32557. button no longer needs it.
  32558. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  32559. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  32560. normal image - if this colour is transparent, no overlay
  32561. will be drawn. The overlay will be drawn over the top of the
  32562. image, so you can basically add a solid or semi-transparent
  32563. colour to the image to brighten or darken it
  32564. @param overImage the image to use when the mouse is over the button. If
  32565. you want to use the same image as was set in the normalImage
  32566. parameter, this value can be a null image.
  32567. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  32568. is over the button
  32569. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  32570. image when the mouse is over - if this colour is transparent,
  32571. no overlay will be drawn
  32572. @param downImage an image to use when the button is pressed down. If set
  32573. to a null image, the 'over' image will be drawn instead (or the
  32574. normal image if there isn't an 'over' image either).
  32575. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  32576. is pressed
  32577. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  32578. image when the button is pressed down - if this colour is
  32579. transparent, no overlay will be drawn
  32580. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  32581. whenever it's inside the button's bounding rectangle. If
  32582. set to values higher than 0, the mouse will only be
  32583. considered to be over the image when the value of the
  32584. image's alpha channel at that position is greater than
  32585. this level.
  32586. */
  32587. void setImages (bool resizeButtonNowToFitThisImage,
  32588. bool rescaleImagesWhenButtonSizeChanges,
  32589. bool preserveImageProportions,
  32590. const Image& normalImage,
  32591. float imageOpacityWhenNormal,
  32592. const Colour& overlayColourWhenNormal,
  32593. const Image& overImage,
  32594. float imageOpacityWhenOver,
  32595. const Colour& overlayColourWhenOver,
  32596. const Image& downImage,
  32597. float imageOpacityWhenDown,
  32598. const Colour& overlayColourWhenDown,
  32599. float hitTestAlphaThreshold = 0.0f);
  32600. /** Returns the currently set 'normal' image. */
  32601. const Image getNormalImage() const;
  32602. /** Returns the image that's drawn when the mouse is over the button.
  32603. If a valid 'over' image has been set, this will return it; otherwise it'll
  32604. just return the normal image.
  32605. */
  32606. const Image getOverImage() const;
  32607. /** Returns the image that's drawn when the button is held down.
  32608. If a valid 'down' image has been set, this will return it; otherwise it'll
  32609. return the 'over' image or normal image, depending on what's available.
  32610. */
  32611. const Image getDownImage() const;
  32612. juce_UseDebuggingNewOperator
  32613. protected:
  32614. /** @internal */
  32615. bool hitTest (int x, int y);
  32616. /** @internal */
  32617. void paintButton (Graphics& g,
  32618. bool isMouseOverButton,
  32619. bool isButtonDown);
  32620. private:
  32621. bool scaleImageToFit, preserveProportions;
  32622. unsigned char alphaThreshold;
  32623. int imageX, imageY, imageW, imageH;
  32624. Image normalImage, overImage, downImage;
  32625. float normalOpacity, overOpacity, downOpacity;
  32626. Colour normalOverlay, overOverlay, downOverlay;
  32627. const Image getCurrentImage() const;
  32628. ImageButton (const ImageButton&);
  32629. ImageButton& operator= (const ImageButton&);
  32630. };
  32631. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  32632. /*** End of inlined file: juce_ImageButton.h ***/
  32633. #endif
  32634. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  32635. /*** Start of inlined file: juce_ShapeButton.h ***/
  32636. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  32637. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  32638. /**
  32639. A button that contains a filled shape.
  32640. @see Button, ImageButton, TextButton, ArrowButton
  32641. */
  32642. class JUCE_API ShapeButton : public Button
  32643. {
  32644. public:
  32645. /** Creates a ShapeButton.
  32646. @param name a name to give the component - see Component::setName()
  32647. @param normalColour the colour to fill the shape with when the mouse isn't over
  32648. @param overColour the colour to use when the mouse is over the shape
  32649. @param downColour the colour to use when the button is in the pressed-down state
  32650. */
  32651. ShapeButton (const String& name,
  32652. const Colour& normalColour,
  32653. const Colour& overColour,
  32654. const Colour& downColour);
  32655. /** Destructor. */
  32656. ~ShapeButton();
  32657. /** Sets the shape to use.
  32658. @param newShape the shape to use
  32659. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  32660. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  32661. the button is resized
  32662. @param hasDropShadow if true, the button will be given a drop-shadow effect
  32663. */
  32664. void setShape (const Path& newShape,
  32665. bool resizeNowToFitThisShape,
  32666. bool maintainShapeProportions,
  32667. bool hasDropShadow);
  32668. /** Set the colours to use for drawing the shape.
  32669. @param normalColour the colour to fill the shape with when the mouse isn't over
  32670. @param overColour the colour to use when the mouse is over the shape
  32671. @param downColour the colour to use when the button is in the pressed-down state
  32672. */
  32673. void setColours (const Colour& normalColour,
  32674. const Colour& overColour,
  32675. const Colour& downColour);
  32676. /** Sets up an outline to draw around the shape.
  32677. @param outlineColour the colour to use
  32678. @param outlineStrokeWidth the thickness of line to draw
  32679. */
  32680. void setOutline (const Colour& outlineColour,
  32681. float outlineStrokeWidth);
  32682. juce_UseDebuggingNewOperator
  32683. protected:
  32684. /** @internal */
  32685. void paintButton (Graphics& g,
  32686. bool isMouseOverButton,
  32687. bool isButtonDown);
  32688. private:
  32689. Colour normalColour, overColour, downColour, outlineColour;
  32690. DropShadowEffect shadow;
  32691. Path shape;
  32692. bool maintainShapeProportions;
  32693. float outlineWidth;
  32694. ShapeButton (const ShapeButton&);
  32695. ShapeButton& operator= (const ShapeButton&);
  32696. };
  32697. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  32698. /*** End of inlined file: juce_ShapeButton.h ***/
  32699. #endif
  32700. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  32701. #endif
  32702. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  32703. /*** Start of inlined file: juce_ToggleButton.h ***/
  32704. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  32705. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  32706. /**
  32707. A button that can be toggled on/off.
  32708. All buttons can be toggle buttons, but this lets you create one of the
  32709. standard ones which has a tick-box and a text label next to it.
  32710. @see Button, DrawableButton, TextButton
  32711. */
  32712. class JUCE_API ToggleButton : public Button
  32713. {
  32714. public:
  32715. /** Creates a ToggleButton.
  32716. @param buttonText the text to put in the button (the component's name is also
  32717. initially set to this string, but these can be changed later
  32718. using the setName() and setButtonText() methods)
  32719. */
  32720. explicit ToggleButton (const String& buttonText = String::empty);
  32721. /** Destructor. */
  32722. ~ToggleButton();
  32723. /** Resizes the button to fit neatly around its current text.
  32724. The button's height won't be affected, only its width.
  32725. */
  32726. void changeWidthToFitText();
  32727. /** A set of colour IDs to use to change the colour of various aspects of the button.
  32728. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32729. methods.
  32730. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32731. */
  32732. enum ColourIds
  32733. {
  32734. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  32735. };
  32736. juce_UseDebuggingNewOperator
  32737. protected:
  32738. /** @internal */
  32739. void paintButton (Graphics& g,
  32740. bool isMouseOverButton,
  32741. bool isButtonDown);
  32742. /** @internal */
  32743. void colourChanged();
  32744. private:
  32745. ToggleButton (const ToggleButton&);
  32746. ToggleButton& operator= (const ToggleButton&);
  32747. };
  32748. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  32749. /*** End of inlined file: juce_ToggleButton.h ***/
  32750. #endif
  32751. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  32752. /*** Start of inlined file: juce_ToolbarButton.h ***/
  32753. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  32754. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  32755. /*** Start of inlined file: juce_ToolbarItemComponent.h ***/
  32756. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  32757. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  32758. /*** Start of inlined file: juce_Toolbar.h ***/
  32759. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  32760. #define __JUCE_TOOLBAR_JUCEHEADER__
  32761. /*** Start of inlined file: juce_DragAndDropContainer.h ***/
  32762. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  32763. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  32764. /*** Start of inlined file: juce_DragAndDropTarget.h ***/
  32765. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  32766. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  32767. /**
  32768. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  32769. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  32770. derive your component from this class, and make sure that it is somewhere inside a
  32771. DragAndDropContainer component.
  32772. Note: If all that you need to do is to respond to files being drag-and-dropped from
  32773. the operating system onto your component, you don't need any of these classes: instead
  32774. see the FileDragAndDropTarget class.
  32775. @see DragAndDropContainer, FileDragAndDropTarget
  32776. */
  32777. class JUCE_API DragAndDropTarget
  32778. {
  32779. public:
  32780. /** Destructor. */
  32781. virtual ~DragAndDropTarget() {}
  32782. /** Callback to check whether this target is interested in the type of object being
  32783. dragged.
  32784. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32785. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32786. @returns true if this component wants to receive the other callbacks regarging this
  32787. type of object; if it returns false, no other callbacks will be made.
  32788. */
  32789. virtual bool isInterestedInDragSource (const String& sourceDescription,
  32790. Component* sourceComponent) = 0;
  32791. /** Callback to indicate that something is being dragged over this component.
  32792. This gets called when the user moves the mouse into this component while dragging
  32793. something.
  32794. Use this callback as a trigger to make your component repaint itself to give the
  32795. user feedback about whether the item can be dropped here or not.
  32796. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32797. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32798. @param x the mouse x position, relative to this component
  32799. @param y the mouse y position, relative to this component
  32800. @see itemDragExit
  32801. */
  32802. virtual void itemDragEnter (const String& sourceDescription,
  32803. Component* sourceComponent,
  32804. int x, int y);
  32805. /** Callback to indicate that the user is dragging something over this component.
  32806. This gets called when the user moves the mouse over this component while dragging
  32807. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  32808. this lets you know what happens in-between.
  32809. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32810. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32811. @param x the mouse x position, relative to this component
  32812. @param y the mouse y position, relative to this component
  32813. */
  32814. virtual void itemDragMove (const String& sourceDescription,
  32815. Component* sourceComponent,
  32816. int x, int y);
  32817. /** Callback to indicate that something has been dragged off the edge of this component.
  32818. This gets called when the user moves the mouse out of this component while dragging
  32819. something.
  32820. If you've used itemDragEnter() to repaint your component and give feedback, use this
  32821. as a signal to repaint it in its normal state.
  32822. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32823. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32824. @see itemDragEnter
  32825. */
  32826. virtual void itemDragExit (const String& sourceDescription,
  32827. Component* sourceComponent);
  32828. /** Callback to indicate that the user has dropped something onto this component.
  32829. When the user drops an item this get called, and you can use the description to
  32830. work out whether your object wants to deal with it or not.
  32831. Note that after this is called, the itemDragExit method may not be called, so you should
  32832. clean up in here if there's anything you need to do when the drag finishes.
  32833. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32834. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32835. @param x the mouse x position, relative to this component
  32836. @param y the mouse y position, relative to this component
  32837. */
  32838. virtual void itemDropped (const String& sourceDescription,
  32839. Component* sourceComponent,
  32840. int x, int y) = 0;
  32841. /** Overriding this allows the target to tell the drag container whether to
  32842. draw the drag image while the cursor is over it.
  32843. By default it returns true, but if you return false, then the normal drag
  32844. image will not be shown when the cursor is over this target.
  32845. */
  32846. virtual bool shouldDrawDragImageWhenOver();
  32847. };
  32848. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  32849. /*** End of inlined file: juce_DragAndDropTarget.h ***/
  32850. /**
  32851. Enables drag-and-drop behaviour for a component and all its sub-components.
  32852. For a component to be able to make or receive drag-and-drop events, one of its parent
  32853. components must derive from this class. It's probably best for the top-level
  32854. component to implement it.
  32855. Then to start a drag operation, any sub-component can just call the startDragging()
  32856. method, and this object will take over, tracking the mouse and sending appropriate
  32857. callbacks to any child components derived from DragAndDropTarget which the mouse
  32858. moves over.
  32859. Note: If all that you need to do is to respond to files being drag-and-dropped from
  32860. the operating system onto your component, you don't need any of these classes: you can do this
  32861. simply by overriding Component::filesDropped().
  32862. @see DragAndDropTarget
  32863. */
  32864. class JUCE_API DragAndDropContainer
  32865. {
  32866. public:
  32867. /** Creates a DragAndDropContainer.
  32868. The object that derives from this class must also be a Component.
  32869. */
  32870. DragAndDropContainer();
  32871. /** Destructor. */
  32872. virtual ~DragAndDropContainer();
  32873. /** Begins a drag-and-drop operation.
  32874. This starts a drag-and-drop operation - call it when the user drags the
  32875. mouse in your drag-source component, and this object will track mouse
  32876. movements until the user lets go of the mouse button, and will send
  32877. appropriate messages to DragAndDropTarget objects that the mouse moves
  32878. over.
  32879. findParentDragContainerFor() is a handy method to call to find the
  32880. drag container to use for a component.
  32881. @param sourceDescription a string to use as the description of the thing being
  32882. dragged - this will be passed to the objects that might be
  32883. dropped-onto so they can decide if they want to handle it or
  32884. not
  32885. @param sourceComponent the component that is being dragged
  32886. @param dragImage the image to drag around underneath the mouse. If this is a null image,
  32887. a snapshot of the sourceComponent will be used instead.
  32888. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  32889. window, and can be dragged to DragAndDropTargets that are the
  32890. children of components other than this one.
  32891. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  32892. at which the image should be drawn from the mouse. If it isn't
  32893. specified, then the image will be centred around the mouse. If
  32894. an image hasn't been passed-in, this will be ignored.
  32895. */
  32896. void startDragging (const String& sourceDescription,
  32897. Component* sourceComponent,
  32898. const Image& dragImage = Image(),
  32899. bool allowDraggingToOtherJuceWindows = false,
  32900. const Point<int>* imageOffsetFromMouse = 0);
  32901. /** Returns true if something is currently being dragged. */
  32902. bool isDragAndDropActive() const;
  32903. /** Returns the description of the thing that's currently being dragged.
  32904. If nothing's being dragged, this will return an empty string, otherwise it's the
  32905. string that was passed into startDragging().
  32906. @see startDragging
  32907. */
  32908. const String getCurrentDragDescription() const;
  32909. /** Utility to find the DragAndDropContainer for a given Component.
  32910. This will search up this component's parent hierarchy looking for the first
  32911. parent component which is a DragAndDropContainer.
  32912. It's useful when a component wants to call startDragging but doesn't know
  32913. the DragAndDropContainer it should to use.
  32914. Obviously this may return 0 if it doesn't find a suitable component.
  32915. */
  32916. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  32917. /** This performs a synchronous drag-and-drop of a set of files to some external
  32918. application.
  32919. You can call this function in response to a mouseDrag callback, and it will
  32920. block, running its own internal message loop and tracking the mouse, while it
  32921. uses a native operating system drag-and-drop operation to move or copy some
  32922. files to another application.
  32923. @param files a list of filenames to drag
  32924. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  32925. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  32926. @returns true if the files were successfully dropped somewhere, or false if it
  32927. was interrupted
  32928. @see performExternalDragDropOfText
  32929. */
  32930. static bool performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles);
  32931. /** This performs a synchronous drag-and-drop of a block of text to some external
  32932. application.
  32933. You can call this function in response to a mouseDrag callback, and it will
  32934. block, running its own internal message loop and tracking the mouse, while it
  32935. uses a native operating system drag-and-drop operation to move or copy some
  32936. text to another application.
  32937. @param text the text to copy
  32938. @returns true if the text was successfully dropped somewhere, or false if it
  32939. was interrupted
  32940. @see performExternalDragDropOfFiles
  32941. */
  32942. static bool performExternalDragDropOfText (const String& text);
  32943. juce_UseDebuggingNewOperator
  32944. protected:
  32945. /** Override this if you want to be able to perform an external drag a set of files
  32946. when the user drags outside of this container component.
  32947. This method will be called when a drag operation moves outside the Juce-based window,
  32948. and if you want it to then perform a file drag-and-drop, add the filenames you want
  32949. to the array passed in, and return true.
  32950. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  32951. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  32952. @param files on return, the filenames you want to drag
  32953. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  32954. it must make a copy of them (see the performExternalDragDropOfFiles()
  32955. method)
  32956. @see performExternalDragDropOfFiles
  32957. */
  32958. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  32959. Component* dragSourceComponent,
  32960. StringArray& files,
  32961. bool& canMoveFiles);
  32962. private:
  32963. friend class DragImageComponent;
  32964. ScopedPointer <Component> dragImageComponent;
  32965. String currentDragDesc;
  32966. };
  32967. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  32968. /*** End of inlined file: juce_DragAndDropContainer.h ***/
  32969. /*** Start of inlined file: juce_ComponentAnimator.h ***/
  32970. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  32971. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  32972. /**
  32973. Animates a set of components, moving it to a new position.
  32974. To use this, create a ComponentAnimator, and use its animateComponent() method
  32975. to tell it to move components to destination positions. Any number of
  32976. components can be animated by one ComponentAnimator object (if you've got a
  32977. lot of components to move, it's much more efficient to share a single animator
  32978. than to have many animators running at once).
  32979. You'll need to make sure the animator object isn't deleted before it finishes
  32980. moving the components.
  32981. The class is a ChangeBroadcaster and sends a notification when any components
  32982. start or finish being animated.
  32983. */
  32984. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  32985. private Timer
  32986. {
  32987. public:
  32988. /** Creates a ComponentAnimator. */
  32989. ComponentAnimator();
  32990. /** Destructor. */
  32991. ~ComponentAnimator();
  32992. /** Starts a component moving from its current position to a specified position.
  32993. If the component is already in the middle of an animation, that will be abandoned,
  32994. and a new animation will begin, moving the component from its current location.
  32995. The start and end speed parameters let you apply some acceleration to the component's
  32996. movement.
  32997. @param component the component to move
  32998. @param finalPosition the destination position and size to move it to
  32999. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  33000. to arrive at its destination
  33001. @param startSpeed a value to indicate the relative start speed of the
  33002. animation. If this is 0, the component will start
  33003. by accelerating from rest; higher values mean that it
  33004. will have an initial speed greater than zero. If the
  33005. value if greater than 1, it will decelerate towards the
  33006. middle of its journey. To move the component at a constant
  33007. rate for its entire animation, set both the start and
  33008. end speeds to 1.0
  33009. @param endSpeed a relative speed at which the component should be moving
  33010. when the animation finishes. If this is 0, the component
  33011. will decelerate to a standstill at its final position; higher
  33012. values mean the component will still be moving when it stops.
  33013. To move the component at a constant rate for its entire
  33014. animation, set both the start and end speeds to 1.0
  33015. */
  33016. void animateComponent (Component* component,
  33017. const Rectangle<int>& finalPosition,
  33018. int millisecondsToSpendMoving,
  33019. double startSpeed = 1.0,
  33020. double endSpeed = 1.0);
  33021. /** Stops a component if it's currently being animated.
  33022. If moveComponentToItsFinalPosition is true, then the component will
  33023. be immediately moved to its destination position and size. If false, it will be
  33024. left in whatever location it currently occupies.
  33025. */
  33026. void cancelAnimation (Component* component,
  33027. bool moveComponentToItsFinalPosition);
  33028. /** Clears all of the active animations.
  33029. If moveComponentsToTheirFinalPositions is true, all the components will
  33030. be immediately set to their final positions. If false, they will be
  33031. left in whatever locations they currently occupy.
  33032. */
  33033. void cancelAllAnimations (bool moveComponentsToTheirFinalPositions);
  33034. /** Returns the destination position for a component.
  33035. If the component is being animated, this will return the target position that
  33036. was specified when animateComponent() was called.
  33037. If the specified component isn't currently being animated, this method will just
  33038. return its current position.
  33039. */
  33040. const Rectangle<int> getComponentDestination (Component* component);
  33041. /** Returns true if the specified component is currently being animated.
  33042. */
  33043. bool isAnimating (Component* component) const;
  33044. juce_UseDebuggingNewOperator
  33045. private:
  33046. class AnimationTask;
  33047. Array <AnimationTask*> tasks;
  33048. uint32 lastTime;
  33049. AnimationTask* findTaskFor (Component* component) const;
  33050. void timerCallback();
  33051. };
  33052. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  33053. /*** End of inlined file: juce_ComponentAnimator.h ***/
  33054. class ToolbarItemComponent;
  33055. class ToolbarItemFactory;
  33056. class MissingItemsComponent;
  33057. /**
  33058. A toolbar component.
  33059. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  33060. and looks after their order and layout.
  33061. Items (icon buttons or other custom components) are added to a toolbar using a
  33062. ToolbarItemFactory - each type of item is given a unique ID number, and a
  33063. toolbar might contain more than one instance of a particular item type.
  33064. Toolbars can be interactively customised, allowing the user to drag the items
  33065. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  33066. component as a source of new items.
  33067. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  33068. */
  33069. class JUCE_API Toolbar : public Component,
  33070. public DragAndDropContainer,
  33071. public DragAndDropTarget,
  33072. private ButtonListener
  33073. {
  33074. public:
  33075. /** Creates an empty toolbar component.
  33076. To add some icons or other components to your toolbar, you'll need to
  33077. create a ToolbarItemFactory class that can create a suitable set of
  33078. ToolbarItemComponents.
  33079. @see ToolbarItemFactory, ToolbarItemComponents
  33080. */
  33081. Toolbar();
  33082. /** Destructor.
  33083. Any items on the bar will be deleted when the toolbar is deleted.
  33084. */
  33085. ~Toolbar();
  33086. /** Changes the bar's orientation.
  33087. @see isVertical
  33088. */
  33089. void setVertical (bool shouldBeVertical);
  33090. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  33091. You can change the bar's orientation with setVertical().
  33092. */
  33093. bool isVertical() const throw() { return vertical; }
  33094. /** Returns the depth of the bar.
  33095. If the bar is horizontal, this will return its height; if it's vertical, it
  33096. will return its width.
  33097. @see getLength
  33098. */
  33099. int getThickness() const throw();
  33100. /** Returns the length of the bar.
  33101. If the bar is horizontal, this will return its width; if it's vertical, it
  33102. will return its height.
  33103. @see getThickness
  33104. */
  33105. int getLength() const throw();
  33106. /** Deletes all items from the bar.
  33107. */
  33108. void clear();
  33109. /** Adds an item to the toolbar.
  33110. The factory's ToolbarItemFactory::createItem() will be called by this method
  33111. to create the component that will actually be added to the bar.
  33112. The new item will be inserted at the specified index (if the index is -1, it
  33113. will be added to the right-hand or bottom end of the bar).
  33114. Once added, the component will be automatically deleted by this object when it
  33115. is no longer needed.
  33116. @see ToolbarItemFactory
  33117. */
  33118. void addItem (ToolbarItemFactory& factory,
  33119. int itemId,
  33120. int insertIndex = -1);
  33121. /** Deletes one of the items from the bar.
  33122. */
  33123. void removeToolbarItem (int itemIndex);
  33124. /** Returns the number of items currently on the toolbar.
  33125. @see getItemId, getItemComponent
  33126. */
  33127. int getNumItems() const throw();
  33128. /** Returns the ID of the item with the given index.
  33129. If the index is less than zero or greater than the number of items,
  33130. this will return 0.
  33131. @see getNumItems
  33132. */
  33133. int getItemId (int itemIndex) const throw();
  33134. /** Returns the component being used for the item with the given index.
  33135. If the index is less than zero or greater than the number of items,
  33136. this will return 0.
  33137. @see getNumItems
  33138. */
  33139. ToolbarItemComponent* getItemComponent (int itemIndex) const throw();
  33140. /** Clears this toolbar and adds to it the default set of items that the specified
  33141. factory creates.
  33142. @see ToolbarItemFactory::getDefaultItemSet
  33143. */
  33144. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  33145. /** Options for the way items should be displayed.
  33146. @see setStyle, getStyle
  33147. */
  33148. enum ToolbarItemStyle
  33149. {
  33150. iconsOnly, /**< Means that the toolbar should just contain icons. */
  33151. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  33152. textOnly /**< Means that the toolbar only display text labels for each item. */
  33153. };
  33154. /** Returns the toolbar's current style.
  33155. @see ToolbarItemStyle, setStyle
  33156. */
  33157. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  33158. /** Changes the toolbar's current style.
  33159. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  33160. */
  33161. void setStyle (const ToolbarItemStyle& newStyle);
  33162. /** Flags used by the showCustomisationDialog() method. */
  33163. enum CustomisationFlags
  33164. {
  33165. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  33166. show the "icons only" option on its choice of toolbar styles. */
  33167. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  33168. show the "icons with text" option on its choice of toolbar styles. */
  33169. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  33170. show the "text only" option on its choice of toolbar styles. */
  33171. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  33172. show a button to reset the toolbar to its default set of items. */
  33173. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  33174. };
  33175. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  33176. The dialog contains a ToolbarItemPalette and various controls for editing other
  33177. aspects of the toolbar. This method will block and run the dialog box modally,
  33178. returning when the user closes it.
  33179. The factory is used to determine the set of items that will be shown on the
  33180. palette.
  33181. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  33182. enum.
  33183. @see ToolbarItemPalette
  33184. */
  33185. void showCustomisationDialog (ToolbarItemFactory& factory,
  33186. int optionFlags = allCustomisationOptionsEnabled);
  33187. /** Turns on or off the toolbar's editing mode, in which its items can be
  33188. rearranged by the user.
  33189. (In most cases it's easier just to use showCustomisationDialog() instead of
  33190. trying to enable editing directly).
  33191. @see ToolbarItemPalette
  33192. */
  33193. void setEditingActive (bool editingEnabled);
  33194. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  33195. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33196. methods.
  33197. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33198. */
  33199. enum ColourIds
  33200. {
  33201. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  33202. more control over this, override LookAndFeel::paintToolbarBackground(). */
  33203. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  33204. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  33205. over them. */
  33206. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  33207. held down on them. */
  33208. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  33209. when the style is set to iconsWithText or textOnly. */
  33210. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  33211. the customisation dialog is active and the mouse moves over them. */
  33212. };
  33213. /** Returns a string that represents the toolbar's current set of items.
  33214. This lets you later restore the same item layout using restoreFromString().
  33215. @see restoreFromString
  33216. */
  33217. const String toString() const;
  33218. /** Restores a set of items that was previously stored in a string by the toString()
  33219. method.
  33220. The factory object is used to create any item components that are needed.
  33221. @see toString
  33222. */
  33223. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  33224. const String& savedVersion);
  33225. /** @internal */
  33226. void paint (Graphics& g);
  33227. /** @internal */
  33228. void resized();
  33229. /** @internal */
  33230. void buttonClicked (Button*);
  33231. /** @internal */
  33232. void mouseDown (const MouseEvent&);
  33233. /** @internal */
  33234. bool isInterestedInDragSource (const String&, Component*);
  33235. /** @internal */
  33236. void itemDragMove (const String&, Component*, int, int);
  33237. /** @internal */
  33238. void itemDragExit (const String&, Component*);
  33239. /** @internal */
  33240. void itemDropped (const String&, Component*, int, int);
  33241. /** @internal */
  33242. void updateAllItemPositions (const bool animate);
  33243. /** @internal */
  33244. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  33245. juce_UseDebuggingNewOperator
  33246. private:
  33247. Button* missingItemsButton;
  33248. bool vertical, isEditingActive;
  33249. ToolbarItemStyle toolbarStyle;
  33250. ComponentAnimator animator;
  33251. friend class MissingItemsComponent;
  33252. Array <ToolbarItemComponent*> items;
  33253. friend class ItemDragAndDropOverlayComponent;
  33254. static const char* const toolbarDragDescriptor;
  33255. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  33256. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  33257. Toolbar (const Toolbar&);
  33258. Toolbar& operator= (const Toolbar&);
  33259. };
  33260. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  33261. /*** End of inlined file: juce_Toolbar.h ***/
  33262. class ItemDragAndDropOverlayComponent;
  33263. /**
  33264. A component that can be used as one of the items in a Toolbar.
  33265. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  33266. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  33267. class for further info about creating them.
  33268. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  33269. components too. To do this, set the value of isBeingUsedAsAButton to false when
  33270. calling the constructor, and override contentAreaChanged(), in which you can position
  33271. any sub-components you need to add.
  33272. To add basic buttons without writing a special subclass, have a look at the
  33273. ToolbarButton class.
  33274. @see ToolbarButton, Toolbar, ToolbarItemFactory
  33275. */
  33276. class JUCE_API ToolbarItemComponent : public Button
  33277. {
  33278. public:
  33279. /** Constructor.
  33280. @param itemId the ID of the type of toolbar item which this represents
  33281. @param labelText the text to display if the toolbar's style is set to
  33282. Toolbar::iconsWithText or Toolbar::textOnly
  33283. @param isBeingUsedAsAButton set this to false if you don't want the button
  33284. to draw itself with button over/down states when the mouse
  33285. moves over it or clicks
  33286. */
  33287. ToolbarItemComponent (int itemId,
  33288. const String& labelText,
  33289. bool isBeingUsedAsAButton);
  33290. /** Destructor. */
  33291. ~ToolbarItemComponent();
  33292. /** Returns the item type ID that this component represents.
  33293. This value is in the constructor.
  33294. */
  33295. int getItemId() const throw() { return itemId; }
  33296. /** Returns the toolbar that contains this component, or 0 if it's not currently
  33297. inside one.
  33298. */
  33299. Toolbar* getToolbar() const;
  33300. /** Returns true if this component is currently inside a toolbar which is vertical.
  33301. @see Toolbar::isVertical
  33302. */
  33303. bool isToolbarVertical() const;
  33304. /** Returns the current style setting of this item.
  33305. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  33306. @see setStyle, Toolbar::getStyle
  33307. */
  33308. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  33309. /** Changes the current style setting of this item.
  33310. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  33311. by the toolbar that holds this item.
  33312. @see setStyle, Toolbar::setStyle
  33313. */
  33314. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  33315. /** Returns the area of the component that should be used to display the button image or
  33316. other contents of the item.
  33317. This content area may change when the item's style changes, and may leave a space around the
  33318. edge of the component where the text label can be shown.
  33319. @see contentAreaChanged
  33320. */
  33321. const Rectangle<int> getContentArea() const throw() { return contentArea; }
  33322. /** This method must return the size criteria for this item, based on a given toolbar
  33323. size and orientation.
  33324. The preferredSize, minSize and maxSize values must all be set by your implementation
  33325. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  33326. toolbar, they refer to the item's height.
  33327. The preferredSize is the size that the component would like to be, and this must be
  33328. between the min and max sizes. For a fixed-size item, simply set all three variables to
  33329. the same value.
  33330. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  33331. Toolbar::getThickness().
  33332. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  33333. vertically.
  33334. */
  33335. virtual bool getToolbarItemSizes (int toolbarThickness,
  33336. bool isToolbarVertical,
  33337. int& preferredSize,
  33338. int& minSize,
  33339. int& maxSize) = 0;
  33340. /** Your subclass should use this method to draw its content area.
  33341. The graphics object that is passed-in will have been clipped and had its origin
  33342. moved to fit the content area as specified get getContentArea(). The width and height
  33343. parameters are the width and height of the content area.
  33344. If the component you're writing isn't a button, you can just do nothing in this method.
  33345. */
  33346. virtual void paintButtonArea (Graphics& g,
  33347. int width, int height,
  33348. bool isMouseOver, bool isMouseDown) = 0;
  33349. /** Callback to indicate that the content area of this item has changed.
  33350. This might be because the component was resized, or because the style changed and
  33351. the space needed for the text label is different.
  33352. See getContentArea() for a description of what the area is.
  33353. */
  33354. virtual void contentAreaChanged (const Rectangle<int>& newBounds) = 0;
  33355. /** Editing modes.
  33356. These are used by setEditingMode(), but will be rarely needed in user code.
  33357. */
  33358. enum ToolbarEditingMode
  33359. {
  33360. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  33361. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  33362. customisation mode, and the items can be dragged around. */
  33363. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  33364. dragged onto a toolbar to add it to that bar.*/
  33365. };
  33366. /** Changes the editing mode of this component.
  33367. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  33368. and is unlikely to be of much use in end-user-code.
  33369. */
  33370. void setEditingMode (const ToolbarEditingMode newMode);
  33371. /** Returns the current editing mode of this component.
  33372. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  33373. and is unlikely to be of much use in end-user-code.
  33374. */
  33375. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  33376. /** @internal */
  33377. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  33378. /** @internal */
  33379. void resized();
  33380. juce_UseDebuggingNewOperator
  33381. private:
  33382. friend class Toolbar;
  33383. friend class ItemDragAndDropOverlayComponent;
  33384. const int itemId;
  33385. ToolbarEditingMode mode;
  33386. Toolbar::ToolbarItemStyle toolbarStyle;
  33387. ScopedPointer <Component> overlayComp;
  33388. int dragOffsetX, dragOffsetY;
  33389. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  33390. Rectangle<int> contentArea;
  33391. ToolbarItemComponent (const ToolbarItemComponent&);
  33392. ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  33393. };
  33394. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  33395. /*** End of inlined file: juce_ToolbarItemComponent.h ***/
  33396. /**
  33397. A type of button designed to go on a toolbar.
  33398. This simple button can have two Drawable objects specified - one for normal
  33399. use and another one (optionally) for the button's "on" state if it's a
  33400. toggle button.
  33401. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  33402. */
  33403. class JUCE_API ToolbarButton : public ToolbarItemComponent
  33404. {
  33405. public:
  33406. /** Creates a ToolbarButton.
  33407. @param itemId the ID for this toolbar item type. This is passed through to the
  33408. ToolbarItemComponent constructor
  33409. @param labelText the text to display on the button (if the toolbar is using a style
  33410. that shows text labels). This is passed through to the
  33411. ToolbarItemComponent constructor
  33412. @param normalImage a drawable object that the button should use as its icon. The object
  33413. that is passed-in here will be kept by this object and will be
  33414. deleted when no longer needed or when this button is deleted.
  33415. @param toggledOnImage a drawable object that the button can use as its icon if the button
  33416. is in a toggled-on state (see the Button::getToggleState() method). If
  33417. 0 is passed-in here, then the normal image will be used instead, regardless
  33418. of the toggle state. The object that is passed-in here will be kept by
  33419. this object and will be deleted when no longer needed or when this button
  33420. is deleted.
  33421. */
  33422. ToolbarButton (int itemId,
  33423. const String& labelText,
  33424. Drawable* normalImage,
  33425. Drawable* toggledOnImage);
  33426. /** Destructor. */
  33427. ~ToolbarButton();
  33428. /** @internal */
  33429. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  33430. int& minSize, int& maxSize);
  33431. /** @internal */
  33432. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  33433. /** @internal */
  33434. void contentAreaChanged (const Rectangle<int>& newBounds);
  33435. juce_UseDebuggingNewOperator
  33436. private:
  33437. ScopedPointer <Drawable> normalImage, toggledOnImage;
  33438. ToolbarButton (const ToolbarButton&);
  33439. ToolbarButton& operator= (const ToolbarButton&);
  33440. };
  33441. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  33442. /*** End of inlined file: juce_ToolbarButton.h ***/
  33443. #endif
  33444. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  33445. /*** Start of inlined file: juce_CodeDocument.h ***/
  33446. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  33447. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  33448. class CodeDocumentLine;
  33449. /**
  33450. A class for storing and manipulating a source code file.
  33451. When using a CodeEditorComponent, it takes one of these as its source object.
  33452. The CodeDocument stores its content as an array of lines, which makes it
  33453. quick to insert and delete.
  33454. @see CodeEditorComponent
  33455. */
  33456. class JUCE_API CodeDocument
  33457. {
  33458. public:
  33459. /** Creates a new, empty document.
  33460. */
  33461. CodeDocument();
  33462. /** Destructor. */
  33463. ~CodeDocument();
  33464. /** A position in a code document.
  33465. Using this class you can find a position in a code document and quickly get its
  33466. character position, line, and index. By calling setPositionMaintained (true), the
  33467. position is automatically updated when text is inserted or deleted in the document,
  33468. so that it maintains its original place in the text.
  33469. */
  33470. class JUCE_API Position
  33471. {
  33472. public:
  33473. /** Creates an uninitialised postion.
  33474. Don't attempt to call any methods on this until you've given it an owner document
  33475. to refer to!
  33476. */
  33477. Position() throw();
  33478. /** Creates a position based on a line and index in a document.
  33479. Note that this index is NOT the column number, it's the number of characters from the
  33480. start of the line. The "column" number isn't quite the same, because if the line
  33481. contains any tab characters, the relationship of the index to its visual column depends on
  33482. the number of spaces per tab being used!
  33483. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  33484. they will be adjusted to keep them within its limits.
  33485. */
  33486. Position (const CodeDocument* ownerDocument,
  33487. int line, int indexInLine) throw();
  33488. /** Creates a position based on a character index in a document.
  33489. This position is placed at the specified number of characters from the start of the
  33490. document. The line and column are auto-calculated.
  33491. If the position is beyond the range of the document, it'll be adjusted to keep it
  33492. inside.
  33493. */
  33494. Position (const CodeDocument* ownerDocument,
  33495. int charactersFromStartOfDocument) throw();
  33496. /** Creates a copy of another position.
  33497. This will copy the position, but the new object will not be set to maintain its position,
  33498. even if the source object was set to do so.
  33499. */
  33500. Position (const Position& other) throw();
  33501. /** Destructor. */
  33502. ~Position() throw();
  33503. Position& operator= (const Position& other) throw();
  33504. bool operator== (const Position& other) const throw();
  33505. bool operator!= (const Position& other) const throw();
  33506. /** Points this object at a new position within the document.
  33507. If the position is beyond the range of the document, it'll be adjusted to keep it
  33508. inside.
  33509. @see getPosition, setLineAndIndex
  33510. */
  33511. void setPosition (int charactersFromStartOfDocument) throw();
  33512. /** Returns the position as the number of characters from the start of the document.
  33513. @see setPosition, getLineNumber, getIndexInLine
  33514. */
  33515. int getPosition() const throw() { return characterPos; }
  33516. /** Moves the position to a new line and index within the line.
  33517. Note that the index is NOT the column at which the position appears in an editor.
  33518. If the line contains any tab characters, the relationship of the index to its
  33519. visual position depends on the number of spaces per tab being used!
  33520. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  33521. they will be adjusted to keep them within its limits.
  33522. */
  33523. void setLineAndIndex (int newLine, int newIndexInLine) throw();
  33524. /** Returns the line number of this position.
  33525. The first line in the document is numbered zero, not one!
  33526. */
  33527. int getLineNumber() const throw() { return line; }
  33528. /** Returns the number of characters from the start of the line.
  33529. Note that this value is NOT the column at which the position appears in an editor.
  33530. If the line contains any tab characters, the relationship of the index to its
  33531. visual position depends on the number of spaces per tab being used!
  33532. */
  33533. int getIndexInLine() const throw() { return indexInLine; }
  33534. /** Allows the position to be automatically updated when the document changes.
  33535. If this is set to true, the positon will register with its document so that
  33536. when the document has text inserted or deleted, this position will be automatically
  33537. moved to keep it at the same position in the text.
  33538. */
  33539. void setPositionMaintained (bool isMaintained) throw();
  33540. /** Moves the position forwards or backwards by the specified number of characters.
  33541. @see movedBy
  33542. */
  33543. void moveBy (int characterDelta) throw();
  33544. /** Returns a position which is the same as this one, moved by the specified number of
  33545. characters.
  33546. @see moveBy
  33547. */
  33548. const Position movedBy (int characterDelta) const throw();
  33549. /** Returns a position which is the same as this one, moved up or down by the specified
  33550. number of lines.
  33551. @see movedBy
  33552. */
  33553. const Position movedByLines (int deltaLines) const throw();
  33554. /** Returns the character in the document at this position.
  33555. @see getLineText
  33556. */
  33557. const juce_wchar getCharacter() const throw();
  33558. /** Returns the line from the document that this position is within.
  33559. @see getCharacter, getLineNumber
  33560. */
  33561. const String getLineText() const throw();
  33562. private:
  33563. CodeDocument* owner;
  33564. int characterPos, line, indexInLine;
  33565. bool positionMaintained;
  33566. };
  33567. /** Returns the full text of the document. */
  33568. const String getAllContent() const throw();
  33569. /** Returns a section of the document's text. */
  33570. const String getTextBetween (const Position& start, const Position& end) const throw();
  33571. /** Returns a line from the document. */
  33572. const String getLine (int lineIndex) const throw();
  33573. /** Returns the number of characters in the document. */
  33574. int getNumCharacters() const throw();
  33575. /** Returns the number of lines in the document. */
  33576. int getNumLines() const throw() { return lines.size(); }
  33577. /** Returns the number of characters in the longest line of the document. */
  33578. int getMaximumLineLength() throw();
  33579. /** Deletes a section of the text.
  33580. This operation is undoable.
  33581. */
  33582. void deleteSection (const Position& startPosition, const Position& endPosition);
  33583. /** Inserts some text into the document at a given position.
  33584. This operation is undoable.
  33585. */
  33586. void insertText (const Position& position, const String& text);
  33587. /** Clears the document and replaces it with some new text.
  33588. This operation is undoable - if you're trying to completely reset the document, you
  33589. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  33590. */
  33591. void replaceAllContent (const String& newContent);
  33592. /** Replaces the editor's contents with the contents of a stream.
  33593. This will also reset the undo history and save point marker.
  33594. */
  33595. bool loadFromStream (InputStream& stream);
  33596. /** Writes the editor's current contents to a stream. */
  33597. bool writeToStream (OutputStream& stream);
  33598. /** Returns the preferred new-line characters for the document.
  33599. This will be either "\n", "\r\n", or (rarely) "\r".
  33600. @see setNewLineCharacters
  33601. */
  33602. const String getNewLineCharacters() const throw() { return newLineChars; }
  33603. /** Sets the new-line characters that the document should use.
  33604. The string must be either "\n", "\r\n", or (rarely) "\r".
  33605. @see getNewLineCharacters
  33606. */
  33607. void setNewLineCharacters (const String& newLine) throw();
  33608. /** Begins a new undo transaction.
  33609. The document itself will not call this internally, so relies on whatever is using the
  33610. document to periodically call this to break up the undo sequence into sensible chunks.
  33611. @see UndoManager::beginNewTransaction
  33612. */
  33613. void newTransaction();
  33614. /** Undo the last operation.
  33615. @see UndoManager::undo
  33616. */
  33617. void undo();
  33618. /** Redo the last operation.
  33619. @see UndoManager::redo
  33620. */
  33621. void redo();
  33622. /** Clears the undo history.
  33623. @see UndoManager::clearUndoHistory
  33624. */
  33625. void clearUndoHistory();
  33626. /** Returns the document's UndoManager */
  33627. UndoManager& getUndoManager() throw() { return undoManager; }
  33628. /** Makes a note that the document's current state matches the one that is saved.
  33629. After this has been called, hasChangedSinceSavePoint() will return false until
  33630. the document has been altered, and then it'll start returning true. If the document is
  33631. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  33632. will again return false.
  33633. @see hasChangedSinceSavePoint
  33634. */
  33635. void setSavePoint() throw();
  33636. /** Returns true if the state of the document differs from the state it was in when
  33637. setSavePoint() was last called.
  33638. @see setSavePoint
  33639. */
  33640. bool hasChangedSinceSavePoint() const throw();
  33641. /** Searches for a word-break. */
  33642. const Position findWordBreakAfter (const Position& position) const throw();
  33643. /** Searches for a word-break. */
  33644. const Position findWordBreakBefore (const Position& position) const throw();
  33645. /** An object that receives callbacks from the CodeDocument when its text changes.
  33646. @see CodeDocument::addListener, CodeDocument::removeListener
  33647. */
  33648. class JUCE_API Listener
  33649. {
  33650. public:
  33651. Listener() {}
  33652. virtual ~Listener() {}
  33653. /** Called by a CodeDocument when it is altered.
  33654. */
  33655. virtual void codeDocumentChanged (const Position& affectedTextStart,
  33656. const Position& affectedTextEnd) = 0;
  33657. };
  33658. /** Registers a listener object to receive callbacks when the document changes.
  33659. If the listener is already registered, this method has no effect.
  33660. @see removeListener
  33661. */
  33662. void addListener (Listener* listener) throw();
  33663. /** Deregisters a listener.
  33664. @see addListener
  33665. */
  33666. void removeListener (Listener* listener) throw();
  33667. /** Iterates the text in a CodeDocument.
  33668. This class lets you read characters from a CodeDocument. It's designed to be used
  33669. by a SyntaxAnalyser object.
  33670. @see CodeDocument, SyntaxAnalyser
  33671. */
  33672. class Iterator
  33673. {
  33674. public:
  33675. Iterator (CodeDocument* document);
  33676. Iterator (const Iterator& other);
  33677. Iterator& operator= (const Iterator& other) throw();
  33678. ~Iterator() throw();
  33679. /** Reads the next character and returns it.
  33680. @see peekNextChar
  33681. */
  33682. juce_wchar nextChar();
  33683. /** Reads the next character without advancing the current position. */
  33684. juce_wchar peekNextChar() const;
  33685. /** Advances the position by one character. */
  33686. void skip();
  33687. /** Returns the position of the next character as its position within the
  33688. whole document.
  33689. */
  33690. int getPosition() const throw() { return position; }
  33691. /** Skips over any whitespace characters until the next character is non-whitespace. */
  33692. void skipWhitespace();
  33693. /** Skips forward until the next character will be the first character on the next line */
  33694. void skipToEndOfLine();
  33695. /** Returns the line number of the next character. */
  33696. int getLine() const throw() { return line; }
  33697. /** Returns true if the iterator has reached the end of the document. */
  33698. bool isEOF() const throw();
  33699. private:
  33700. CodeDocument* document;
  33701. CodeDocumentLine* currentLine;
  33702. int line, position;
  33703. };
  33704. juce_UseDebuggingNewOperator
  33705. private:
  33706. friend class CodeDocumentInsertAction;
  33707. friend class CodeDocumentDeleteAction;
  33708. friend class Iterator;
  33709. friend class Position;
  33710. OwnedArray <CodeDocumentLine> lines;
  33711. Array <Position*> positionsToMaintain;
  33712. UndoManager undoManager;
  33713. int currentActionIndex, indexOfSavedState;
  33714. int maximumLineLength;
  33715. ListenerList <Listener> listeners;
  33716. String newLineChars;
  33717. void sendListenerChangeMessage (int startLine, int endLine);
  33718. void insert (const String& text, int insertPos, bool undoable);
  33719. void remove (int startPos, int endPos, bool undoable);
  33720. void checkLastLineStatus();
  33721. CodeDocument (const CodeDocument&);
  33722. CodeDocument& operator= (const CodeDocument&);
  33723. };
  33724. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  33725. /*** End of inlined file: juce_CodeDocument.h ***/
  33726. #endif
  33727. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33728. /*** Start of inlined file: juce_CodeEditorComponent.h ***/
  33729. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33730. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33731. /*** Start of inlined file: juce_CodeTokeniser.h ***/
  33732. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  33733. #define __JUCE_CODETOKENISER_JUCEHEADER__
  33734. /**
  33735. A base class for tokenising code so that the syntax can be displayed in a
  33736. code editor.
  33737. @see CodeDocument, CodeEditorComponent
  33738. */
  33739. class JUCE_API CodeTokeniser
  33740. {
  33741. public:
  33742. CodeTokeniser() {}
  33743. virtual ~CodeTokeniser() {}
  33744. /** Reads the next token from the source and returns its token type.
  33745. This must leave the source pointing to the first character in the
  33746. next token.
  33747. */
  33748. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  33749. /** Returns a list of the names of the token types this analyser uses.
  33750. The index in this list must match the token type numbers that are
  33751. returned by readNextToken().
  33752. */
  33753. virtual const StringArray getTokenTypes() = 0;
  33754. /** Returns a suggested syntax highlighting colour for a specified
  33755. token type.
  33756. */
  33757. virtual const Colour getDefaultColour (int tokenType) = 0;
  33758. juce_UseDebuggingNewOperator
  33759. };
  33760. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  33761. /*** End of inlined file: juce_CodeTokeniser.h ***/
  33762. /**
  33763. A text editor component designed specifically for source code.
  33764. This is designed to handle syntax highlighting and fast editing of very large
  33765. files.
  33766. */
  33767. class JUCE_API CodeEditorComponent : public Component,
  33768. public TextInputTarget,
  33769. public Timer,
  33770. public ScrollBarListener,
  33771. public CodeDocument::Listener,
  33772. public AsyncUpdater
  33773. {
  33774. public:
  33775. /** Creates an editor for a document.
  33776. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  33777. The object that you pass in is not owned or deleted by the editor - you must
  33778. make sure that it doesn't get deleted while this component is still using it.
  33779. @see CodeDocument
  33780. */
  33781. CodeEditorComponent (CodeDocument& document,
  33782. CodeTokeniser* codeTokeniser);
  33783. /** Destructor. */
  33784. ~CodeEditorComponent();
  33785. /** Returns the code document that this component is editing. */
  33786. CodeDocument& getDocument() const throw() { return document; }
  33787. /** Loads the given content into the document.
  33788. This will completely reset the CodeDocument object, clear its undo history,
  33789. and fill it with this text.
  33790. */
  33791. void loadContent (const String& newContent);
  33792. /** Returns the standard character width. */
  33793. float getCharWidth() const throw() { return charWidth; }
  33794. /** Returns the height of a line of text, in pixels. */
  33795. int getLineHeight() const throw() { return lineHeight; }
  33796. /** Returns the number of whole lines visible on the screen,
  33797. This doesn't include a cut-off line that might be visible at the bottom if the
  33798. component's height isn't an exact multiple of the line-height.
  33799. */
  33800. int getNumLinesOnScreen() const throw() { return linesOnScreen; }
  33801. /** Returns the number of whole columns visible on the screen.
  33802. This doesn't include any cut-off columns at the right-hand edge.
  33803. */
  33804. int getNumColumnsOnScreen() const throw() { return columnsOnScreen; }
  33805. /** Returns the current caret position. */
  33806. const CodeDocument::Position getCaretPos() const { return caretPos; }
  33807. /** Moves the caret.
  33808. If selecting is true, the section of the document between the current
  33809. caret position and the new one will become selected. If false, any currently
  33810. selected region will be deselected.
  33811. */
  33812. void moveCaretTo (const CodeDocument::Position& newPos, bool selecting);
  33813. /** Returns the on-screen position of a character in the document.
  33814. The rectangle returned is relative to this component's top-left origin.
  33815. */
  33816. const Rectangle<int> getCharacterBounds (const CodeDocument::Position& pos) const throw();
  33817. /** Finds the character at a given on-screen position.
  33818. The co-ordinates are relative to this component's top-left origin.
  33819. */
  33820. const CodeDocument::Position getPositionAt (int x, int y);
  33821. void cursorLeft (bool moveInWholeWordSteps, bool selecting);
  33822. void cursorRight (bool moveInWholeWordSteps, bool selecting);
  33823. void cursorDown (bool selecting);
  33824. void cursorUp (bool selecting);
  33825. void pageDown (bool selecting);
  33826. void pageUp (bool selecting);
  33827. void scrollDown();
  33828. void scrollUp();
  33829. void scrollToLine (int newFirstLineOnScreen);
  33830. void scrollBy (int deltaLines);
  33831. void scrollToColumn (int newFirstColumnOnScreen);
  33832. void scrollToKeepCaretOnScreen();
  33833. void goToStartOfDocument (bool selecting);
  33834. void goToStartOfLine (bool selecting);
  33835. void goToEndOfDocument (bool selecting);
  33836. void goToEndOfLine (bool selecting);
  33837. void deselectAll();
  33838. void selectAll();
  33839. void insertTextAtCaret (const String& textToInsert);
  33840. void insertTabAtCaret();
  33841. void cut();
  33842. void copy();
  33843. void copyThenCut();
  33844. void paste();
  33845. void backspace (bool moveInWholeWordSteps);
  33846. void deleteForward (bool moveInWholeWordSteps);
  33847. void undo();
  33848. void redo();
  33849. const Range<int> getHighlightedRegion() const;
  33850. void setHighlightedRegion (const Range<int>& newRange);
  33851. const String getTextInRange (const Range<int>& range) const;
  33852. /** Changes the current tab settings.
  33853. This lets you change the tab size and whether pressing the tab key inserts a
  33854. tab character, or its equivalent number of spaces.
  33855. */
  33856. void setTabSize (int numSpacesPerTab,
  33857. bool insertSpacesInsteadOfTabCharacters) throw();
  33858. /** Returns the current number of spaces per tab.
  33859. @see setTabSize
  33860. */
  33861. int getTabSize() const throw() { return spacesPerTab; }
  33862. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  33863. @see setTabSize
  33864. */
  33865. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  33866. /** Changes the font.
  33867. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  33868. */
  33869. void setFont (const Font& newFont);
  33870. /** Returns the font that the editor is using. */
  33871. const Font& getFont() const throw() { return font; }
  33872. /** Resets the syntax highlighting colours to the default ones provided by the
  33873. code tokeniser.
  33874. @see CodeTokeniser::getDefaultColour
  33875. */
  33876. void resetToDefaultColours();
  33877. /** Changes one of the syntax highlighting colours.
  33878. The token type values are dependent on the tokeniser being used - use
  33879. CodeTokeniser::getTokenTypes() to get a list of the token types.
  33880. @see getColourForTokenType
  33881. */
  33882. void setColourForTokenType (int tokenType, const Colour& colour);
  33883. /** Returns one of the syntax highlighting colours.
  33884. The token type values are dependent on the tokeniser being used - use
  33885. CodeTokeniser::getTokenTypes() to get a list of the token types.
  33886. @see setColourForTokenType
  33887. */
  33888. const Colour getColourForTokenType (int tokenType) const throw();
  33889. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  33890. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33891. methods.
  33892. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33893. */
  33894. enum ColourIds
  33895. {
  33896. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  33897. caretColourId = 0x1004501, /**< The colour to draw the caret. */
  33898. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  33899. selected text. */
  33900. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  33901. enabled. */
  33902. };
  33903. /** Changes the size of the scrollbars. */
  33904. void setScrollbarThickness (int thickness) throw();
  33905. /** Returns the thickness of the scrollbars. */
  33906. int getScrollbarThickness() const throw() { return scrollbarThickness; }
  33907. /** @internal */
  33908. void resized();
  33909. /** @internal */
  33910. void paint (Graphics& g);
  33911. /** @internal */
  33912. bool keyPressed (const KeyPress& key);
  33913. /** @internal */
  33914. void mouseDown (const MouseEvent& e);
  33915. /** @internal */
  33916. void mouseDrag (const MouseEvent& e);
  33917. /** @internal */
  33918. void mouseUp (const MouseEvent& e);
  33919. /** @internal */
  33920. void mouseDoubleClick (const MouseEvent& e);
  33921. /** @internal */
  33922. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  33923. /** @internal */
  33924. void focusGained (FocusChangeType cause);
  33925. /** @internal */
  33926. void focusLost (FocusChangeType cause);
  33927. /** @internal */
  33928. void timerCallback();
  33929. /** @internal */
  33930. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  33931. /** @internal */
  33932. void handleAsyncUpdate();
  33933. /** @internal */
  33934. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  33935. const CodeDocument::Position& affectedTextEnd);
  33936. /** @internal */
  33937. bool isTextInputActive() const;
  33938. juce_UseDebuggingNewOperator
  33939. private:
  33940. CodeDocument& document;
  33941. Font font;
  33942. int firstLineOnScreen, gutter, spacesPerTab;
  33943. float charWidth;
  33944. int lineHeight, linesOnScreen, columnsOnScreen;
  33945. int scrollbarThickness, columnToTryToMaintain;
  33946. bool useSpacesForTabs;
  33947. double xOffset;
  33948. CodeDocument::Position caretPos;
  33949. CodeDocument::Position selectionStart, selectionEnd;
  33950. class CaretComponent;
  33951. CaretComponent* caret;
  33952. ScrollBar* verticalScrollBar;
  33953. ScrollBar* horizontalScrollBar;
  33954. enum DragType
  33955. {
  33956. notDragging,
  33957. draggingSelectionStart,
  33958. draggingSelectionEnd
  33959. };
  33960. DragType dragType;
  33961. CodeTokeniser* codeTokeniser;
  33962. Array <Colour> coloursForTokenCategories;
  33963. class CodeEditorLine;
  33964. OwnedArray <CodeEditorLine> lines;
  33965. void rebuildLineTokens();
  33966. OwnedArray <CodeDocument::Iterator> cachedIterators;
  33967. void clearCachedIterators (int firstLineToBeInvalid) throw();
  33968. void updateCachedIterators (int maxLineNum);
  33969. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  33970. void moveLineDelta (int delta, bool selecting);
  33971. void updateScrollBars();
  33972. void scrollToLineInternal (int line);
  33973. void scrollToColumnInternal (double column);
  33974. void newTransaction();
  33975. int indexToColumn (int line, int index) const throw();
  33976. int columnToIndex (int line, int column) const throw();
  33977. CodeEditorComponent (const CodeEditorComponent&);
  33978. CodeEditorComponent& operator= (const CodeEditorComponent&);
  33979. };
  33980. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33981. /*** End of inlined file: juce_CodeEditorComponent.h ***/
  33982. #endif
  33983. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  33984. #endif
  33985. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  33986. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  33987. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  33988. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  33989. /**
  33990. A simple lexical analyser for syntax colouring of C++ code.
  33991. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  33992. */
  33993. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  33994. {
  33995. public:
  33996. CPlusPlusCodeTokeniser();
  33997. ~CPlusPlusCodeTokeniser();
  33998. enum TokenType
  33999. {
  34000. tokenType_error = 0,
  34001. tokenType_comment,
  34002. tokenType_builtInKeyword,
  34003. tokenType_identifier,
  34004. tokenType_integerLiteral,
  34005. tokenType_floatLiteral,
  34006. tokenType_stringLiteral,
  34007. tokenType_operator,
  34008. tokenType_bracket,
  34009. tokenType_punctuation,
  34010. tokenType_preprocessor
  34011. };
  34012. int readNextToken (CodeDocument::Iterator& source);
  34013. const StringArray getTokenTypes();
  34014. const Colour getDefaultColour (int tokenType);
  34015. /** This is a handy method for checking whether a string is a c++ reserved keyword. */
  34016. static bool isReservedKeyword (const String& token) throw();
  34017. juce_UseDebuggingNewOperator
  34018. };
  34019. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  34020. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  34021. #endif
  34022. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  34023. #endif
  34024. #ifndef __JUCE_LABEL_JUCEHEADER__
  34025. #endif
  34026. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  34027. #endif
  34028. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  34029. /*** Start of inlined file: juce_ProgressBar.h ***/
  34030. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  34031. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  34032. /**
  34033. A progress bar component.
  34034. To use this, just create one and make it visible. It'll run its own timer
  34035. to keep an eye on a variable that you give it, and will automatically
  34036. redraw itself when the variable changes.
  34037. For an easy way of running a background task with a dialog box showing its
  34038. progress, see the ThreadWithProgressWindow class.
  34039. @see ThreadWithProgressWindow
  34040. */
  34041. class JUCE_API ProgressBar : public Component,
  34042. public SettableTooltipClient,
  34043. private Timer
  34044. {
  34045. public:
  34046. /** Creates a ProgressBar.
  34047. @param progress pass in a reference to a double that you're going to
  34048. update with your task's progress. The ProgressBar will
  34049. monitor the value of this variable and will redraw itself
  34050. when the value changes. The range is from 0 to 1.0. Obviously
  34051. you'd better be careful not to delete this variable while the
  34052. ProgressBar still exists!
  34053. */
  34054. explicit ProgressBar (double& progress);
  34055. /** Destructor. */
  34056. ~ProgressBar();
  34057. /** Turns the percentage display on or off.
  34058. By default this is on, and the progress bar will display a text string showing
  34059. its current percentage.
  34060. */
  34061. void setPercentageDisplay (const bool shouldDisplayPercentage);
  34062. /** Gives the progress bar a string to display inside it.
  34063. If you call this, it will turn off the percentage display.
  34064. @see setPercentageDisplay
  34065. */
  34066. void setTextToDisplay (const String& text);
  34067. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  34068. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34069. methods.
  34070. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34071. */
  34072. enum ColourIds
  34073. {
  34074. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  34075. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  34076. classes will probably use variations on this colour. */
  34077. };
  34078. juce_UseDebuggingNewOperator
  34079. protected:
  34080. /** @internal */
  34081. void paint (Graphics& g);
  34082. /** @internal */
  34083. void lookAndFeelChanged();
  34084. /** @internal */
  34085. void visibilityChanged();
  34086. /** @internal */
  34087. void colourChanged();
  34088. private:
  34089. double& progress;
  34090. double currentValue;
  34091. bool displayPercentage;
  34092. String displayedMessage, currentMessage;
  34093. uint32 lastCallbackTime;
  34094. void timerCallback();
  34095. ProgressBar (const ProgressBar&);
  34096. ProgressBar& operator= (const ProgressBar&);
  34097. };
  34098. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  34099. /*** End of inlined file: juce_ProgressBar.h ***/
  34100. #endif
  34101. #ifndef __JUCE_SLIDER_JUCEHEADER__
  34102. /*** Start of inlined file: juce_Slider.h ***/
  34103. #ifndef __JUCE_SLIDER_JUCEHEADER__
  34104. #define __JUCE_SLIDER_JUCEHEADER__
  34105. /*** Start of inlined file: juce_SliderListener.h ***/
  34106. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  34107. #define __JUCE_SLIDERLISTENER_JUCEHEADER__
  34108. class Slider;
  34109. /**
  34110. A class for receiving callbacks from a Slider.
  34111. To be told when a slider's value changes, you can register a SliderListener
  34112. object using Slider::addListener().
  34113. @see Slider::addListener, Slider::removeListener
  34114. */
  34115. class JUCE_API SliderListener
  34116. {
  34117. public:
  34118. /** Destructor. */
  34119. virtual ~SliderListener() {}
  34120. /** Called when the slider's value is changed.
  34121. This may be caused by dragging it, or by typing in its text entry box,
  34122. or by a call to Slider::setValue().
  34123. You can find out the new value using Slider::getValue().
  34124. @see Slider::valueChanged
  34125. */
  34126. virtual void sliderValueChanged (Slider* slider) = 0;
  34127. /** Called when the slider is about to be dragged.
  34128. This is called when a drag begins, then it's followed by multiple calls
  34129. to sliderValueChanged(), and then sliderDragEnded() is called after the
  34130. user lets go.
  34131. @see sliderDragEnded, Slider::startedDragging
  34132. */
  34133. virtual void sliderDragStarted (Slider* slider);
  34134. /** Called after a drag operation has finished.
  34135. @see sliderDragStarted, Slider::stoppedDragging
  34136. */
  34137. virtual void sliderDragEnded (Slider* slider);
  34138. };
  34139. #endif // __JUCE_SLIDERLISTENER_JUCEHEADER__
  34140. /*** End of inlined file: juce_SliderListener.h ***/
  34141. /**
  34142. A slider control for changing a value.
  34143. The slider can be horizontal, vertical, or rotary, and can optionally have
  34144. a text-box inside it to show an editable display of the current value.
  34145. To use it, create a Slider object and use the setSliderStyle() method
  34146. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  34147. To define the values that it can be set to, see the setRange() and setValue() methods.
  34148. There are also lots of custom tweaks you can do by subclassing and overriding
  34149. some of the virtual methods, such as changing the scaling, changing the format of
  34150. the text display, custom ways of limiting the values, etc.
  34151. You can register SliderListeners with a slider, which will be informed when the value
  34152. changes, or a subclass can override valueChanged() to be informed synchronously.
  34153. @see SliderListener
  34154. */
  34155. class JUCE_API Slider : public Component,
  34156. public SettableTooltipClient,
  34157. private AsyncUpdater,
  34158. private ButtonListener,
  34159. private LabelListener,
  34160. private Value::Listener
  34161. {
  34162. public:
  34163. /** Creates a slider.
  34164. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  34165. setRange(), etc.
  34166. */
  34167. explicit Slider (const String& componentName = String::empty);
  34168. /** Destructor. */
  34169. ~Slider();
  34170. /** The types of slider available.
  34171. @see setSliderStyle, setRotaryParameters
  34172. */
  34173. enum SliderStyle
  34174. {
  34175. LinearHorizontal, /**< A traditional horizontal slider. */
  34176. LinearVertical, /**< A traditional vertical slider. */
  34177. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  34178. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  34179. @see setRotaryParameters */
  34180. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  34181. @see setRotaryParameters */
  34182. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  34183. @see setRotaryParameters */
  34184. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  34185. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  34186. @see setMinValue, setMaxValue */
  34187. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  34188. @see setMinValue, setMaxValue */
  34189. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  34190. value, with the current value being somewhere between them.
  34191. @see setMinValue, setMaxValue */
  34192. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  34193. value, with the current value being somewhere between them.
  34194. @see setMinValue, setMaxValue */
  34195. };
  34196. /** Changes the type of slider interface being used.
  34197. @param newStyle the type of interface
  34198. @see setRotaryParameters, setVelocityBasedMode,
  34199. */
  34200. void setSliderStyle (SliderStyle newStyle);
  34201. /** Returns the slider's current style.
  34202. @see setSliderStyle
  34203. */
  34204. SliderStyle getSliderStyle() const { return style; }
  34205. /** Changes the properties of a rotary slider.
  34206. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  34207. the slider's minimum value is represented
  34208. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  34209. the slider's maximum value is represented. This must be
  34210. greater than startAngleRadians
  34211. @param stopAtEnd if true, then when the slider is dragged around past the
  34212. minimum or maximum, it'll stop there; if false, it'll wrap
  34213. back to the opposite value
  34214. */
  34215. void setRotaryParameters (float startAngleRadians,
  34216. float endAngleRadians,
  34217. bool stopAtEnd);
  34218. /** Sets the distance the mouse has to move to drag the slider across
  34219. the full extent of its range.
  34220. This only applies when in modes like RotaryHorizontalDrag, where it's using
  34221. relative mouse movements to adjust the slider.
  34222. */
  34223. void setMouseDragSensitivity (int distanceForFullScaleDrag);
  34224. /** Changes the way the the mouse is used when dragging the slider.
  34225. If true, this will turn on velocity-sensitive dragging, so that
  34226. the faster the mouse moves, the bigger the movement to the slider. This
  34227. helps when making accurate adjustments if the slider's range is quite large.
  34228. If false, the slider will just try to snap to wherever the mouse is.
  34229. */
  34230. void setVelocityBasedMode (bool isVelocityBased);
  34231. /** Returns true if velocity-based mode is active.
  34232. @see setVelocityBasedMode
  34233. */
  34234. bool getVelocityBasedMode() const { return isVelocityBased; }
  34235. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  34236. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  34237. or if you're holding down ctrl.
  34238. @param sensitivity higher values than 1.0 increase the range of acceleration used
  34239. @param threshold the minimum number of pixels that the mouse needs to move for it
  34240. to be treated as a movement
  34241. @param offset values greater than 0.0 increase the minimum speed that will be used when
  34242. the threshold is reached
  34243. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  34244. key to toggle velocity-sensitive mode
  34245. */
  34246. void setVelocityModeParameters (double sensitivity = 1.0,
  34247. int threshold = 1,
  34248. double offset = 0.0,
  34249. bool userCanPressKeyToSwapMode = true);
  34250. /** Returns the velocity sensitivity setting.
  34251. @see setVelocityModeParameters
  34252. */
  34253. double getVelocitySensitivity() const { return velocityModeSensitivity; }
  34254. /** Returns the velocity threshold setting.
  34255. @see setVelocityModeParameters
  34256. */
  34257. int getVelocityThreshold() const { return velocityModeThreshold; }
  34258. /** Returns the velocity offset setting.
  34259. @see setVelocityModeParameters
  34260. */
  34261. double getVelocityOffset() const { return velocityModeOffset; }
  34262. /** Returns the velocity user key setting.
  34263. @see setVelocityModeParameters
  34264. */
  34265. bool getVelocityModeIsSwappable() const { return userKeyOverridesVelocity; }
  34266. /** Sets up a skew factor to alter the way values are distributed.
  34267. You may want to use a range of values on the slider where more accuracy
  34268. is required towards one end of the range, so this will logarithmically
  34269. spread the values across the length of the slider.
  34270. If the factor is < 1.0, the lower end of the range will fill more of the
  34271. slider's length; if the factor is > 1.0, the upper end of the range
  34272. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  34273. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  34274. method instead.
  34275. @see getSkewFactor, setSkewFactorFromMidPoint
  34276. */
  34277. void setSkewFactor (double factor);
  34278. /** Sets up a skew factor to alter the way values are distributed.
  34279. This allows you to specify the slider value that should appear in the
  34280. centre of the slider's visible range.
  34281. @see setSkewFactor, getSkewFactor
  34282. */
  34283. void setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint);
  34284. /** Returns the current skew factor.
  34285. See setSkewFactor for more info.
  34286. @see setSkewFactor, setSkewFactorFromMidPoint
  34287. */
  34288. double getSkewFactor() const { return skewFactor; }
  34289. /** Used by setIncDecButtonsMode().
  34290. */
  34291. enum IncDecButtonMode
  34292. {
  34293. incDecButtonsNotDraggable,
  34294. incDecButtonsDraggable_AutoDirection,
  34295. incDecButtonsDraggable_Horizontal,
  34296. incDecButtonsDraggable_Vertical
  34297. };
  34298. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  34299. can be dragged on the buttons to drag the values.
  34300. By default this is turned off. When enabled, clicking on the buttons still works
  34301. them as normal, but by holding down the mouse on a button and dragging it a little
  34302. distance, it flips into a mode where the value can be dragged. The drag direction can
  34303. either be set explicitly to be vertical or horizontal, or can be set to
  34304. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  34305. are side-by-side or above each other.
  34306. */
  34307. void setIncDecButtonsMode (IncDecButtonMode mode);
  34308. /** The position of the slider's text-entry box.
  34309. @see setTextBoxStyle
  34310. */
  34311. enum TextEntryBoxPosition
  34312. {
  34313. NoTextBox, /**< Doesn't display a text box. */
  34314. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  34315. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  34316. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  34317. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  34318. };
  34319. /** Changes the location and properties of the text-entry box.
  34320. @param newPosition where it should go (or NoTextBox to not have one at all)
  34321. @param isReadOnly if true, it's a read-only display
  34322. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  34323. room for the slider as well!
  34324. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  34325. room for the slider as well!
  34326. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  34327. */
  34328. void setTextBoxStyle (TextEntryBoxPosition newPosition,
  34329. bool isReadOnly,
  34330. int textEntryBoxWidth,
  34331. int textEntryBoxHeight);
  34332. /** Returns the status of the text-box.
  34333. @see setTextBoxStyle
  34334. */
  34335. const TextEntryBoxPosition getTextBoxPosition() const { return textBoxPos; }
  34336. /** Returns the width used for the text-box.
  34337. @see setTextBoxStyle
  34338. */
  34339. int getTextBoxWidth() const { return textBoxWidth; }
  34340. /** Returns the height used for the text-box.
  34341. @see setTextBoxStyle
  34342. */
  34343. int getTextBoxHeight() const { return textBoxHeight; }
  34344. /** Makes the text-box editable.
  34345. By default this is true, and the user can enter values into the textbox,
  34346. but it can be turned off if that's not suitable.
  34347. @see setTextBoxStyle, getValueFromText, getTextFromValue
  34348. */
  34349. void setTextBoxIsEditable (bool shouldBeEditable);
  34350. /** Returns true if the text-box is read-only.
  34351. @see setTextBoxStyle
  34352. */
  34353. bool isTextBoxEditable() const { return editableText; }
  34354. /** If the text-box is editable, this will give it the focus so that the user can
  34355. type directly into it.
  34356. This is basically the effect as the user clicking on it.
  34357. */
  34358. void showTextBox();
  34359. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  34360. focus away from it.
  34361. @param discardCurrentEditorContents if true, the slider's value will be left
  34362. unchanged; if false, the current contents of the
  34363. text editor will be used to set the slider position
  34364. before it is hidden.
  34365. */
  34366. void hideTextBox (bool discardCurrentEditorContents);
  34367. /** Changes the slider's current value.
  34368. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34369. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34370. want to handle it.
  34371. @param newValue the new value to set - this will be restricted by the
  34372. minimum and maximum range, and will be snapped to the
  34373. nearest interval if one has been set
  34374. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34375. any SliderListeners or the valueChanged() method
  34376. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34377. synchronously; if false, it will be asynchronous
  34378. */
  34379. void setValue (double newValue,
  34380. bool sendUpdateMessage = true,
  34381. bool sendMessageSynchronously = false);
  34382. /** Returns the slider's current value. */
  34383. double getValue() const;
  34384. /** Returns the Value object that represents the slider's current position.
  34385. You can use this Value object to connect the slider's position to external values or setters,
  34386. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34387. your own Value object.
  34388. @see Value, getMaxValue, getMinValueObject
  34389. */
  34390. Value& getValueObject() { return currentValue; }
  34391. /** Sets the limits that the slider's value can take.
  34392. @param newMinimum the lowest value allowed
  34393. @param newMaximum the highest value allowed
  34394. @param newInterval the steps in which the value is allowed to increase - if this
  34395. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  34396. */
  34397. void setRange (double newMinimum,
  34398. double newMaximum,
  34399. double newInterval = 0);
  34400. /** Returns the current maximum value.
  34401. @see setRange
  34402. */
  34403. double getMaximum() const { return maximum; }
  34404. /** Returns the current minimum value.
  34405. @see setRange
  34406. */
  34407. double getMinimum() const { return minimum; }
  34408. /** Returns the current step-size for values.
  34409. @see setRange
  34410. */
  34411. double getInterval() const { return interval; }
  34412. /** For a slider with two or three thumbs, this returns the lower of its values.
  34413. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34414. A slider with three values also uses the normal getValue() and setValue() methods to
  34415. control the middle value.
  34416. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34417. */
  34418. double getMinValue() const;
  34419. /** For a slider with two or three thumbs, this returns the lower of its values.
  34420. You can use this Value object to connect the slider's position to external values or setters,
  34421. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34422. your own Value object.
  34423. @see Value, getMinValue, getMaxValueObject
  34424. */
  34425. Value& getMinValueObject() { return valueMin; }
  34426. /** For a slider with two or three thumbs, this sets the lower of its values.
  34427. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34428. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34429. want to handle it.
  34430. @param newValue the new value to set - this will be restricted by the
  34431. minimum and maximum range, and will be snapped to the nearest
  34432. interval if one has been set.
  34433. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34434. any SliderListeners or the valueChanged() method
  34435. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34436. synchronously; if false, it will be asynchronous
  34437. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  34438. max value (in a two-value slider) or the mid value (in a three-value
  34439. slider). If false, then if this value goes beyond those values,
  34440. it will push them along with it.
  34441. @see getMinValue, setMaxValue, setValue
  34442. */
  34443. void setMinValue (double newValue,
  34444. bool sendUpdateMessage = true,
  34445. bool sendMessageSynchronously = false,
  34446. bool allowNudgingOfOtherValues = false);
  34447. /** For a slider with two or three thumbs, this returns the higher of its values.
  34448. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34449. A slider with three values also uses the normal getValue() and setValue() methods to
  34450. control the middle value.
  34451. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34452. */
  34453. double getMaxValue() const;
  34454. /** For a slider with two or three thumbs, this returns the higher of its values.
  34455. You can use this Value object to connect the slider's position to external values or setters,
  34456. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34457. your own Value object.
  34458. @see Value, getMaxValue, getMinValueObject
  34459. */
  34460. Value& getMaxValueObject() { return valueMax; }
  34461. /** For a slider with two or three thumbs, this sets the lower of its values.
  34462. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34463. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34464. want to handle it.
  34465. @param newValue the new value to set - this will be restricted by the
  34466. minimum and maximum range, and will be snapped to the nearest
  34467. interval if one has been set.
  34468. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34469. any SliderListeners or the valueChanged() method
  34470. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34471. synchronously; if false, it will be asynchronous
  34472. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  34473. min value (in a two-value slider) or the mid value (in a three-value
  34474. slider). If false, then if this value goes beyond those values,
  34475. it will push them along with it.
  34476. @see getMaxValue, setMinValue, setValue
  34477. */
  34478. void setMaxValue (double newValue,
  34479. bool sendUpdateMessage = true,
  34480. bool sendMessageSynchronously = false,
  34481. bool allowNudgingOfOtherValues = false);
  34482. /** Adds a listener to be called when this slider's value changes. */
  34483. void addListener (SliderListener* listener);
  34484. /** Removes a previously-registered listener. */
  34485. void removeListener (SliderListener* listener);
  34486. /** This lets you choose whether double-clicking moves the slider to a given position.
  34487. By default this is turned off, but it's handy if you want a double-click to act
  34488. as a quick way of resetting a slider. Just pass in the value you want it to
  34489. go to when double-clicked.
  34490. @see getDoubleClickReturnValue
  34491. */
  34492. void setDoubleClickReturnValue (bool isDoubleClickEnabled,
  34493. double valueToSetOnDoubleClick);
  34494. /** Returns the values last set by setDoubleClickReturnValue() method.
  34495. Sets isEnabled to true if double-click is enabled, and returns the value
  34496. that was set.
  34497. @see setDoubleClickReturnValue
  34498. */
  34499. double getDoubleClickReturnValue (bool& isEnabled) const;
  34500. /** Tells the slider whether to keep sending change messages while the user
  34501. is dragging the slider.
  34502. If set to true, a change message will only be sent when the user has
  34503. dragged the slider and let go. If set to false (the default), then messages
  34504. will be continuously sent as they drag it while the mouse button is still
  34505. held down.
  34506. */
  34507. void setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease);
  34508. /** This lets you change whether the slider thumb jumps to the mouse position
  34509. when you click.
  34510. By default, this is true. If it's false, then the slider moves with relative
  34511. motion when you drag it.
  34512. This only applies to linear bars, and won't affect two- or three- value
  34513. sliders.
  34514. */
  34515. void setSliderSnapsToMousePosition (bool shouldSnapToMouse);
  34516. /** If enabled, this gives the slider a pop-up bubble which appears while the
  34517. slider is being dragged.
  34518. This can be handy if your slider doesn't have a text-box, so that users can
  34519. see the value just when they're changing it.
  34520. If you pass a component as the parentComponentToUse parameter, the pop-up
  34521. bubble will be added as a child of that component when it's needed. If you
  34522. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  34523. transparent window, so if you're using an OS that can't do transparent windows
  34524. you'll have to add it to a parent component instead).
  34525. */
  34526. void setPopupDisplayEnabled (bool isEnabled,
  34527. Component* parentComponentToUse);
  34528. /** If this is set to true, then right-clicking on the slider will pop-up
  34529. a menu to let the user change the way it works.
  34530. By default this is turned off, but when turned on, the menu will include
  34531. things like velocity sensitivity, and for rotary sliders, whether they
  34532. use a linear or rotary mouse-drag to move them.
  34533. */
  34534. void setPopupMenuEnabled (bool menuEnabled);
  34535. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  34536. By default it's enabled.
  34537. */
  34538. void setScrollWheelEnabled (bool enabled);
  34539. /** Returns a number to indicate which thumb is currently being dragged by the
  34540. mouse.
  34541. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  34542. the maximum-value thumb, or -1 if none is currently down.
  34543. */
  34544. int getThumbBeingDragged() const { return sliderBeingDragged; }
  34545. /** Callback to indicate that the user is about to start dragging the slider.
  34546. @see SliderListener::sliderDragStarted
  34547. */
  34548. virtual void startedDragging();
  34549. /** Callback to indicate that the user has just stopped dragging the slider.
  34550. @see SliderListener::sliderDragEnded
  34551. */
  34552. virtual void stoppedDragging();
  34553. /** Callback to indicate that the user has just moved the slider.
  34554. @see SliderListener::sliderValueChanged
  34555. */
  34556. virtual void valueChanged();
  34557. /** Subclasses can override this to convert a text string to a value.
  34558. When the user enters something into the text-entry box, this method is
  34559. called to convert it to a value.
  34560. The default routine just tries to convert it to a double.
  34561. @see getTextFromValue
  34562. */
  34563. virtual double getValueFromText (const String& text);
  34564. /** Turns the slider's current value into a text string.
  34565. Subclasses can override this to customise the formatting of the text-entry box.
  34566. The default implementation just turns the value into a string, using
  34567. a number of decimal places based on the range interval. If a suffix string
  34568. has been set using setTextValueSuffix(), this will be appended to the text.
  34569. @see getValueFromText
  34570. */
  34571. virtual const String getTextFromValue (double value);
  34572. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  34573. a string.
  34574. This is used by the default implementation of getTextFromValue(), and is just
  34575. appended to the numeric value. For more advanced formatting, you can override
  34576. getTextFromValue() and do something else.
  34577. */
  34578. void setTextValueSuffix (const String& suffix);
  34579. /** Returns the suffix that was set by setTextValueSuffix(). */
  34580. const String getTextValueSuffix() const;
  34581. /** Allows a user-defined mapping of distance along the slider to its value.
  34582. The default implementation for this performs the skewing operation that
  34583. can be set up in the setSkewFactor() method. Override it if you need
  34584. some kind of custom mapping instead, but make sure you also implement the
  34585. inverse function in valueToProportionOfLength().
  34586. @param proportion a value 0 to 1.0, indicating a distance along the slider
  34587. @returns the slider value that is represented by this position
  34588. @see valueToProportionOfLength
  34589. */
  34590. virtual double proportionOfLengthToValue (double proportion);
  34591. /** Allows a user-defined mapping of value to the position of the slider along its length.
  34592. The default implementation for this performs the skewing operation that
  34593. can be set up in the setSkewFactor() method. Override it if you need
  34594. some kind of custom mapping instead, but make sure you also implement the
  34595. inverse function in proportionOfLengthToValue().
  34596. @param value a valid slider value, between the range of values specified in
  34597. setRange()
  34598. @returns a value 0 to 1.0 indicating the distance along the slider that
  34599. represents this value
  34600. @see proportionOfLengthToValue
  34601. */
  34602. virtual double valueToProportionOfLength (double value);
  34603. /** Returns the X or Y coordinate of a value along the slider's length.
  34604. If the slider is horizontal, this will be the X coordinate of the given
  34605. value, relative to the left of the slider. If it's vertical, then this will
  34606. be the Y coordinate, relative to the top of the slider.
  34607. If the slider is rotary, this will throw an assertion and return 0. If the
  34608. value is out-of-range, it will be constrained to the length of the slider.
  34609. */
  34610. float getPositionOfValue (double value);
  34611. /** This can be overridden to allow the slider to snap to user-definable values.
  34612. If overridden, it will be called when the user tries to move the slider to
  34613. a given position, and allows a subclass to sanity-check this value, possibly
  34614. returning a different value to use instead.
  34615. @param attemptedValue the value the user is trying to enter
  34616. @param userIsDragging true if the user is dragging with the mouse; false if
  34617. they are entering the value using the text box
  34618. @returns the value to use instead
  34619. */
  34620. virtual double snapValue (double attemptedValue, bool userIsDragging);
  34621. /** This can be called to force the text box to update its contents.
  34622. (Not normally needed, as this is done automatically).
  34623. */
  34624. void updateText();
  34625. /** True if the slider moves horizontally. */
  34626. bool isHorizontal() const;
  34627. /** True if the slider moves vertically. */
  34628. bool isVertical() const;
  34629. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  34630. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34631. methods.
  34632. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34633. */
  34634. enum ColourIds
  34635. {
  34636. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  34637. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  34638. and feel class how this is used. */
  34639. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  34640. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  34641. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  34642. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  34643. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  34644. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  34645. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  34646. };
  34647. juce_UseDebuggingNewOperator
  34648. protected:
  34649. /** @internal */
  34650. void labelTextChanged (Label*);
  34651. /** @internal */
  34652. void paint (Graphics& g);
  34653. /** @internal */
  34654. void resized();
  34655. /** @internal */
  34656. void mouseDown (const MouseEvent& e);
  34657. /** @internal */
  34658. void mouseUp (const MouseEvent& e);
  34659. /** @internal */
  34660. void mouseDrag (const MouseEvent& e);
  34661. /** @internal */
  34662. void mouseDoubleClick (const MouseEvent& e);
  34663. /** @internal */
  34664. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34665. /** @internal */
  34666. void modifierKeysChanged (const ModifierKeys& modifiers);
  34667. /** @internal */
  34668. void buttonClicked (Button* button);
  34669. /** @internal */
  34670. void lookAndFeelChanged();
  34671. /** @internal */
  34672. void enablementChanged();
  34673. /** @internal */
  34674. void focusOfChildComponentChanged (FocusChangeType cause);
  34675. /** @internal */
  34676. void handleAsyncUpdate();
  34677. /** @internal */
  34678. void colourChanged();
  34679. /** @internal */
  34680. void valueChanged (Value& value);
  34681. /** Returns the best number of decimal places to use when displaying numbers.
  34682. This is calculated from the slider's interval setting.
  34683. */
  34684. int getNumDecimalPlacesToDisplay() const throw() { return numDecimalPlaces; }
  34685. private:
  34686. ListenerList <SliderListener> listeners;
  34687. Value currentValue, valueMin, valueMax;
  34688. double lastCurrentValue, lastValueMin, lastValueMax;
  34689. double minimum, maximum, interval, doubleClickReturnValue;
  34690. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  34691. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  34692. int velocityModeThreshold;
  34693. float rotaryStart, rotaryEnd;
  34694. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  34695. int mouseDragStartX, mouseDragStartY;
  34696. int sliderRegionStart, sliderRegionSize;
  34697. int sliderBeingDragged;
  34698. int pixelsForFullDragExtent;
  34699. Rectangle<int> sliderRect;
  34700. String textSuffix;
  34701. SliderStyle style;
  34702. TextEntryBoxPosition textBoxPos;
  34703. int textBoxWidth, textBoxHeight;
  34704. IncDecButtonMode incDecButtonMode;
  34705. bool editableText : 1, doubleClickToValue : 1;
  34706. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  34707. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  34708. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  34709. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  34710. Label* valueBox;
  34711. Button* incButton;
  34712. Button* decButton;
  34713. ScopedPointer <Component> popupDisplay;
  34714. Component* parentForPopupDisplay;
  34715. float getLinearSliderPos (double value);
  34716. void restoreMouseIfHidden();
  34717. void sendDragStart();
  34718. void sendDragEnd();
  34719. double constrainedValue (double value) const;
  34720. void triggerChangeMessage (bool synchronous);
  34721. bool incDecDragDirectionIsHorizontal() const;
  34722. Slider (const Slider&);
  34723. Slider& operator= (const Slider&);
  34724. };
  34725. #endif // __JUCE_SLIDER_JUCEHEADER__
  34726. /*** End of inlined file: juce_Slider.h ***/
  34727. #endif
  34728. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  34729. #endif
  34730. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34731. /*** Start of inlined file: juce_TableHeaderComponent.h ***/
  34732. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34733. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34734. class TableHeaderComponent;
  34735. /**
  34736. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  34737. You can register one of these objects for table events using TableHeaderComponent::addListener()
  34738. and TableHeaderComponent::removeListener().
  34739. @see TableHeaderComponent
  34740. */
  34741. class JUCE_API TableHeaderListener
  34742. {
  34743. public:
  34744. TableHeaderListener() {}
  34745. /** Destructor. */
  34746. virtual ~TableHeaderListener() {}
  34747. /** This is called when some of the table's columns are added, removed, hidden,
  34748. or rearranged.
  34749. */
  34750. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  34751. /** This is called when one or more of the table's columns are resized.
  34752. */
  34753. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  34754. /** This is called when the column by which the table should be sorted is changed.
  34755. */
  34756. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  34757. /** This is called when the user begins or ends dragging one of the columns around.
  34758. When the user starts dragging a column, this is called with the ID of that
  34759. column. When they finish dragging, it is called again with 0 as the ID.
  34760. */
  34761. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  34762. int columnIdNowBeingDragged);
  34763. };
  34764. /**
  34765. A component that displays a strip of column headings for a table, and allows these
  34766. to be resized, dragged around, etc.
  34767. This is just the component that goes at the top of a table. You can use it
  34768. directly for custom components, or to create a simple table, use the
  34769. TableListBox class.
  34770. To use one of these, create it and use addColumn() to add all the columns that you need.
  34771. Each column must be given a unique ID number that's used to refer to it.
  34772. @see TableListBox, TableHeaderListener
  34773. */
  34774. class JUCE_API TableHeaderComponent : public Component,
  34775. private AsyncUpdater
  34776. {
  34777. public:
  34778. /** Creates an empty table header.
  34779. */
  34780. TableHeaderComponent();
  34781. /** Destructor. */
  34782. ~TableHeaderComponent();
  34783. /** A combination of these flags are passed into the addColumn() method to specify
  34784. the properties of a column.
  34785. */
  34786. enum ColumnPropertyFlags
  34787. {
  34788. 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. */
  34789. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  34790. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  34791. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  34792. 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. */
  34793. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  34794. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  34795. /** This set of default flags is used as the default parameter value in addColumn(). */
  34796. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  34797. /** A quick way of combining flags for a column that's not resizable. */
  34798. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  34799. /** A quick way of combining flags for a column that's not resizable or sortable. */
  34800. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  34801. /** A quick way of combining flags for a column that's not sortable. */
  34802. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  34803. };
  34804. /** Adds a column to the table.
  34805. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  34806. registered listeners.
  34807. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  34808. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  34809. a unique ID. This is used to identify the column later on, after the user may have
  34810. changed the order that they appear in
  34811. @param width the initial width of the column, in pixels
  34812. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  34813. if the 'resizable' flag is specified for this column
  34814. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  34815. if the 'resizable' flag is specified for this column
  34816. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  34817. properties of this column
  34818. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  34819. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  34820. all columns, not just the index amongst those that are currently visible
  34821. */
  34822. void addColumn (const String& columnName,
  34823. int columnId,
  34824. int width,
  34825. int minimumWidth = 30,
  34826. int maximumWidth = -1,
  34827. int propertyFlags = defaultFlags,
  34828. int insertIndex = -1);
  34829. /** Removes a column with the given ID.
  34830. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  34831. registered listeners.
  34832. */
  34833. void removeColumn (int columnIdToRemove);
  34834. /** Deletes all columns from the table.
  34835. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  34836. registered listeners.
  34837. */
  34838. void removeAllColumns();
  34839. /** Returns the number of columns in the table.
  34840. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  34841. return the total number of columns, including hidden ones.
  34842. @see isColumnVisible
  34843. */
  34844. int getNumColumns (bool onlyCountVisibleColumns) const;
  34845. /** Returns the name for a column.
  34846. @see setColumnName
  34847. */
  34848. const String getColumnName (int columnId) const;
  34849. /** Changes the name of a column. */
  34850. void setColumnName (int columnId, const String& newName);
  34851. /** Moves a column to a different index in the table.
  34852. @param columnId the column to move
  34853. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  34854. */
  34855. void moveColumn (int columnId, int newVisibleIndex);
  34856. /** Returns the width of one of the columns.
  34857. */
  34858. int getColumnWidth (int columnId) const;
  34859. /** Changes the width of a column.
  34860. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  34861. */
  34862. void setColumnWidth (int columnId, int newWidth);
  34863. /** Shows or hides a column.
  34864. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  34865. @see isColumnVisible
  34866. */
  34867. void setColumnVisible (int columnId, bool shouldBeVisible);
  34868. /** Returns true if this column is currently visible.
  34869. @see setColumnVisible
  34870. */
  34871. bool isColumnVisible (int columnId) const;
  34872. /** Changes the column which is the sort column.
  34873. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  34874. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  34875. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  34876. @see getSortColumnId, isSortedForwards, reSortTable
  34877. */
  34878. void setSortColumnId (int columnId, bool sortForwards);
  34879. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  34880. @see setSortColumnId, isSortedForwards
  34881. */
  34882. int getSortColumnId() const;
  34883. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  34884. @see setSortColumnId
  34885. */
  34886. bool isSortedForwards() const;
  34887. /** Triggers a re-sort of the table according to the current sort-column.
  34888. If you modifiy the table's contents, you can call this to signal that the table needs
  34889. to be re-sorted.
  34890. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  34891. tableSortOrderChanged() method of any listeners).
  34892. */
  34893. void reSortTable();
  34894. /** Returns the total width of all the visible columns in the table.
  34895. */
  34896. int getTotalWidth() const;
  34897. /** Returns the index of a given column.
  34898. If there's no such column ID, this will return -1.
  34899. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  34900. otherwise it'll return the index amongst all the columns, including any hidden ones.
  34901. */
  34902. int getIndexOfColumnId (int columnId, bool onlyCountVisibleColumns) const;
  34903. /** Returns the ID of the column at a given index.
  34904. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  34905. otherwise it'll count it amongst all the columns, including any hidden ones.
  34906. If the index is out-of-range, it'll return 0.
  34907. */
  34908. int getColumnIdOfIndex (int index, bool onlyCountVisibleColumns) const;
  34909. /** Returns the rectangle containing of one of the columns.
  34910. The index is an index from 0 to the number of columns that are currently visible (hidden
  34911. ones are not counted). It returns a rectangle showing the position of the column relative
  34912. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  34913. */
  34914. const Rectangle<int> getColumnPosition (int index) const;
  34915. /** Finds the column ID at a given x-position in the component.
  34916. If there is a column at this point this returns its ID, or if not, it will return 0.
  34917. */
  34918. int getColumnIdAtX (int xToFind) const;
  34919. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  34920. entire width of the component.
  34921. By default this is disabled. Turning it on also means that when resizing a column, those
  34922. on the right will be squashed to fit.
  34923. */
  34924. void setStretchToFitActive (bool shouldStretchToFit);
  34925. /** Returns true if stretch-to-fit has been enabled.
  34926. @see setStretchToFitActive
  34927. */
  34928. bool isStretchToFitActive() const;
  34929. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  34930. specified width, keeping their relative proportions the same.
  34931. If the minimum widths of the columns are too wide to fit into this space, it may
  34932. actually end up wider.
  34933. */
  34934. void resizeAllColumnsToFit (int targetTotalWidth);
  34935. /** Enables or disables the pop-up menu.
  34936. The default menu allows the user to show or hide columns. You can add custom
  34937. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  34938. By default the menu is enabled.
  34939. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  34940. */
  34941. void setPopupMenuActive (bool hasMenu);
  34942. /** Returns true if the pop-up menu is enabled.
  34943. @see setPopupMenuActive
  34944. */
  34945. bool isPopupMenuActive() const;
  34946. /** Returns a string that encapsulates the table's current layout.
  34947. This can be restored later using restoreFromString(). It saves the order of
  34948. the columns, the currently-sorted column, and the widths.
  34949. @see restoreFromString
  34950. */
  34951. const String toString() const;
  34952. /** Restores the state of the table, based on a string previously created with
  34953. toString().
  34954. @see toString
  34955. */
  34956. void restoreFromString (const String& storedVersion);
  34957. /** Adds a listener to be informed about things that happen to the header. */
  34958. void addListener (TableHeaderListener* newListener);
  34959. /** Removes a previously-registered listener. */
  34960. void removeListener (TableHeaderListener* listenerToRemove);
  34961. /** This can be overridden to handle a mouse-click on one of the column headers.
  34962. The default implementation will use this click to call getSortColumnId() and
  34963. change the sort order.
  34964. */
  34965. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  34966. /** This can be overridden to add custom items to the pop-up menu.
  34967. If you override this, you should call the superclass's method to add its
  34968. column show/hide items, if you want them on the menu as well.
  34969. Then to handle the result, override reactToMenuItem().
  34970. @see reactToMenuItem
  34971. */
  34972. virtual void addMenuItems (PopupMenu& menu, int columnIdClicked);
  34973. /** Override this to handle any custom items that you have added to the
  34974. pop-up menu with an addMenuItems() override.
  34975. If the menuReturnId isn't one of your own custom menu items, you'll need to
  34976. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  34977. handle the items that it had added.
  34978. @see addMenuItems
  34979. */
  34980. virtual void reactToMenuItem (int menuReturnId, int columnIdClicked);
  34981. /** @internal */
  34982. void paint (Graphics& g);
  34983. /** @internal */
  34984. void resized();
  34985. /** @internal */
  34986. void mouseMove (const MouseEvent&);
  34987. /** @internal */
  34988. void mouseEnter (const MouseEvent&);
  34989. /** @internal */
  34990. void mouseExit (const MouseEvent&);
  34991. /** @internal */
  34992. void mouseDown (const MouseEvent&);
  34993. /** @internal */
  34994. void mouseDrag (const MouseEvent&);
  34995. /** @internal */
  34996. void mouseUp (const MouseEvent&);
  34997. /** @internal */
  34998. const MouseCursor getMouseCursor();
  34999. /** Can be overridden for more control over the pop-up menu behaviour. */
  35000. virtual void showColumnChooserMenu (int columnIdClicked);
  35001. juce_UseDebuggingNewOperator
  35002. private:
  35003. struct ColumnInfo
  35004. {
  35005. String name;
  35006. int id, propertyFlags, width, minimumWidth, maximumWidth;
  35007. double lastDeliberateWidth;
  35008. bool isVisible() const;
  35009. };
  35010. OwnedArray <ColumnInfo> columns;
  35011. Array <TableHeaderListener*> listeners;
  35012. ScopedPointer <Component> dragOverlayComp;
  35013. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  35014. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  35015. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  35016. ColumnInfo* getInfoForId (int columnId) const;
  35017. int visibleIndexToTotalIndex (int visibleIndex) const;
  35018. void sendColumnsChanged();
  35019. void handleAsyncUpdate();
  35020. void beginDrag (const MouseEvent&);
  35021. void endDrag (int finalIndex);
  35022. int getResizeDraggerAt (int mouseX) const;
  35023. void updateColumnUnderMouse (int x, int y);
  35024. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  35025. TableHeaderComponent (const TableHeaderComponent&);
  35026. TableHeaderComponent operator= (const TableHeaderComponent&);
  35027. };
  35028. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35029. /*** End of inlined file: juce_TableHeaderComponent.h ***/
  35030. #endif
  35031. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  35032. /*** Start of inlined file: juce_TableListBox.h ***/
  35033. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  35034. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  35035. /**
  35036. One of these is used by a TableListBox as the data model for the table's contents.
  35037. The virtual methods that you override in this class take care of drawing the
  35038. table cells, and reacting to events.
  35039. @see TableListBox
  35040. */
  35041. class JUCE_API TableListBoxModel
  35042. {
  35043. public:
  35044. TableListBoxModel() {}
  35045. /** Destructor. */
  35046. virtual ~TableListBoxModel() {}
  35047. /** This must return the number of rows currently in the table.
  35048. If the number of rows changes, you must call TableListBox::updateContent() to
  35049. cause it to refresh the list.
  35050. */
  35051. virtual int getNumRows() = 0;
  35052. /** This must draw the background behind one of the rows in the table.
  35053. The graphics context has its origin at the row's top-left, and your method
  35054. should fill the area specified by the width and height parameters.
  35055. */
  35056. virtual void paintRowBackground (Graphics& g,
  35057. int rowNumber,
  35058. int width, int height,
  35059. bool rowIsSelected) = 0;
  35060. /** This must draw one of the cells.
  35061. The graphics context's origin will already be set to the top-left of the cell,
  35062. whose size is specified by (width, height).
  35063. */
  35064. virtual void paintCell (Graphics& g,
  35065. int rowNumber,
  35066. int columnId,
  35067. int width, int height,
  35068. bool rowIsSelected) = 0;
  35069. /** This is used to create or update a custom component to go in a cell.
  35070. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  35071. and handle mouse clicks with cellClicked().
  35072. This method will be called whenever a custom component might need to be updated - e.g.
  35073. when the table is changed, or TableListBox::updateContent() is called.
  35074. If you don't need a custom component for the specified cell, then return 0.
  35075. If you do want a custom component, and the existingComponentToUpdate is null, then
  35076. this method must create a new component suitable for the cell, and return it.
  35077. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  35078. by this method. In this case, the method must either update it to make sure it's correctly representing
  35079. the given cell (which may be different from the one that the component was created for), or it can
  35080. delete this component and return a new one.
  35081. */
  35082. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  35083. Component* existingComponentToUpdate);
  35084. /** This callback is made when the user clicks on one of the cells in the table.
  35085. The mouse event's coordinates will be relative to the entire table row.
  35086. @see cellDoubleClicked, backgroundClicked
  35087. */
  35088. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  35089. /** This callback is made when the user clicks on one of the cells in the table.
  35090. The mouse event's coordinates will be relative to the entire table row.
  35091. @see cellClicked, backgroundClicked
  35092. */
  35093. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  35094. /** This can be overridden to react to the user double-clicking on a part of the list where
  35095. there are no rows.
  35096. @see cellClicked
  35097. */
  35098. virtual void backgroundClicked();
  35099. /** This callback is made when the table's sort order is changed.
  35100. This could be because the user has clicked a column header, or because the
  35101. TableHeaderComponent::setSortColumnId() method was called.
  35102. If you implement this, your method should re-sort the table using the given
  35103. column as the key.
  35104. */
  35105. virtual void sortOrderChanged (int newSortColumnId, bool isForwards);
  35106. /** Returns the best width for one of the columns.
  35107. If you implement this method, you should measure the width of all the items
  35108. in this column, and return the best size.
  35109. Returning 0 means that the column shouldn't be changed.
  35110. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  35111. */
  35112. virtual int getColumnAutoSizeWidth (int columnId);
  35113. /** Returns a tooltip for a particular cell in the table.
  35114. */
  35115. virtual const String getCellTooltip (int rowNumber, int columnId);
  35116. /** Override this to be informed when rows are selected or deselected.
  35117. @see ListBox::selectedRowsChanged()
  35118. */
  35119. virtual void selectedRowsChanged (int lastRowSelected);
  35120. /** Override this to be informed when the delete key is pressed.
  35121. @see ListBox::deleteKeyPressed()
  35122. */
  35123. virtual void deleteKeyPressed (int lastRowSelected);
  35124. /** Override this to be informed when the return key is pressed.
  35125. @see ListBox::returnKeyPressed()
  35126. */
  35127. virtual void returnKeyPressed (int lastRowSelected);
  35128. /** Override this to be informed when the list is scrolled.
  35129. This might be caused by the user moving the scrollbar, or by programmatic changes
  35130. to the list position.
  35131. */
  35132. virtual void listWasScrolled();
  35133. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  35134. If this returns a non-empty name then when the user drags a row, the table will try to
  35135. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  35136. drag-and-drop operation, using this string as the source description, and the listbox
  35137. itself as the source component.
  35138. @see DragAndDropContainer::startDragging
  35139. */
  35140. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  35141. };
  35142. /**
  35143. A table of cells, using a TableHeaderComponent as its header.
  35144. This component makes it easy to create a table by providing a TableListBoxModel as
  35145. the data source.
  35146. @see TableListBoxModel, TableHeaderComponent
  35147. */
  35148. class JUCE_API TableListBox : public ListBox,
  35149. private ListBoxModel,
  35150. private TableHeaderListener
  35151. {
  35152. public:
  35153. /** Creates a TableListBox.
  35154. The model pointer passed-in can be null, in which case you can set it later
  35155. with setModel().
  35156. */
  35157. TableListBox (const String& componentName,
  35158. TableListBoxModel* model);
  35159. /** Destructor. */
  35160. ~TableListBox();
  35161. /** Changes the TableListBoxModel that is being used for this table.
  35162. */
  35163. void setModel (TableListBoxModel* newModel);
  35164. /** Returns the model currently in use. */
  35165. TableListBoxModel* getModel() const { return model; }
  35166. /** Returns the header component being used in this table. */
  35167. TableHeaderComponent* getHeader() const { return header; }
  35168. /** Changes the height of the table header component.
  35169. @see getHeaderHeight
  35170. */
  35171. void setHeaderHeight (int newHeight);
  35172. /** Returns the height of the table header.
  35173. @see setHeaderHeight
  35174. */
  35175. int getHeaderHeight() const;
  35176. /** Resizes a column to fit its contents.
  35177. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  35178. and applies that to the column.
  35179. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  35180. */
  35181. void autoSizeColumn (int columnId);
  35182. /** Calls autoSizeColumn() for all columns in the table. */
  35183. void autoSizeAllColumns();
  35184. /** Enables or disables the auto size options on the popup menu.
  35185. By default, these are enabled.
  35186. */
  35187. void setAutoSizeMenuOptionShown (bool shouldBeShown);
  35188. /** True if the auto-size options should be shown on the menu.
  35189. @see setAutoSizeMenuOptionsShown
  35190. */
  35191. bool isAutoSizeMenuOptionShown() const;
  35192. /** Returns the position of one of the cells in the table.
  35193. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  35194. the table component's top-left. The row number isn't checked to see if it's
  35195. in-range, but the column ID must exist or this will return an empty rectangle.
  35196. If relativeToComponentTopLeft is false, the co-ords are relative to the
  35197. top-left of the table's top-left cell.
  35198. */
  35199. const Rectangle<int> getCellPosition (int columnId,
  35200. int rowNumber,
  35201. bool relativeToComponentTopLeft) const;
  35202. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  35203. @see ListBox::scrollToEnsureRowIsOnscreen
  35204. */
  35205. void scrollToEnsureColumnIsOnscreen (int columnId);
  35206. /** @internal */
  35207. int getNumRows();
  35208. /** @internal */
  35209. void paintListBoxItem (int, Graphics&, int, int, bool);
  35210. /** @internal */
  35211. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  35212. /** @internal */
  35213. void selectedRowsChanged (int lastRowSelected);
  35214. /** @internal */
  35215. void deleteKeyPressed (int currentSelectedRow);
  35216. /** @internal */
  35217. void returnKeyPressed (int currentSelectedRow);
  35218. /** @internal */
  35219. void backgroundClicked();
  35220. /** @internal */
  35221. void listWasScrolled();
  35222. /** @internal */
  35223. void tableColumnsChanged (TableHeaderComponent*);
  35224. /** @internal */
  35225. void tableColumnsResized (TableHeaderComponent*);
  35226. /** @internal */
  35227. void tableSortOrderChanged (TableHeaderComponent*);
  35228. /** @internal */
  35229. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  35230. /** @internal */
  35231. void resized();
  35232. juce_UseDebuggingNewOperator
  35233. private:
  35234. TableHeaderComponent* header;
  35235. TableListBoxModel* model;
  35236. int columnIdNowBeingDragged;
  35237. bool autoSizeOptionsShown;
  35238. void updateColumnComponents() const;
  35239. TableListBox (const TableListBox&);
  35240. TableListBox& operator= (const TableListBox&);
  35241. };
  35242. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  35243. /*** End of inlined file: juce_TableListBox.h ***/
  35244. #endif
  35245. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  35246. #endif
  35247. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  35248. #endif
  35249. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  35250. #endif
  35251. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35252. /*** Start of inlined file: juce_ToolbarItemFactory.h ***/
  35253. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35254. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35255. /**
  35256. A factory object which can create ToolbarItemComponent objects.
  35257. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  35258. that it can create.
  35259. Each type of item is identified by a unique ID, and multiple instances of an
  35260. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  35261. bars).
  35262. @see Toolbar, ToolbarItemComponent, ToolbarButton
  35263. */
  35264. class JUCE_API ToolbarItemFactory
  35265. {
  35266. public:
  35267. ToolbarItemFactory();
  35268. /** Destructor. */
  35269. virtual ~ToolbarItemFactory();
  35270. /** A set of reserved item ID values, used for the built-in item types.
  35271. */
  35272. enum SpecialItemIds
  35273. {
  35274. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  35275. can be placed between sets of items to break them into groups. */
  35276. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  35277. items.*/
  35278. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  35279. either side of it, filling any available space. */
  35280. };
  35281. /** Must return a list of the IDs for all the item types that this factory can create.
  35282. The ids should be added to the array that is passed-in.
  35283. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  35284. and the predefined IDs in the SpecialItemIds enum.
  35285. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  35286. to this list if you want your toolbar to be able to contain those items.
  35287. The list returned here is used by the ToolbarItemPalette class to obtain its list
  35288. of available items, and their order on the palette will reflect the order in which
  35289. they appear on this list.
  35290. @see ToolbarItemPalette
  35291. */
  35292. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  35293. /** Must return the set of items that should be added to a toolbar as its default set.
  35294. This method is used by Toolbar::addDefaultItems() to determine which items to
  35295. create.
  35296. The items that your method adds to the array that is passed-in will be added to the
  35297. toolbar in the same order. Items can appear in the list more than once.
  35298. */
  35299. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  35300. /** Must create an instance of one of the items that the factory lists in its
  35301. getAllToolbarItemIds() method.
  35302. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  35303. method, except for the built-in item types from the SpecialItemIds enum, which
  35304. are created internally by the toolbar code.
  35305. Try not to keep a pointer to the object that is returned, as it will be deleted
  35306. automatically by the toolbar, and remember that multiple instances of the same
  35307. item type are likely to exist at the same time.
  35308. */
  35309. virtual ToolbarItemComponent* createItem (int itemId) = 0;
  35310. };
  35311. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35312. /*** End of inlined file: juce_ToolbarItemFactory.h ***/
  35313. #endif
  35314. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35315. /*** Start of inlined file: juce_ToolbarItemPalette.h ***/
  35316. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35317. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35318. /**
  35319. A component containing a list of toolbar items, which the user can drag onto
  35320. a toolbar to add them.
  35321. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  35322. which automatically shows one of these in a dialog box with lots of extra controls.
  35323. @see Toolbar
  35324. */
  35325. class JUCE_API ToolbarItemPalette : public Component,
  35326. public DragAndDropContainer
  35327. {
  35328. public:
  35329. /** Creates a palette of items for a given factory, with the aim of adding them
  35330. to the specified toolbar.
  35331. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  35332. set of items that are shown in this palette.
  35333. The toolbar and factory must not be deleted while this object exists.
  35334. */
  35335. ToolbarItemPalette (ToolbarItemFactory& factory,
  35336. Toolbar* toolbar);
  35337. /** Destructor. */
  35338. ~ToolbarItemPalette();
  35339. /** @internal */
  35340. void resized();
  35341. juce_UseDebuggingNewOperator
  35342. private:
  35343. ToolbarItemFactory& factory;
  35344. Toolbar* toolbar;
  35345. Viewport* viewport;
  35346. friend class Toolbar;
  35347. void replaceComponent (ToolbarItemComponent* comp);
  35348. ToolbarItemPalette (const ToolbarItemPalette&);
  35349. ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  35350. };
  35351. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35352. /*** End of inlined file: juce_ToolbarItemPalette.h ***/
  35353. #endif
  35354. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  35355. /*** Start of inlined file: juce_TreeView.h ***/
  35356. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  35357. #define __JUCE_TREEVIEW_JUCEHEADER__
  35358. /*** Start of inlined file: juce_FileDragAndDropTarget.h ***/
  35359. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  35360. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  35361. /**
  35362. Components derived from this class can have files dropped onto them by an external application.
  35363. @see DragAndDropContainer
  35364. */
  35365. class JUCE_API FileDragAndDropTarget
  35366. {
  35367. public:
  35368. /** Destructor. */
  35369. virtual ~FileDragAndDropTarget() {}
  35370. /** Callback to check whether this target is interested in the set of files being offered.
  35371. Note that this will be called repeatedly when the user is dragging the mouse around over your
  35372. component, so don't do anything time-consuming in here, like opening the files to have a look
  35373. inside them!
  35374. @param files the set of (absolute) pathnames of the files that the user is dragging
  35375. @returns true if this component wants to receive the other callbacks regarging this
  35376. type of object; if it returns false, no other callbacks will be made.
  35377. */
  35378. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  35379. /** Callback to indicate that some files are being dragged over this component.
  35380. This gets called when the user moves the mouse into this component while dragging.
  35381. Use this callback as a trigger to make your component repaint itself to give the
  35382. user feedback about whether the files can be dropped here or not.
  35383. @param files the set of (absolute) pathnames of the files that the user is dragging
  35384. @param x the mouse x position, relative to this component
  35385. @param y the mouse y position, relative to this component
  35386. */
  35387. virtual void fileDragEnter (const StringArray& files, int x, int y);
  35388. /** Callback to indicate that the user is dragging some files over this component.
  35389. This gets called when the user moves the mouse over this component while dragging.
  35390. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  35391. this lets you know what happens in-between.
  35392. @param files the set of (absolute) pathnames of the files that the user is dragging
  35393. @param x the mouse x position, relative to this component
  35394. @param y the mouse y position, relative to this component
  35395. */
  35396. virtual void fileDragMove (const StringArray& files, int x, int y);
  35397. /** Callback to indicate that the mouse has moved away from this component.
  35398. This gets called when the user moves the mouse out of this component while dragging
  35399. the files.
  35400. If you've used fileDragEnter() to repaint your component and give feedback, use this
  35401. as a signal to repaint it in its normal state.
  35402. @param files the set of (absolute) pathnames of the files that the user is dragging
  35403. */
  35404. virtual void fileDragExit (const StringArray& files);
  35405. /** Callback to indicate that the user has dropped the files onto this component.
  35406. When the user drops the files, this get called, and you can use the files in whatever
  35407. way is appropriate.
  35408. Note that after this is called, the fileDragExit method may not be called, so you should
  35409. clean up in here if there's anything you need to do when the drag finishes.
  35410. @param files the set of (absolute) pathnames of the files that the user is dragging
  35411. @param x the mouse x position, relative to this component
  35412. @param y the mouse y position, relative to this component
  35413. */
  35414. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  35415. };
  35416. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  35417. /*** End of inlined file: juce_FileDragAndDropTarget.h ***/
  35418. class TreeView;
  35419. /**
  35420. An item in a treeview.
  35421. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  35422. own sub-items.
  35423. To implement an item that contains sub-items, override the itemOpennessChanged()
  35424. method so that when it is opened, it adds the new sub-items to itself using the
  35425. addSubItem method. Depending on the nature of the item it might choose to only
  35426. do this the first time it's opened, or it might want to refresh itself each time.
  35427. It also has the option of deleting its sub-items when it is closed, or leaving them
  35428. in place.
  35429. */
  35430. class JUCE_API TreeViewItem
  35431. {
  35432. public:
  35433. /** Constructor. */
  35434. TreeViewItem();
  35435. /** Destructor. */
  35436. virtual ~TreeViewItem();
  35437. /** Returns the number of sub-items that have been added to this item.
  35438. Note that this doesn't mean much if the node isn't open.
  35439. @see getSubItem, mightContainSubItems, addSubItem
  35440. */
  35441. int getNumSubItems() const throw();
  35442. /** Returns one of the item's sub-items.
  35443. Remember that the object returned might get deleted at any time when its parent
  35444. item is closed or refreshed, depending on the nature of the items you're using.
  35445. @see getNumSubItems
  35446. */
  35447. TreeViewItem* getSubItem (int index) const throw();
  35448. /** Removes any sub-items. */
  35449. void clearSubItems();
  35450. /** Adds a sub-item.
  35451. @param newItem the object to add to the item's sub-item list. Once added, these can be
  35452. found using getSubItem(). When the items are later removed with
  35453. removeSubItem() (or when this item is deleted), they will be deleted.
  35454. @param insertPosition the index which the new item should have when it's added. If this
  35455. value is less than 0, the item will be added to the end of the list.
  35456. */
  35457. void addSubItem (TreeViewItem* newItem, int insertPosition = -1);
  35458. /** Removes one of the sub-items.
  35459. @param index the item to remove
  35460. @param deleteItem if true, the item that is removed will also be deleted.
  35461. */
  35462. void removeSubItem (int index, bool deleteItem = true);
  35463. /** Returns the TreeView to which this item belongs. */
  35464. TreeView* getOwnerView() const throw() { return ownerView; }
  35465. /** Returns the item within which this item is contained. */
  35466. TreeViewItem* getParentItem() const throw() { return parentItem; }
  35467. /** True if this item is currently open in the treeview. */
  35468. bool isOpen() const throw();
  35469. /** Opens or closes the item.
  35470. When opened or closed, the item's itemOpennessChanged() method will be called,
  35471. and a subclass should use this callback to create and add any sub-items that
  35472. it needs to.
  35473. @see itemOpennessChanged, mightContainSubItems
  35474. */
  35475. void setOpen (bool shouldBeOpen);
  35476. /** True if this item is currently selected.
  35477. Use this when painting the node, to decide whether to draw it as selected or not.
  35478. */
  35479. bool isSelected() const throw();
  35480. /** Selects or deselects the item.
  35481. This will cause a callback to itemSelectionChanged()
  35482. */
  35483. void setSelected (bool shouldBeSelected,
  35484. bool deselectOtherItemsFirst);
  35485. /** Returns the rectangle that this item occupies.
  35486. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  35487. top-left of the TreeView comp, so this will depend on the scroll-position of
  35488. the tree. If false, it is relative to the top-left of the topmost item in the
  35489. tree (so this would be unaffected by scrolling the view).
  35490. */
  35491. const Rectangle<int> getItemPosition (bool relativeToTreeViewTopLeft) const throw();
  35492. /** Sends a signal to the treeview to make it refresh itself.
  35493. Call this if your items have changed and you want the tree to update to reflect
  35494. this.
  35495. */
  35496. void treeHasChanged() const throw();
  35497. /** Sends a repaint message to redraw just this item.
  35498. Note that you should only call this if you want to repaint a superficial change. If
  35499. you're altering the tree's nodes, you should instead call treeHasChanged().
  35500. */
  35501. void repaintItem() const;
  35502. /** Returns the row number of this item in the tree.
  35503. The row number of an item will change according to which items are open.
  35504. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  35505. */
  35506. int getRowNumberInTree() const throw();
  35507. /** Returns true if all the item's parent nodes are open.
  35508. This is useful to check whether the item might actually be visible or not.
  35509. */
  35510. bool areAllParentsOpen() const throw();
  35511. /** Changes whether lines are drawn to connect any sub-items to this item.
  35512. By default, line-drawing is turned on.
  35513. */
  35514. void setLinesDrawnForSubItems (bool shouldDrawLines) throw();
  35515. /** Tells the tree whether this item can potentially be opened.
  35516. If your item could contain sub-items, this should return true; if it returns
  35517. false then the tree will not try to open the item. This determines whether or
  35518. not the item will be drawn with a 'plus' button next to it.
  35519. */
  35520. virtual bool mightContainSubItems() = 0;
  35521. /** Returns a string to uniquely identify this item.
  35522. If you're planning on using the TreeView::getOpennessState() method, then
  35523. these strings will be used to identify which nodes are open. The string
  35524. should be unique amongst the item's sibling items, but it's ok for there
  35525. to be duplicates at other levels of the tree.
  35526. If you're not going to store the state, then it's ok not to bother implementing
  35527. this method.
  35528. */
  35529. virtual const String getUniqueName() const;
  35530. /** Called when an item is opened or closed.
  35531. When setOpen() is called and the item has specified that it might
  35532. have sub-items with the mightContainSubItems() method, this method
  35533. is called to let the item create or manage its sub-items.
  35534. So when this is called with isNowOpen set to true (i.e. when the item is being
  35535. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  35536. refresh its sub-item list.
  35537. When this is called with isNowOpen set to false, the subclass might want
  35538. to use clearSubItems() to save on space, or it might choose to leave them,
  35539. depending on the nature of the tree.
  35540. You could also use this callback as a trigger to start a background process
  35541. which asynchronously creates sub-items and adds them, if that's more
  35542. appropriate for the task in hand.
  35543. @see mightContainSubItems
  35544. */
  35545. virtual void itemOpennessChanged (bool isNowOpen);
  35546. /** Must return the width required by this item.
  35547. If your item needs to have a particular width in pixels, return that value; if
  35548. you'd rather have it just fill whatever space is available in the treeview,
  35549. return -1.
  35550. If all your items return -1, no horizontal scrollbar will be shown, but if any
  35551. items have fixed widths and extend beyond the width of the treeview, a
  35552. scrollbar will appear.
  35553. Each item can be a different width, but if they change width, you should call
  35554. treeHasChanged() to update the tree.
  35555. */
  35556. virtual int getItemWidth() const { return -1; }
  35557. /** Must return the height required by this item.
  35558. This is the height in pixels that the item will take up. Items in the tree
  35559. can be different heights, but if they change height, you should call
  35560. treeHasChanged() to update the tree.
  35561. */
  35562. virtual int getItemHeight() const { return 20; }
  35563. /** You can override this method to return false if you don't want to allow the
  35564. user to select this item.
  35565. */
  35566. virtual bool canBeSelected() const { return true; }
  35567. /** Creates a component that will be used to represent this item.
  35568. You don't have to implement this method - if it returns 0 then no component
  35569. will be used for the item, and you can just draw it using the paintItem()
  35570. callback. But if you do return a component, it will be positioned in the
  35571. treeview so that it can be used to represent this item.
  35572. The component returned will be managed by the treeview, so always return
  35573. a new component, and don't keep a reference to it, as the treeview will
  35574. delete it later when it goes off the screen or is no longer needed. Also
  35575. bear in mind that if the component keeps a reference to the item that
  35576. created it, that item could be deleted before the component. Its position
  35577. and size will be completely managed by the tree, so don't attempt to move it
  35578. around.
  35579. Something you may want to do with your component is to give it a pointer to
  35580. the TreeView that created it. This is perfectly safe, and there's no danger
  35581. of it becoming a dangling pointer because the TreeView will always delete
  35582. the component before it is itself deleted.
  35583. As long as you stick to these rules you can return whatever kind of
  35584. component you like. It's most useful if you're doing things like drag-and-drop
  35585. of items, or want to use a Label component to edit item names, etc.
  35586. */
  35587. virtual Component* createItemComponent() { return 0; }
  35588. /** Draws the item's contents.
  35589. You can choose to either implement this method and draw each item, or you
  35590. can use createItemComponent() to create a component that will represent the
  35591. item.
  35592. If all you need in your tree is to be able to draw the items and detect when
  35593. the user selects or double-clicks one of them, it's probably enough to
  35594. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  35595. complicated interactions, you may need to use createItemComponent() instead.
  35596. @param g the graphics context to draw into
  35597. @param width the width of the area available for drawing
  35598. @param height the height of the area available for drawing
  35599. */
  35600. virtual void paintItem (Graphics& g, int width, int height);
  35601. /** Draws the item's open/close button.
  35602. If you don't implement this method, the default behaviour is to
  35603. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  35604. it for custom effects.
  35605. */
  35606. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  35607. /** Called when the user clicks on this item.
  35608. If you're using createItemComponent() to create a custom component for the
  35609. item, the mouse-clicks might not make it through to the treeview, but this
  35610. is how you find out about clicks when just drawing each item individually.
  35611. The associated mouse-event details are passed in, so you can find out about
  35612. which button, where it was, etc.
  35613. @see itemDoubleClicked
  35614. */
  35615. virtual void itemClicked (const MouseEvent& e);
  35616. /** Called when the user double-clicks on this item.
  35617. If you're using createItemComponent() to create a custom component for the
  35618. item, the mouse-clicks might not make it through to the treeview, but this
  35619. is how you find out about clicks when just drawing each item individually.
  35620. The associated mouse-event details are passed in, so you can find out about
  35621. which button, where it was, etc.
  35622. If not overridden, the base class method here will open or close the item as
  35623. if the 'plus' button had been clicked.
  35624. @see itemClicked
  35625. */
  35626. virtual void itemDoubleClicked (const MouseEvent& e);
  35627. /** Called when the item is selected or deselected.
  35628. Use this if you want to do something special when the item's selectedness
  35629. changes. By default it'll get repainted when this happens.
  35630. */
  35631. virtual void itemSelectionChanged (bool isNowSelected);
  35632. /** The item can return a tool tip string here if it wants to.
  35633. @see TooltipClient
  35634. */
  35635. virtual const String getTooltip();
  35636. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  35637. If this returns a non-empty name then when the user drags an item, the treeview will
  35638. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  35639. a drag-and-drop operation, using this string as the source description, with the treeview
  35640. itself as the source component.
  35641. If you need more complex drag-and-drop behaviour, you can use custom components for
  35642. the items, and use those to trigger the drag.
  35643. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  35644. isInterestedInFileDrag(), etc.
  35645. @see DragAndDropContainer::startDragging
  35646. */
  35647. virtual const String getDragSourceDescription();
  35648. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  35649. method and return true.
  35650. If you return true and allow some files to be dropped, you'll also need to implement the
  35651. filesDropped() method to do something with them.
  35652. Note that this will be called often, so make your implementation very quick! There's
  35653. certainly no time to try opening the files and having a think about what's inside them!
  35654. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  35655. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  35656. */
  35657. virtual bool isInterestedInFileDrag (const StringArray& files);
  35658. /** When files are dropped into this item, this callback is invoked.
  35659. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  35660. The insertIndex value indicates where in the list of sub-items the files were dropped.
  35661. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  35662. */
  35663. virtual void filesDropped (const StringArray& files, int insertIndex);
  35664. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  35665. If you implement this method, you'll also need to implement itemDropped() in order to handle
  35666. the items when they are dropped.
  35667. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  35668. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  35669. */
  35670. virtual bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  35671. /** When a things are dropped into this item, this callback is invoked.
  35672. For this to work, you need to have also implemented isInterestedInDragSource().
  35673. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  35674. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  35675. */
  35676. virtual void itemDropped (const String& sourceDescription, Component* sourceComponent, int insertIndex);
  35677. /** Sets a flag to indicate that the item wants to be allowed
  35678. to draw all the way across to the left edge of the treeview.
  35679. By default this is false, which means that when the paintItem()
  35680. method is called, its graphics context is clipped to only allow
  35681. drawing within the item's rectangle. If this flag is set to true,
  35682. then the graphics context isn't clipped on its left side, so it
  35683. can draw all the way across to the left margin. Note that the
  35684. context will still have its origin in the same place though, so
  35685. the coordinates of anything to its left will be negative. It's
  35686. mostly useful if you want to draw a wider bar behind the
  35687. highlighted item.
  35688. */
  35689. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  35690. /** Saves the current state of open/closed nodes so it can be restored later.
  35691. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  35692. and records it as XML. To identify node objects it uses the
  35693. TreeViewItem::getUniqueName() method to create named paths. This
  35694. means that the same state of open/closed nodes can be restored to a
  35695. completely different instance of the tree, as long as it contains nodes
  35696. whose unique names are the same.
  35697. You'd normally want to use TreeView::getOpennessState() rather than call it
  35698. for a specific item, but this can be handy if you need to briefly save the state
  35699. for a section of the tree.
  35700. The caller is responsible for deleting the object that is returned.
  35701. @see TreeView::getOpennessState, restoreOpennessState
  35702. */
  35703. XmlElement* getOpennessState() const throw();
  35704. /** Restores the openness of this item and all its sub-items from a saved state.
  35705. See TreeView::restoreOpennessState for more details.
  35706. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  35707. for a specific item, but this can be handy if you need to briefly save the state
  35708. for a section of the tree.
  35709. @see TreeView::restoreOpennessState, getOpennessState
  35710. */
  35711. void restoreOpennessState (const XmlElement& xml) throw();
  35712. /** Returns the index of this item in its parent's sub-items. */
  35713. int getIndexInParent() const throw();
  35714. /** Returns true if this item is the last of its parent's sub-itens. */
  35715. bool isLastOfSiblings() const throw();
  35716. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  35717. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  35718. The string takes the form of a path, constructed from the getUniqueName() of this
  35719. item and all its parents, so these must all be correctly implemented for it to work.
  35720. @see TreeView::findItemFromIdentifierString, getUniqueName
  35721. */
  35722. const String getItemIdentifierString() const;
  35723. juce_UseDebuggingNewOperator
  35724. private:
  35725. TreeView* ownerView;
  35726. TreeViewItem* parentItem;
  35727. OwnedArray <TreeViewItem> subItems;
  35728. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  35729. int uid;
  35730. bool selected : 1;
  35731. bool redrawNeeded : 1;
  35732. bool drawLinesInside : 1;
  35733. bool drawsInLeftMargin : 1;
  35734. unsigned int openness : 2;
  35735. friend class TreeView;
  35736. friend class TreeViewContentComponent;
  35737. void updatePositions (int newY);
  35738. int getIndentX() const throw();
  35739. void setOwnerView (TreeView* newOwner) throw();
  35740. void paintRecursively (Graphics& g, int width);
  35741. TreeViewItem* getTopLevelItem() throw();
  35742. TreeViewItem* findItemRecursively (int y) throw();
  35743. TreeViewItem* getDeepestOpenParentItem() throw();
  35744. int getNumRows() const throw();
  35745. TreeViewItem* getItemOnRow (int index) throw();
  35746. void deselectAllRecursively();
  35747. int countSelectedItemsRecursively() const throw();
  35748. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  35749. TreeViewItem* getNextVisibleItem (bool recurse) const throw();
  35750. TreeViewItem* findItemFromIdentifierString (const String& identifierString);
  35751. TreeViewItem (const TreeViewItem&);
  35752. TreeViewItem& operator= (const TreeViewItem&);
  35753. };
  35754. /**
  35755. A tree-view component.
  35756. Use one of these to hold and display a structure of TreeViewItem objects.
  35757. */
  35758. class JUCE_API TreeView : public Component,
  35759. public SettableTooltipClient,
  35760. public FileDragAndDropTarget,
  35761. public DragAndDropTarget,
  35762. private AsyncUpdater
  35763. {
  35764. public:
  35765. /** Creates an empty treeview.
  35766. Once you've got a treeview component, you'll need to give it something to
  35767. display, using the setRootItem() method.
  35768. */
  35769. TreeView (const String& componentName = String::empty);
  35770. /** Destructor. */
  35771. ~TreeView();
  35772. /** Sets the item that is displayed in the treeview.
  35773. A tree has a single root item which contains as many sub-items as it needs. If
  35774. you want the tree to contain a number of root items, you should still use a single
  35775. root item above these, but hide it using setRootItemVisible().
  35776. You can pass in 0 to this method to clear the tree and remove its current root item.
  35777. The object passed in will not be deleted by the treeview, it's up to the caller
  35778. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  35779. this item until you've removed it from the tree, either by calling setRootItem (0),
  35780. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  35781. to delete it.
  35782. */
  35783. void setRootItem (TreeViewItem* newRootItem);
  35784. /** Returns the tree's root item.
  35785. This will be the last object passed to setRootItem(), or 0 if none has been set.
  35786. */
  35787. TreeViewItem* getRootItem() const throw() { return rootItem; }
  35788. /** This will remove and delete the current root item.
  35789. It's a convenient way of deleting the item and calling setRootItem (0).
  35790. */
  35791. void deleteRootItem();
  35792. /** Changes whether the tree's root item is shown or not.
  35793. If the root item is hidden, only its sub-items will be shown in the treeview - this
  35794. lets you make the tree look as if it's got many root items. If it's hidden, this call
  35795. will also make sure the root item is open (otherwise the treeview would look empty).
  35796. */
  35797. void setRootItemVisible (bool shouldBeVisible);
  35798. /** Returns true if the root item is visible.
  35799. @see setRootItemVisible
  35800. */
  35801. bool isRootItemVisible() const throw() { return rootItemVisible; }
  35802. /** Sets whether items are open or closed by default.
  35803. Normally, items are closed until the user opens them, but you can use this
  35804. to make them default to being open until explicitly closed.
  35805. @see areItemsOpenByDefault
  35806. */
  35807. void setDefaultOpenness (bool isOpenByDefault);
  35808. /** Returns true if the tree's items default to being open.
  35809. @see setDefaultOpenness
  35810. */
  35811. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  35812. /** This sets a flag to indicate that the tree can be used for multi-selection.
  35813. You can always select multiple items internally by calling the
  35814. TreeViewItem::setSelected() method, but this flag indicates whether the user
  35815. is allowed to multi-select by clicking on the tree.
  35816. By default it is disabled.
  35817. @see isMultiSelectEnabled
  35818. */
  35819. void setMultiSelectEnabled (bool canMultiSelect);
  35820. /** Returns whether multi-select has been enabled for the tree.
  35821. @see setMultiSelectEnabled
  35822. */
  35823. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  35824. /** Sets a flag to indicate whether to hide the open/close buttons.
  35825. @see areOpenCloseButtonsVisible
  35826. */
  35827. void setOpenCloseButtonsVisible (bool shouldBeVisible);
  35828. /** Returns whether open/close buttons are shown.
  35829. @see setOpenCloseButtonsVisible
  35830. */
  35831. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  35832. /** Deselects any items that are currently selected. */
  35833. void clearSelectedItems();
  35834. /** Returns the number of items that are currently selected.
  35835. @see getSelectedItem, clearSelectedItems
  35836. */
  35837. int getNumSelectedItems() const throw();
  35838. /** Returns one of the selected items in the tree.
  35839. @param index the index, 0 to (getNumSelectedItems() - 1)
  35840. */
  35841. TreeViewItem* getSelectedItem (int index) const throw();
  35842. /** Returns the number of rows the tree is using.
  35843. This will depend on which items are open.
  35844. @see TreeViewItem::getRowNumberInTree()
  35845. */
  35846. int getNumRowsInTree() const;
  35847. /** Returns the item on a particular row of the tree.
  35848. If the index is out of range, this will return 0.
  35849. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  35850. */
  35851. TreeViewItem* getItemOnRow (int index) const;
  35852. /** Returns the item that contains a given y position.
  35853. The y is relative to the top of the TreeView component.
  35854. */
  35855. TreeViewItem* getItemAt (int yPosition) const throw();
  35856. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  35857. void scrollToKeepItemVisible (TreeViewItem* item);
  35858. /** Returns the treeview's Viewport object. */
  35859. Viewport* getViewport() const throw();
  35860. /** Returns the number of pixels by which each nested level of the tree is indented.
  35861. @see setIndentSize
  35862. */
  35863. int getIndentSize() const throw() { return indentSize; }
  35864. /** Changes the distance by which each nested level of the tree is indented.
  35865. @see getIndentSize
  35866. */
  35867. void setIndentSize (int newIndentSize);
  35868. /** Searches the tree for an item with the specified identifier.
  35869. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  35870. If no such item exists, this will return false. If the item is found, all of its items
  35871. will be automatically opened.
  35872. */
  35873. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  35874. /** Saves the current state of open/closed nodes so it can be restored later.
  35875. This takes a snapshot of which nodes have been explicitly opened or closed,
  35876. and records it as XML. To identify node objects it uses the
  35877. TreeViewItem::getUniqueName() method to create named paths. This
  35878. means that the same state of open/closed nodes can be restored to a
  35879. completely different instance of the tree, as long as it contains nodes
  35880. whose unique names are the same.
  35881. The caller is responsible for deleting the object that is returned.
  35882. @param alsoIncludeScrollPosition if this is true, the state will also
  35883. include information about where the
  35884. tree has been scrolled to vertically,
  35885. so this can also be restored
  35886. @see restoreOpennessState
  35887. */
  35888. XmlElement* getOpennessState (bool alsoIncludeScrollPosition) const;
  35889. /** Restores a previously saved arrangement of open/closed nodes.
  35890. This will try to restore a snapshot of the tree's state that was created by
  35891. the getOpennessState() method. If any of the nodes named in the original
  35892. XML aren't present in this tree, they will be ignored.
  35893. @see getOpennessState
  35894. */
  35895. void restoreOpennessState (const XmlElement& newState);
  35896. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  35897. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35898. methods.
  35899. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35900. */
  35901. enum ColourIds
  35902. {
  35903. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  35904. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  35905. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  35906. };
  35907. /** @internal */
  35908. void paint (Graphics& g);
  35909. /** @internal */
  35910. void resized();
  35911. /** @internal */
  35912. bool keyPressed (const KeyPress& key);
  35913. /** @internal */
  35914. void colourChanged();
  35915. /** @internal */
  35916. void enablementChanged();
  35917. /** @internal */
  35918. bool isInterestedInFileDrag (const StringArray& files);
  35919. /** @internal */
  35920. void fileDragEnter (const StringArray& files, int x, int y);
  35921. /** @internal */
  35922. void fileDragMove (const StringArray& files, int x, int y);
  35923. /** @internal */
  35924. void fileDragExit (const StringArray& files);
  35925. /** @internal */
  35926. void filesDropped (const StringArray& files, int x, int y);
  35927. /** @internal */
  35928. bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  35929. /** @internal */
  35930. void itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y);
  35931. /** @internal */
  35932. void itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y);
  35933. /** @internal */
  35934. void itemDragExit (const String& sourceDescription, Component* sourceComponent);
  35935. /** @internal */
  35936. void itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y);
  35937. juce_UseDebuggingNewOperator
  35938. private:
  35939. friend class TreeViewItem;
  35940. friend class TreeViewContentComponent;
  35941. class TreeViewport;
  35942. class InsertPointHighlight;
  35943. class TargetGroupHighlight;
  35944. friend class ScopedPointer<TreeViewport>;
  35945. friend class ScopedPointer<InsertPointHighlight>;
  35946. friend class ScopedPointer<TargetGroupHighlight>;
  35947. ScopedPointer<TreeViewport> viewport;
  35948. CriticalSection nodeAlterationLock;
  35949. TreeViewItem* rootItem;
  35950. ScopedPointer<InsertPointHighlight> dragInsertPointHighlight;
  35951. ScopedPointer<TargetGroupHighlight> dragTargetGroupHighlight;
  35952. int indentSize;
  35953. bool defaultOpenness : 1;
  35954. bool needsRecalculating : 1;
  35955. bool rootItemVisible : 1;
  35956. bool multiSelectEnabled : 1;
  35957. bool openCloseButtonsVisible : 1;
  35958. void itemsChanged() throw();
  35959. void handleAsyncUpdate();
  35960. void moveSelectedRow (int delta);
  35961. void updateButtonUnderMouse (const MouseEvent& e);
  35962. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw();
  35963. void hideDragHighlight() throw();
  35964. void handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  35965. void handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  35966. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  35967. const StringArray& files, const String& sourceDescription,
  35968. Component* sourceComponent) const throw();
  35969. TreeView (const TreeView&);
  35970. TreeView& operator= (const TreeView&);
  35971. };
  35972. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  35973. /*** End of inlined file: juce_TreeView.h ***/
  35974. #endif
  35975. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  35976. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  35977. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  35978. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  35979. /*** Start of inlined file: juce_DirectoryContentsList.h ***/
  35980. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  35981. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  35982. /*** Start of inlined file: juce_FileFilter.h ***/
  35983. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  35984. #define __JUCE_FILEFILTER_JUCEHEADER__
  35985. /**
  35986. Interface for deciding which files are suitable for something.
  35987. For example, this is used by DirectoryContentsList to select which files
  35988. go into the list.
  35989. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  35990. */
  35991. class JUCE_API FileFilter
  35992. {
  35993. public:
  35994. /** Creates a filter with the given description.
  35995. The description can be returned later with the getDescription() method.
  35996. */
  35997. FileFilter (const String& filterDescription);
  35998. /** Destructor. */
  35999. virtual ~FileFilter();
  36000. /** Returns the description that the filter was created with. */
  36001. const String& getDescription() const throw();
  36002. /** Should return true if this file is suitable for inclusion in whatever context
  36003. the object is being used.
  36004. */
  36005. virtual bool isFileSuitable (const File& file) const = 0;
  36006. /** Should return true if this directory is suitable for inclusion in whatever context
  36007. the object is being used.
  36008. */
  36009. virtual bool isDirectorySuitable (const File& file) const = 0;
  36010. protected:
  36011. String description;
  36012. };
  36013. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  36014. /*** End of inlined file: juce_FileFilter.h ***/
  36015. /**
  36016. A class to asynchronously scan for details about the files in a directory.
  36017. This keeps a list of files and some information about them, using a background
  36018. thread to scan for more files. As files are found, it broadcasts change messages
  36019. to tell any listeners.
  36020. @see FileListComponent, FileBrowserComponent
  36021. */
  36022. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  36023. public TimeSliceClient
  36024. {
  36025. public:
  36026. /** Creates a directory list.
  36027. To set the directory it should point to, use setDirectory(), which will
  36028. also start it scanning for files on the background thread.
  36029. When the background thread finds and adds new files to this list, the
  36030. ChangeBroadcaster class will send a change message, so you can register
  36031. listeners and update them when the list changes.
  36032. @param fileFilter an optional filter to select which files are
  36033. included in the list. If this is 0, then all files
  36034. and directories are included. Make sure that the
  36035. filter doesn't get deleted during the lifetime of this
  36036. object
  36037. @param threadToUse a thread object that this list can use
  36038. to scan for files as a background task. Make sure
  36039. that the thread you give it has been started, or you
  36040. won't get any files!
  36041. */
  36042. DirectoryContentsList (const FileFilter* fileFilter,
  36043. TimeSliceThread& threadToUse);
  36044. /** Destructor. */
  36045. ~DirectoryContentsList();
  36046. /** Sets the directory to look in for files.
  36047. If the directory that's passed in is different to the current one, this will
  36048. also start the background thread scanning it for files.
  36049. */
  36050. void setDirectory (const File& directory,
  36051. bool includeDirectories,
  36052. bool includeFiles);
  36053. /** Returns the directory that's currently being used. */
  36054. const File& getDirectory() const;
  36055. /** Clears the list, and stops the thread scanning for files. */
  36056. void clear();
  36057. /** Clears the list and restarts scanning the directory for files. */
  36058. void refresh();
  36059. /** True if the background thread hasn't yet finished scanning for files. */
  36060. bool isStillLoading() const;
  36061. /** Tells the list whether or not to ignore hidden files.
  36062. By default these are ignored.
  36063. */
  36064. void setIgnoresHiddenFiles (bool shouldIgnoreHiddenFiles);
  36065. /** Returns true if hidden files are ignored.
  36066. @see setIgnoresHiddenFiles
  36067. */
  36068. bool ignoresHiddenFiles() const;
  36069. /** Contains cached information about one of the files in a DirectoryContentsList.
  36070. */
  36071. struct FileInfo
  36072. {
  36073. /** The filename.
  36074. This isn't a full pathname, it's just the last part of the path, same as you'd
  36075. get from File::getFileName().
  36076. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  36077. */
  36078. String filename;
  36079. /** File size in bytes. */
  36080. int64 fileSize;
  36081. /** File modification time.
  36082. As supplied by File::getLastModificationTime().
  36083. */
  36084. Time modificationTime;
  36085. /** File creation time.
  36086. As supplied by File::getCreationTime().
  36087. */
  36088. Time creationTime;
  36089. /** True if the file is a directory. */
  36090. bool isDirectory;
  36091. /** True if the file is read-only. */
  36092. bool isReadOnly;
  36093. };
  36094. /** Returns the number of files currently available in the list.
  36095. The info about one of these files can be retrieved with getFileInfo() or
  36096. getFile().
  36097. Obviously as the background thread runs and scans the directory for files, this
  36098. number will change.
  36099. @see getFileInfo, getFile
  36100. */
  36101. int getNumFiles() const;
  36102. /** Returns the cached information about one of the files in the list.
  36103. If the index is in-range, this will return true and will copy the file's details
  36104. to the structure that is passed-in.
  36105. If it returns false, then the index wasn't in range, and the structure won't
  36106. be affected.
  36107. @see getNumFiles, getFile
  36108. */
  36109. bool getFileInfo (int index, FileInfo& resultInfo) const;
  36110. /** Returns one of the files in the list.
  36111. @param index should be less than getNumFiles(). If this is out-of-range, the
  36112. return value will be File::nonexistent
  36113. @see getNumFiles, getFileInfo
  36114. */
  36115. const File getFile (int index) const;
  36116. /** Returns the file filter being used.
  36117. The filter is specified in the constructor.
  36118. */
  36119. const FileFilter* getFilter() const { return fileFilter; }
  36120. /** @internal */
  36121. bool useTimeSlice();
  36122. /** @internal */
  36123. TimeSliceThread& getTimeSliceThread() { return thread; }
  36124. /** @internal */
  36125. static int compareElements (const DirectoryContentsList::FileInfo* first,
  36126. const DirectoryContentsList::FileInfo* second);
  36127. juce_UseDebuggingNewOperator
  36128. private:
  36129. File root;
  36130. const FileFilter* fileFilter;
  36131. TimeSliceThread& thread;
  36132. int fileTypeFlags;
  36133. CriticalSection fileListLock;
  36134. OwnedArray <FileInfo> files;
  36135. ScopedPointer <DirectoryIterator> fileFindHandle;
  36136. bool volatile shouldStop;
  36137. void changed();
  36138. bool checkNextFile (bool& hasChanged);
  36139. bool addFile (const File& file, bool isDir,
  36140. const int64 fileSize, const Time& modTime,
  36141. const Time& creationTime, bool isReadOnly);
  36142. void setTypeFlags (int newFlags);
  36143. DirectoryContentsList (const DirectoryContentsList&);
  36144. DirectoryContentsList& operator= (const DirectoryContentsList&);
  36145. };
  36146. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36147. /*** End of inlined file: juce_DirectoryContentsList.h ***/
  36148. /*** Start of inlined file: juce_FileBrowserListener.h ***/
  36149. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36150. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36151. /**
  36152. A listener for user selection events in a file browser.
  36153. This is used by a FileBrowserComponent or FileListComponent.
  36154. */
  36155. class JUCE_API FileBrowserListener
  36156. {
  36157. public:
  36158. /** Destructor. */
  36159. virtual ~FileBrowserListener();
  36160. /** Callback when the user selects a different file in the browser. */
  36161. virtual void selectionChanged() = 0;
  36162. /** Callback when the user clicks on a file in the browser. */
  36163. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  36164. /** Callback when the user double-clicks on a file in the browser. */
  36165. virtual void fileDoubleClicked (const File& file) = 0;
  36166. };
  36167. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36168. /*** End of inlined file: juce_FileBrowserListener.h ***/
  36169. /**
  36170. A base class for components that display a list of the files in a directory.
  36171. @see DirectoryContentsList
  36172. */
  36173. class JUCE_API DirectoryContentsDisplayComponent
  36174. {
  36175. public:
  36176. /** Creates a DirectoryContentsDisplayComponent for a given list of files. */
  36177. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  36178. /** Destructor. */
  36179. virtual ~DirectoryContentsDisplayComponent();
  36180. /** Returns the number of files the user has got selected.
  36181. @see getSelectedFile
  36182. */
  36183. virtual int getNumSelectedFiles() const = 0;
  36184. /** Returns one of the files that the user has currently selected.
  36185. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  36186. @see getNumSelectedFiles
  36187. */
  36188. virtual const File getSelectedFile (int index) const = 0;
  36189. /** Deselects any selected files. */
  36190. virtual void deselectAllFiles() = 0;
  36191. /** Scrolls this view to the top. */
  36192. virtual void scrollToTop() = 0;
  36193. /** Adds a listener to be told when files are selected or clicked.
  36194. @see removeListener
  36195. */
  36196. void addListener (FileBrowserListener* listener);
  36197. /** Removes a listener.
  36198. @see addListener
  36199. */
  36200. void removeListener (FileBrowserListener* listener);
  36201. /** A set of colour IDs to use to change the colour of various aspects of the list.
  36202. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36203. methods.
  36204. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36205. */
  36206. enum ColourIds
  36207. {
  36208. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  36209. textColourId = 0x1000541, /**< The colour for the text. */
  36210. };
  36211. /** @internal */
  36212. void sendSelectionChangeMessage();
  36213. /** @internal */
  36214. void sendDoubleClickMessage (const File& file);
  36215. /** @internal */
  36216. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  36217. juce_UseDebuggingNewOperator
  36218. protected:
  36219. DirectoryContentsList& fileList;
  36220. ListenerList <FileBrowserListener> listeners;
  36221. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  36222. DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  36223. };
  36224. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36225. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  36226. #endif
  36227. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36228. #endif
  36229. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36230. /*** Start of inlined file: juce_FileBrowserComponent.h ***/
  36231. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36232. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36233. /*** Start of inlined file: juce_FilePreviewComponent.h ***/
  36234. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36235. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36236. /**
  36237. Base class for components that live inside a file chooser dialog box and
  36238. show previews of the files that get selected.
  36239. One of these allows special extra information to be displayed for files
  36240. in a dialog box as the user selects them. Each time the current file or
  36241. directory is changed, the selectedFileChanged() method will be called
  36242. to allow it to update itself appropriately.
  36243. @see FileChooser, ImagePreviewComponent
  36244. */
  36245. class JUCE_API FilePreviewComponent : public Component
  36246. {
  36247. public:
  36248. /** Creates a FilePreviewComponent. */
  36249. FilePreviewComponent();
  36250. /** Destructor. */
  36251. ~FilePreviewComponent();
  36252. /** Called to indicate that the user's currently selected file has changed.
  36253. @param newSelectedFile the newly selected file or directory, which may be
  36254. File::nonexistent if none is selected.
  36255. */
  36256. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  36257. juce_UseDebuggingNewOperator
  36258. private:
  36259. FilePreviewComponent (const FilePreviewComponent&);
  36260. FilePreviewComponent& operator= (const FilePreviewComponent&);
  36261. };
  36262. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36263. /*** End of inlined file: juce_FilePreviewComponent.h ***/
  36264. /**
  36265. A component for browsing and selecting a file or directory to open or save.
  36266. This contains a FileListComponent and adds various boxes and controls for
  36267. navigating and selecting a file. It can work in different modes so that it can
  36268. be used for loading or saving a file, or for choosing a directory.
  36269. @see FileChooserDialogBox, FileChooser, FileListComponent
  36270. */
  36271. class JUCE_API FileBrowserComponent : public Component,
  36272. public ChangeBroadcaster,
  36273. private FileBrowserListener,
  36274. private TextEditorListener,
  36275. private ButtonListener,
  36276. private ComboBoxListener,
  36277. private FileFilter
  36278. {
  36279. public:
  36280. /** Various options for the browser.
  36281. A combination of these is passed into the FileBrowserComponent constructor.
  36282. */
  36283. enum FileChooserFlags
  36284. {
  36285. openMode = 1, /**< specifies that the component should allow the user to
  36286. choose an existing file with the intention of opening it. */
  36287. saveMode = 2, /**< specifies that the component should allow the user to specify
  36288. the name of a file that will be used to save something. */
  36289. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  36290. conjunction with canSelectDirectories). */
  36291. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  36292. conjuction with canSelectFiles). */
  36293. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  36294. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  36295. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  36296. };
  36297. /** Creates a FileBrowserComponent.
  36298. @param flags A combination of flags from the FileChooserFlags enumeration,
  36299. used to specify the component's behaviour. The flags must contain
  36300. either openMode or saveMode, and canSelectFiles and/or
  36301. canSelectDirectories.
  36302. @param initialFileOrDirectory The file or directory that should be selected when
  36303. the component begins. If this is File::nonexistent,
  36304. a default directory will be chosen.
  36305. @param fileFilter an optional filter to use to determine which files
  36306. are shown. If this is 0 then all files are displayed. Note
  36307. that a pointer is kept internally to this object, so
  36308. make sure that it is not deleted before the browser object
  36309. is deleted.
  36310. @param previewComp an optional preview component that will be used to
  36311. show previews of files that the user selects
  36312. */
  36313. FileBrowserComponent (int flags,
  36314. const File& initialFileOrDirectory,
  36315. const FileFilter* fileFilter,
  36316. FilePreviewComponent* previewComp);
  36317. /** Destructor. */
  36318. ~FileBrowserComponent();
  36319. /** Returns the number of files that the user has got selected.
  36320. If multiple select isn't active, this will only be 0 or 1. To get the complete
  36321. list of files they've chosen, pass an index to getCurrentFile().
  36322. */
  36323. int getNumSelectedFiles() const throw();
  36324. /** Returns one of the files that the user has chosen.
  36325. If the box has multi-select enabled, the index lets you specify which of the files
  36326. to get - see getNumSelectedFiles() to find out how many files were chosen.
  36327. @see getHighlightedFile
  36328. */
  36329. const File getSelectedFile (int index) const throw();
  36330. /** Deselects any files that are currently selected.
  36331. */
  36332. void deselectAllFiles();
  36333. /** Returns true if the currently selected file(s) are usable.
  36334. This can be used to decide whether the user can press "ok" for the
  36335. current file. What it does depends on the mode, so for example in an "open"
  36336. mode, this only returns true if a file has been selected and if it exists.
  36337. In a "save" mode, a non-existent file would also be valid.
  36338. */
  36339. bool currentFileIsValid() const;
  36340. /** This returns the last item in the view that the user has highlighted.
  36341. This may be different from getCurrentFile(), which returns the value
  36342. that is shown in the filename box, and if there are multiple selections,
  36343. this will only return one of them.
  36344. @see getSelectedFile
  36345. */
  36346. const File getHighlightedFile() const throw();
  36347. /** Returns the directory whose contents are currently being shown in the listbox. */
  36348. const File getRoot() const;
  36349. /** Changes the directory that's being shown in the listbox. */
  36350. void setRoot (const File& newRootDirectory);
  36351. /** Equivalent to pressing the "up" button to browse the parent directory. */
  36352. void goUp();
  36353. /** Refreshes the directory that's currently being listed. */
  36354. void refresh();
  36355. /** Returns a verb to describe what should happen when the file is accepted.
  36356. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  36357. mode, it'll be "Save", etc.
  36358. */
  36359. virtual const String getActionVerb() const;
  36360. /** Returns true if the saveMode flag was set when this component was created.
  36361. */
  36362. bool isSaveMode() const throw();
  36363. /** Adds a listener to be told when the user selects and clicks on files.
  36364. @see removeListener
  36365. */
  36366. void addListener (FileBrowserListener* listener);
  36367. /** Removes a listener.
  36368. @see addListener
  36369. */
  36370. void removeListener (FileBrowserListener* listener);
  36371. /** @internal */
  36372. void resized();
  36373. /** @internal */
  36374. void buttonClicked (Button* b);
  36375. /** @internal */
  36376. void comboBoxChanged (ComboBox*);
  36377. /** @internal */
  36378. void textEditorTextChanged (TextEditor& editor);
  36379. /** @internal */
  36380. void textEditorReturnKeyPressed (TextEditor& editor);
  36381. /** @internal */
  36382. void textEditorEscapeKeyPressed (TextEditor& editor);
  36383. /** @internal */
  36384. void textEditorFocusLost (TextEditor& editor);
  36385. /** @internal */
  36386. bool keyPressed (const KeyPress& key);
  36387. /** @internal */
  36388. void selectionChanged();
  36389. /** @internal */
  36390. void fileClicked (const File& f, const MouseEvent& e);
  36391. /** @internal */
  36392. void fileDoubleClicked (const File& f);
  36393. /** @internal */
  36394. bool isFileSuitable (const File& file) const;
  36395. /** @internal */
  36396. bool isDirectorySuitable (const File&) const;
  36397. /** @internal */
  36398. FilePreviewComponent* getPreviewComponent() const throw();
  36399. juce_UseDebuggingNewOperator
  36400. protected:
  36401. virtual const BigInteger getRoots (StringArray& rootNames, StringArray& rootPaths);
  36402. private:
  36403. ScopedPointer <DirectoryContentsList> fileList;
  36404. const FileFilter* fileFilter;
  36405. int flags;
  36406. File currentRoot;
  36407. Array<File> chosenFiles;
  36408. ListenerList <FileBrowserListener> listeners;
  36409. DirectoryContentsDisplayComponent* fileListComponent;
  36410. FilePreviewComponent* previewComp;
  36411. ComboBox* currentPathBox;
  36412. TextEditor* filenameBox;
  36413. Button* goUpButton;
  36414. TimeSliceThread thread;
  36415. void sendListenerChangeMessage();
  36416. bool isFileOrDirSuitable (const File& f) const;
  36417. FileBrowserComponent (const FileBrowserComponent&);
  36418. FileBrowserComponent& operator= (const FileBrowserComponent&);
  36419. };
  36420. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36421. /*** End of inlined file: juce_FileBrowserComponent.h ***/
  36422. #endif
  36423. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36424. #endif
  36425. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36426. /*** Start of inlined file: juce_FileChooser.h ***/
  36427. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36428. #define __JUCE_FILECHOOSER_JUCEHEADER__
  36429. /**
  36430. Creates a dialog box to choose a file or directory to load or save.
  36431. To use a FileChooser:
  36432. - create one (as a local stack variable is the neatest way)
  36433. - call one of its browseFor.. methods
  36434. - if this returns true, the user has selected a file, so you can retrieve it
  36435. with the getResult() method.
  36436. e.g. @code
  36437. void loadMooseFile()
  36438. {
  36439. FileChooser myChooser ("Please select the moose you want to load...",
  36440. File::getSpecialLocation (File::userHomeDirectory),
  36441. "*.moose");
  36442. if (myChooser.browseForFileToOpen())
  36443. {
  36444. File mooseFile (myChooser.getResult());
  36445. loadMoose (mooseFile);
  36446. }
  36447. }
  36448. @endcode
  36449. */
  36450. class JUCE_API FileChooser
  36451. {
  36452. public:
  36453. /** Creates a FileChooser.
  36454. After creating one of these, use one of the browseFor... methods to display it.
  36455. @param dialogBoxTitle a text string to display in the dialog box to
  36456. tell the user what's going on
  36457. @param initialFileOrDirectory the file or directory that should be selected when
  36458. the dialog box opens. If this parameter is set to
  36459. File::nonexistent, a sensible default directory
  36460. will be used instead.
  36461. @param filePatternsAllowed a set of file patterns to specify which files can be
  36462. selected - each pattern should be separated by a
  36463. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  36464. empty string means that all files are allowed
  36465. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  36466. possible; if false, then a Juce-based browser dialog
  36467. box will always be used
  36468. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  36469. */
  36470. FileChooser (const String& dialogBoxTitle,
  36471. const File& initialFileOrDirectory = File::nonexistent,
  36472. const String& filePatternsAllowed = String::empty,
  36473. bool useOSNativeDialogBox = true);
  36474. /** Destructor. */
  36475. ~FileChooser();
  36476. /** Shows a dialog box to choose a file to open.
  36477. This will display the dialog box modally, using an "open file" mode, so that
  36478. it won't allow non-existent files or directories to be chosen.
  36479. @param previewComponent an optional component to display inside the dialog
  36480. box to show special info about the files that the user
  36481. is browsing. The component will not be deleted by this
  36482. object, so the caller must take care of it.
  36483. @returns true if the user selected a file, in which case, use the getResult()
  36484. method to find out what it was. Returns false if they cancelled instead.
  36485. @see browseForFileToSave, browseForDirectory
  36486. */
  36487. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  36488. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  36489. The files that are returned can be obtained by calling getResults(). See
  36490. browseForFileToOpen() for more info about the behaviour of this method.
  36491. */
  36492. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  36493. /** Shows a dialog box to choose a file to save.
  36494. This will display the dialog box modally, using an "save file" mode, so it
  36495. will allow non-existent files to be chosen, but not directories.
  36496. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  36497. the user if they're sure they want to overwrite a file that already
  36498. exists
  36499. @returns true if the user chose a file and pressed 'ok', in which case, use
  36500. the getResult() method to find out what the file was. Returns false
  36501. if they cancelled instead.
  36502. @see browseForFileToOpen, browseForDirectory
  36503. */
  36504. bool browseForFileToSave (bool warnAboutOverwritingExistingFiles);
  36505. /** Shows a dialog box to choose a directory.
  36506. This will display the dialog box modally, using an "open directory" mode, so it
  36507. will only allow directories to be returned, not files.
  36508. @returns true if the user chose a directory and pressed 'ok', in which case, use
  36509. the getResult() method to find out what they chose. Returns false
  36510. if they cancelled instead.
  36511. @see browseForFileToOpen, browseForFileToSave
  36512. */
  36513. bool browseForDirectory();
  36514. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  36515. The files that are returned can be obtained by calling getResults(). See
  36516. browseForFileToOpen() for more info about the behaviour of this method.
  36517. */
  36518. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  36519. /** Returns the last file that was chosen by one of the browseFor methods.
  36520. After calling the appropriate browseFor... method, this method lets you
  36521. find out what file or directory they chose.
  36522. Note that the file returned is only valid if the browse method returned true (i.e.
  36523. if the user pressed 'ok' rather than cancelling).
  36524. If you're using a multiple-file select, then use the getResults() method instead,
  36525. to obtain the list of all files chosen.
  36526. @see getResults
  36527. */
  36528. const File getResult() const;
  36529. /** Returns a list of all the files that were chosen during the last call to a
  36530. browse method.
  36531. This array may be empty if no files were chosen, or can contain multiple entries
  36532. if multiple files were chosen.
  36533. @see getResult
  36534. */
  36535. const Array<File>& getResults() const;
  36536. juce_UseDebuggingNewOperator
  36537. private:
  36538. String title, filters;
  36539. File startingFile;
  36540. Array<File> results;
  36541. bool useNativeDialogBox;
  36542. bool showDialog (bool selectsDirectories, bool selectsFiles, bool isSave,
  36543. bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  36544. FilePreviewComponent* previewComponent);
  36545. static void showPlatformDialog (Array<File>& results, const String& title, const File& file,
  36546. const String& filters, bool selectsDirectories, bool selectsFiles,
  36547. bool isSave, bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  36548. FilePreviewComponent* previewComponent);
  36549. };
  36550. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  36551. /*** End of inlined file: juce_FileChooser.h ***/
  36552. #endif
  36553. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36554. /*** Start of inlined file: juce_FileChooserDialogBox.h ***/
  36555. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36556. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36557. /*** Start of inlined file: juce_ResizableWindow.h ***/
  36558. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36559. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36560. /*** Start of inlined file: juce_TopLevelWindow.h ***/
  36561. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36562. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36563. /*** Start of inlined file: juce_DropShadower.h ***/
  36564. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  36565. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  36566. /**
  36567. Adds a drop-shadow to a component.
  36568. This object creates and manages a set of components which sit around a
  36569. component, creating a gaussian shadow around it. The components will track
  36570. the position of the component and if it's brought to the front they'll also
  36571. follow this.
  36572. For desktop windows you don't need to use this class directly - just
  36573. set the Component::windowHasDropShadow flag when calling
  36574. Component::addToDesktop(), and the system will create one of these if it's
  36575. needed (which it obviously isn't on the Mac, for example).
  36576. */
  36577. class JUCE_API DropShadower : public ComponentListener
  36578. {
  36579. public:
  36580. /** Creates a DropShadower.
  36581. @param alpha the opacity of the shadows, from 0 to 1.0
  36582. @param xOffset the horizontal displacement of the shadow, in pixels
  36583. @param yOffset the vertical displacement of the shadow, in pixels
  36584. @param blurRadius the radius of the blur to use for creating the shadow
  36585. */
  36586. DropShadower (float alpha = 0.5f,
  36587. int xOffset = 1,
  36588. int yOffset = 5,
  36589. float blurRadius = 10.0f);
  36590. /** Destructor. */
  36591. virtual ~DropShadower();
  36592. /** Attaches the DropShadower to the component you want to shadow. */
  36593. void setOwner (Component* componentToFollow);
  36594. /** @internal */
  36595. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  36596. /** @internal */
  36597. void componentBroughtToFront (Component& component);
  36598. /** @internal */
  36599. void componentChildrenChanged (Component& component);
  36600. /** @internal */
  36601. void componentParentHierarchyChanged (Component& component);
  36602. /** @internal */
  36603. void componentVisibilityChanged (Component& component);
  36604. juce_UseDebuggingNewOperator
  36605. private:
  36606. Component* owner;
  36607. int numShadows;
  36608. Component* shadowWindows[4];
  36609. Image shadowImageSections[12];
  36610. const int shadowEdge, xOffset, yOffset;
  36611. const float alpha, blurRadius;
  36612. bool inDestructor, reentrant;
  36613. void updateShadows();
  36614. void setShadowImage (const Image& src,
  36615. const int num,
  36616. const int w, const int h,
  36617. const int sx, const int sy);
  36618. void bringShadowWindowsToFront();
  36619. void deleteShadowWindows();
  36620. DropShadower (const DropShadower&);
  36621. DropShadower& operator= (const DropShadower&);
  36622. };
  36623. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  36624. /*** End of inlined file: juce_DropShadower.h ***/
  36625. /**
  36626. A base class for top-level windows.
  36627. This class is used for components that are considered a major part of your
  36628. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  36629. etc. Things like menus that pop up briefly aren't derived from it.
  36630. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  36631. could itself be the child of another component.
  36632. The class manages a list of all instances of top-level windows that are in use,
  36633. and each one is also given the concept of being "active". The active window is
  36634. one that is actively being used by the user. This isn't quite the same as the
  36635. component with the keyboard focus, because there may be a popup menu or other
  36636. temporary window which gets keyboard focus while the active top level window is
  36637. unchanged.
  36638. A top-level window also has an optional drop-shadow.
  36639. @see ResizableWindow, DocumentWindow, DialogWindow
  36640. */
  36641. class JUCE_API TopLevelWindow : public Component
  36642. {
  36643. public:
  36644. /** Creates a TopLevelWindow.
  36645. @param name the name to give the component
  36646. @param addToDesktop if true, the window will be automatically added to the
  36647. desktop; if false, you can use it as a child component
  36648. */
  36649. TopLevelWindow (const String& name, bool addToDesktop);
  36650. /** Destructor. */
  36651. ~TopLevelWindow();
  36652. /** True if this is currently the TopLevelWindow that is actively being used.
  36653. This isn't quite the same as having keyboard focus, because the focus may be
  36654. on a child component or a temporary pop-up menu, etc, while this window is
  36655. still considered to be active.
  36656. @see activeWindowStatusChanged
  36657. */
  36658. bool isActiveWindow() const throw() { return windowIsActive_; }
  36659. /** This will set the bounds of the window so that it's centred in front of another
  36660. window.
  36661. If your app has a few windows open and want to pop up a dialog box for one of
  36662. them, you can use this to show it in front of the relevent parent window, which
  36663. is a bit neater than just having it appear in the middle of the screen.
  36664. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  36665. be used instead. If no window is focused, it'll just default to the middle of the
  36666. screen.
  36667. */
  36668. void centreAroundComponent (Component* componentToCentreAround,
  36669. int width, int height);
  36670. /** Turns the drop-shadow on and off. */
  36671. void setDropShadowEnabled (bool useShadow);
  36672. /** Sets whether an OS-native title bar will be used, or a Juce one.
  36673. @see isUsingNativeTitleBar
  36674. */
  36675. void setUsingNativeTitleBar (bool useNativeTitleBar);
  36676. /** Returns true if the window is currently using an OS-native title bar.
  36677. @see setUsingNativeTitleBar
  36678. */
  36679. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  36680. /** Returns the number of TopLevelWindow objects currently in use.
  36681. @see getTopLevelWindow
  36682. */
  36683. static int getNumTopLevelWindows() throw();
  36684. /** Returns one of the TopLevelWindow objects currently in use.
  36685. The index is 0 to (getNumTopLevelWindows() - 1).
  36686. */
  36687. static TopLevelWindow* getTopLevelWindow (int index) throw();
  36688. /** Returns the currently-active top level window.
  36689. There might not be one, of course, so this can return 0.
  36690. */
  36691. static TopLevelWindow* getActiveTopLevelWindow() throw();
  36692. juce_UseDebuggingNewOperator
  36693. /** @internal */
  36694. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  36695. protected:
  36696. /** This callback happens when this window becomes active or inactive.
  36697. @see isActiveWindow
  36698. */
  36699. virtual void activeWindowStatusChanged();
  36700. /** @internal */
  36701. void focusOfChildComponentChanged (FocusChangeType cause);
  36702. /** @internal */
  36703. void parentHierarchyChanged();
  36704. /** @internal */
  36705. void visibilityChanged();
  36706. /** @internal */
  36707. virtual int getDesktopWindowStyleFlags() const;
  36708. /** @internal */
  36709. void recreateDesktopWindow();
  36710. private:
  36711. friend class TopLevelWindowManager;
  36712. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  36713. ScopedPointer <DropShadower> shadower;
  36714. void setWindowActive (bool isNowActive);
  36715. TopLevelWindow (const TopLevelWindow&);
  36716. TopLevelWindow& operator= (const TopLevelWindow&);
  36717. };
  36718. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36719. /*** End of inlined file: juce_TopLevelWindow.h ***/
  36720. /*** Start of inlined file: juce_ComponentDragger.h ***/
  36721. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  36722. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  36723. /*** Start of inlined file: juce_ComponentBoundsConstrainer.h ***/
  36724. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  36725. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  36726. /**
  36727. A class that imposes restrictions on a Component's size or position.
  36728. This is used by classes such as ResizableCornerComponent,
  36729. ResizableBorderComponent and ResizableWindow.
  36730. The base class can impose some basic size and position limits, but you can
  36731. also subclass this for custom uses.
  36732. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  36733. */
  36734. class JUCE_API ComponentBoundsConstrainer
  36735. {
  36736. public:
  36737. /** When first created, the object will not impose any restrictions on the components. */
  36738. ComponentBoundsConstrainer() throw();
  36739. /** Destructor. */
  36740. virtual ~ComponentBoundsConstrainer();
  36741. /** Imposes a minimum width limit. */
  36742. void setMinimumWidth (int minimumWidth) throw();
  36743. /** Returns the current minimum width. */
  36744. int getMinimumWidth() const throw() { return minW; }
  36745. /** Imposes a maximum width limit. */
  36746. void setMaximumWidth (int maximumWidth) throw();
  36747. /** Returns the current maximum width. */
  36748. int getMaximumWidth() const throw() { return maxW; }
  36749. /** Imposes a minimum height limit. */
  36750. void setMinimumHeight (int minimumHeight) throw();
  36751. /** Returns the current minimum height. */
  36752. int getMinimumHeight() const throw() { return minH; }
  36753. /** Imposes a maximum height limit. */
  36754. void setMaximumHeight (int maximumHeight) throw();
  36755. /** Returns the current maximum height. */
  36756. int getMaximumHeight() const throw() { return maxH; }
  36757. /** Imposes a minimum width and height limit. */
  36758. void setMinimumSize (int minimumWidth,
  36759. int minimumHeight) throw();
  36760. /** Imposes a maximum width and height limit. */
  36761. void setMaximumSize (int maximumWidth,
  36762. int maximumHeight) throw();
  36763. /** Set all the maximum and minimum dimensions. */
  36764. void setSizeLimits (int minimumWidth,
  36765. int minimumHeight,
  36766. int maximumWidth,
  36767. int maximumHeight) throw();
  36768. /** Sets the amount by which the component is allowed to go off-screen.
  36769. The values indicate how many pixels must remain on-screen when dragged off
  36770. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  36771. when the component goes off the top of the screen, its y-position will be
  36772. clipped so that there are always at least 10 pixels on-screen. In other words,
  36773. the lowest y-position it can take would be (10 - the component's height).
  36774. If you pass 0 or less for one of these amounts, the component is allowed
  36775. to move beyond that edge completely, with no restrictions at all.
  36776. If you pass a very large number (i.e. larger that the dimensions of the
  36777. component itself), then the component won't be allowed to overlap that
  36778. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  36779. the component will bump into the left side of the screen and go no further.
  36780. */
  36781. void setMinimumOnscreenAmounts (int minimumWhenOffTheTop,
  36782. int minimumWhenOffTheLeft,
  36783. int minimumWhenOffTheBottom,
  36784. int minimumWhenOffTheRight) throw();
  36785. /** Specifies a width-to-height ratio that the resizer should always maintain.
  36786. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  36787. will always be maintained as this multiple of the height.
  36788. @see setResizeLimits
  36789. */
  36790. void setFixedAspectRatio (double widthOverHeight) throw();
  36791. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  36792. If no aspect ratio is being enforced, this will return 0.
  36793. */
  36794. double getFixedAspectRatio() const throw();
  36795. /** This callback changes the given co-ordinates to impose whatever the current
  36796. constraints are set to be.
  36797. @param bounds the target position that should be examined and adjusted
  36798. @param previousBounds the component's current size
  36799. @param limits the region in which the component can be positioned
  36800. @param isStretchingTop whether the top edge of the component is being resized
  36801. @param isStretchingLeft whether the left edge of the component is being resized
  36802. @param isStretchingBottom whether the bottom edge of the component is being resized
  36803. @param isStretchingRight whether the right edge of the component is being resized
  36804. */
  36805. virtual void checkBounds (Rectangle<int>& bounds,
  36806. const Rectangle<int>& previousBounds,
  36807. const Rectangle<int>& limits,
  36808. bool isStretchingTop,
  36809. bool isStretchingLeft,
  36810. bool isStretchingBottom,
  36811. bool isStretchingRight);
  36812. /** This callback happens when the resizer is about to start dragging. */
  36813. virtual void resizeStart();
  36814. /** This callback happens when the resizer has finished dragging. */
  36815. virtual void resizeEnd();
  36816. /** Checks the given bounds, and then sets the component to the corrected size. */
  36817. void setBoundsForComponent (Component* const component,
  36818. const Rectangle<int>& bounds,
  36819. bool isStretchingTop,
  36820. bool isStretchingLeft,
  36821. bool isStretchingBottom,
  36822. bool isStretchingRight);
  36823. /** Performs a check on the current size of a component, and moves or resizes
  36824. it if it fails the constraints.
  36825. */
  36826. void checkComponentBounds (Component* component);
  36827. /** Called by setBoundsForComponent() to apply a new constrained size to a
  36828. component.
  36829. By default this just calls setBounds(), but it virtual in case it's needed for
  36830. extremely cunning purposes.
  36831. */
  36832. virtual void applyBoundsToComponent (Component* component,
  36833. const Rectangle<int>& bounds);
  36834. juce_UseDebuggingNewOperator
  36835. private:
  36836. int minW, maxW, minH, maxH;
  36837. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  36838. double aspectRatio;
  36839. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  36840. ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  36841. };
  36842. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  36843. /*** End of inlined file: juce_ComponentBoundsConstrainer.h ***/
  36844. /**
  36845. An object to take care of the logic for dragging components around with the mouse.
  36846. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  36847. then in your mouseDrag() callback, call dragComponent().
  36848. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  36849. to limit the component's position and keep it on-screen.
  36850. e.g. @code
  36851. class MyDraggableComp
  36852. {
  36853. ComponentDragger myDragger;
  36854. void mouseDown (const MouseEvent& e)
  36855. {
  36856. myDragger.startDraggingComponent (this, 0);
  36857. }
  36858. void mouseDrag (const MouseEvent& e)
  36859. {
  36860. myDragger.dragComponent (this, e);
  36861. }
  36862. };
  36863. @endcode
  36864. */
  36865. class JUCE_API ComponentDragger
  36866. {
  36867. public:
  36868. /** Creates a ComponentDragger. */
  36869. ComponentDragger();
  36870. /** Destructor. */
  36871. virtual ~ComponentDragger();
  36872. /** Call this from your component's mouseDown() method, to prepare for dragging.
  36873. @param componentToDrag the component that you want to drag
  36874. @param constrainer a constrainer object to use to keep the component
  36875. from going offscreen
  36876. @see dragComponent
  36877. */
  36878. void startDraggingComponent (Component* const componentToDrag,
  36879. ComponentBoundsConstrainer* constrainer);
  36880. /** Call this from your mouseDrag() callback to move the component.
  36881. This will move the component, but will first check the validity of the
  36882. component's new position using the checkPosition() method, which you
  36883. can override if you need to enforce special positioning limits on the
  36884. component.
  36885. @param componentToDrag the component that you want to drag
  36886. @param e the current mouse-drag event
  36887. @see dragComponent
  36888. */
  36889. void dragComponent (Component* const componentToDrag,
  36890. const MouseEvent& e);
  36891. juce_UseDebuggingNewOperator
  36892. private:
  36893. ComponentBoundsConstrainer* constrainer;
  36894. Point<int> originalPos;
  36895. ComponentDragger (const ComponentDragger&);
  36896. ComponentDragger& operator= (const ComponentDragger&);
  36897. };
  36898. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  36899. /*** End of inlined file: juce_ComponentDragger.h ***/
  36900. /*** Start of inlined file: juce_ResizableBorderComponent.h ***/
  36901. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36902. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36903. /**
  36904. A component that resizes its parent window when dragged.
  36905. This component forms a frame around the edge of a component, allowing it to
  36906. be dragged by the edges or corners to resize it - like the way windows are
  36907. resized in MSWindows or Linux.
  36908. To use it, just add it to your component, making it fill the entire parent component
  36909. (there's a mouse hit-test that only traps mouse-events which land around the
  36910. edge of the component, so it's even ok to put it on top of any other components
  36911. you're using). Make sure you rescale the resizer component to fill the parent
  36912. each time the parent's size changes.
  36913. @see ResizableCornerComponent
  36914. */
  36915. class JUCE_API ResizableBorderComponent : public Component
  36916. {
  36917. public:
  36918. /** Creates a resizer.
  36919. Pass in the target component which you want to be resized when this one is
  36920. dragged.
  36921. The target component will usually be a parent of the resizer component, but this
  36922. isn't mandatory.
  36923. Remember that when the target component is resized, it'll need to move and
  36924. resize this component to keep it in place, as this won't happen automatically.
  36925. If the constrainer parameter is non-zero, then this object will be used to enforce
  36926. limits on the size and position that the component can be stretched to. Make sure
  36927. that the constrainer isn't deleted while still in use by this object.
  36928. @see ComponentBoundsConstrainer
  36929. */
  36930. ResizableBorderComponent (Component* componentToResize,
  36931. ComponentBoundsConstrainer* constrainer);
  36932. /** Destructor. */
  36933. ~ResizableBorderComponent();
  36934. /** Specifies how many pixels wide the draggable edges of this component are.
  36935. @see getBorderThickness
  36936. */
  36937. void setBorderThickness (const BorderSize& newBorderSize);
  36938. /** Returns the number of pixels wide that the draggable edges of this component are.
  36939. @see setBorderThickness
  36940. */
  36941. const BorderSize getBorderThickness() const;
  36942. /** Represents the different sections of a resizable border, which allow it to
  36943. resized in different ways.
  36944. */
  36945. class Zone
  36946. {
  36947. public:
  36948. enum Zones
  36949. {
  36950. centre = 0,
  36951. left = 1,
  36952. top = 2,
  36953. right = 4,
  36954. bottom = 8
  36955. };
  36956. /** Creates a Zone from a combination of the flags in \enum Zones. */
  36957. explicit Zone (int zoneFlags = 0) throw();
  36958. Zone (const Zone& other) throw();
  36959. Zone& operator= (const Zone& other) throw();
  36960. bool operator== (const Zone& other) const throw();
  36961. bool operator!= (const Zone& other) const throw();
  36962. /** Given a point within a rectangle with a resizable border, this returns the
  36963. zone that the point lies within.
  36964. */
  36965. static const Zone fromPositionOnBorder (const Rectangle<int>& totalSize,
  36966. const BorderSize& border,
  36967. const Point<int>& position);
  36968. /** Returns an appropriate mouse-cursor for this resize zone. */
  36969. const MouseCursor getMouseCursor() const throw();
  36970. /** Returns true if dragging this zone will move the enire object without resizing it. */
  36971. bool isDraggingWholeObject() const throw() { return zone == centre; }
  36972. /** Returns true if dragging this zone will move the object's left edge. */
  36973. bool isDraggingLeftEdge() const throw() { return (zone & left) != 0; }
  36974. /** Returns true if dragging this zone will move the object's right edge. */
  36975. bool isDraggingRightEdge() const throw() { return (zone & right) != 0; }
  36976. /** Returns true if dragging this zone will move the object's top edge. */
  36977. bool isDraggingTopEdge() const throw() { return (zone & top) != 0; }
  36978. /** Returns true if dragging this zone will move the object's bottom edge. */
  36979. bool isDraggingBottomEdge() const throw() { return (zone & bottom) != 0; }
  36980. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  36981. applies to.
  36982. */
  36983. const Rectangle<int> resizeRectangleBy (Rectangle<int> original,
  36984. const Point<int>& distance) const throw();
  36985. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  36986. applies to.
  36987. */
  36988. const Rectangle<float> resizeRectangleBy (Rectangle<float> original,
  36989. const Point<float>& distance) const throw();
  36990. /** Returns the raw flags for this zone. */
  36991. int getZoneFlags() const throw() { return zone; }
  36992. private:
  36993. int zone;
  36994. };
  36995. juce_UseDebuggingNewOperator
  36996. protected:
  36997. /** @internal */
  36998. void paint (Graphics& g);
  36999. /** @internal */
  37000. void mouseEnter (const MouseEvent& e);
  37001. /** @internal */
  37002. void mouseMove (const MouseEvent& e);
  37003. /** @internal */
  37004. void mouseDown (const MouseEvent& e);
  37005. /** @internal */
  37006. void mouseDrag (const MouseEvent& e);
  37007. /** @internal */
  37008. void mouseUp (const MouseEvent& e);
  37009. /** @internal */
  37010. bool hitTest (int x, int y);
  37011. private:
  37012. Component::SafePointer<Component> component;
  37013. ComponentBoundsConstrainer* constrainer;
  37014. BorderSize borderSize;
  37015. Rectangle<int> originalBounds;
  37016. Zone mouseZone;
  37017. void updateMouseZone (const MouseEvent& e);
  37018. ResizableBorderComponent (const ResizableBorderComponent&);
  37019. ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  37020. };
  37021. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  37022. /*** End of inlined file: juce_ResizableBorderComponent.h ***/
  37023. /*** Start of inlined file: juce_ResizableCornerComponent.h ***/
  37024. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37025. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37026. /** A component that resizes a parent window when dragged.
  37027. This is the small triangular stripey resizer component you get in the bottom-right
  37028. of windows (more commonly on the Mac than Windows). Put one in the corner of
  37029. a larger component and it will automatically resize its parent when it gets dragged
  37030. around.
  37031. @see ResizableFrameComponent
  37032. */
  37033. class JUCE_API ResizableCornerComponent : public Component
  37034. {
  37035. public:
  37036. /** Creates a resizer.
  37037. Pass in the target component which you want to be resized when this one is
  37038. dragged.
  37039. The target component will usually be a parent of the resizer component, but this
  37040. isn't mandatory.
  37041. Remember that when the target component is resized, it'll need to move and
  37042. resize this component to keep it in place, as this won't happen automatically.
  37043. If the constrainer parameter is non-zero, then this object will be used to enforce
  37044. limits on the size and position that the component can be stretched to. Make sure
  37045. that the constrainer isn't deleted while still in use by this object. If you
  37046. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  37047. @see ComponentBoundsConstrainer
  37048. */
  37049. ResizableCornerComponent (Component* componentToResize,
  37050. ComponentBoundsConstrainer* constrainer);
  37051. /** Destructor. */
  37052. ~ResizableCornerComponent();
  37053. juce_UseDebuggingNewOperator
  37054. protected:
  37055. /** @internal */
  37056. void paint (Graphics& g);
  37057. /** @internal */
  37058. void mouseDown (const MouseEvent& e);
  37059. /** @internal */
  37060. void mouseDrag (const MouseEvent& e);
  37061. /** @internal */
  37062. void mouseUp (const MouseEvent& e);
  37063. /** @internal */
  37064. bool hitTest (int x, int y);
  37065. private:
  37066. Component::SafePointer<Component> component;
  37067. ComponentBoundsConstrainer* constrainer;
  37068. Rectangle<int> originalBounds;
  37069. ResizableCornerComponent (const ResizableCornerComponent&);
  37070. ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  37071. };
  37072. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37073. /*** End of inlined file: juce_ResizableCornerComponent.h ***/
  37074. /**
  37075. A base class for top-level windows that can be dragged around and resized.
  37076. To add content to the window, use its setContentComponent() method to
  37077. give it a component that will remain positioned inside it (leaving a gap around
  37078. the edges for a border).
  37079. It's not advisable to add child components directly to a ResizableWindow: put them
  37080. inside your content component instead. And overriding methods like resized(), moved(), etc
  37081. is also not recommended - instead override these methods for your content component.
  37082. (If for some obscure reason you do need to override these methods, always remember to
  37083. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  37084. decorations correctly).
  37085. By default resizing isn't enabled - use the setResizable() method to enable it and
  37086. to choose the style of resizing to use.
  37087. @see TopLevelWindow
  37088. */
  37089. class JUCE_API ResizableWindow : public TopLevelWindow
  37090. {
  37091. public:
  37092. /** Creates a ResizableWindow.
  37093. This constructor doesn't specify a background colour, so the LookAndFeel's default
  37094. background colour will be used.
  37095. @param name the name to give the component
  37096. @param addToDesktop if true, the window will be automatically added to the
  37097. desktop; if false, you can use it as a child component
  37098. */
  37099. ResizableWindow (const String& name,
  37100. bool addToDesktop);
  37101. /** Creates a ResizableWindow.
  37102. @param name the name to give the component
  37103. @param backgroundColour the colour to use for filling the window's background.
  37104. @param addToDesktop if true, the window will be automatically added to the
  37105. desktop; if false, you can use it as a child component
  37106. */
  37107. ResizableWindow (const String& name,
  37108. const Colour& backgroundColour,
  37109. bool addToDesktop);
  37110. /** Destructor.
  37111. If a content component has been set with setContentComponent(), it
  37112. will be deleted.
  37113. */
  37114. ~ResizableWindow();
  37115. /** Returns the colour currently being used for the window's background.
  37116. As a convenience the window will fill itself with this colour, but you
  37117. can override the paint() method if you need more customised behaviour.
  37118. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  37119. @see setBackgroundColour
  37120. */
  37121. const Colour getBackgroundColour() const throw();
  37122. /** Changes the colour currently being used for the window's background.
  37123. As a convenience the window will fill itself with this colour, but you
  37124. can override the paint() method if you need more customised behaviour.
  37125. Note that the opaque state of this window is altered by this call to reflect
  37126. the opacity of the colour passed-in. On window systems which can't support
  37127. semi-transparent windows this might cause problems, (though it's unlikely you'll
  37128. be using this class as a base for a semi-transparent component anyway).
  37129. You can also use the ResizableWindow::backgroundColourId colour id to set
  37130. this colour.
  37131. @see getBackgroundColour
  37132. */
  37133. void setBackgroundColour (const Colour& newColour);
  37134. /** Make the window resizable or fixed.
  37135. @param shouldBeResizable whether it's resizable at all
  37136. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  37137. bottom-right; if false, it'll use a ResizableBorderComponent
  37138. around the edge
  37139. @see setResizeLimits, isResizable
  37140. */
  37141. void setResizable (bool shouldBeResizable,
  37142. bool useBottomRightCornerResizer);
  37143. /** True if resizing is enabled.
  37144. @see setResizable
  37145. */
  37146. bool isResizable() const throw();
  37147. /** This sets the maximum and minimum sizes for the window.
  37148. If the window's current size is outside these limits, it will be resized to
  37149. make sure it's within them.
  37150. Calling setBounds() on the component will bypass any size checking - it's only when
  37151. the window is being resized by the user that these values are enforced.
  37152. @see setResizable, setFixedAspectRatio
  37153. */
  37154. void setResizeLimits (int newMinimumWidth,
  37155. int newMinimumHeight,
  37156. int newMaximumWidth,
  37157. int newMaximumHeight) throw();
  37158. /** Returns the bounds constrainer object that this window is using.
  37159. You can access this to change its properties.
  37160. */
  37161. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  37162. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  37163. A pointer to the object you pass in will be kept, but it won't be deleted
  37164. by this object, so it's the caller's responsiblity to manage it.
  37165. If you pass 0, then no contraints will be placed on the positioning of the window.
  37166. */
  37167. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  37168. /** Calls the window's setBounds method, after first checking these bounds
  37169. with the current constrainer.
  37170. @see setConstrainer
  37171. */
  37172. void setBoundsConstrained (const Rectangle<int>& bounds);
  37173. /** Returns true if the window is currently in full-screen mode.
  37174. @see setFullScreen
  37175. */
  37176. bool isFullScreen() const;
  37177. /** Puts the window into full-screen mode, or restores it to its normal size.
  37178. If true, the window will become full-screen; if false, it will return to the
  37179. last size it was before being made full-screen.
  37180. @see isFullScreen
  37181. */
  37182. void setFullScreen (bool shouldBeFullScreen);
  37183. /** Returns true if the window is currently minimised.
  37184. @see setMinimised
  37185. */
  37186. bool isMinimised() const;
  37187. /** Minimises the window, or restores it to its previous position and size.
  37188. When being un-minimised, it'll return to the last position and size it
  37189. was in before being minimised.
  37190. @see isMinimised
  37191. */
  37192. void setMinimised (bool shouldMinimise);
  37193. /** Returns a string which encodes the window's current size and position.
  37194. This string will encapsulate the window's size, position, and whether it's
  37195. in full-screen mode. It's intended for letting your application save and
  37196. restore a window's position.
  37197. Use the restoreWindowStateFromString() to restore from a saved state.
  37198. @see restoreWindowStateFromString
  37199. */
  37200. const String getWindowStateAsString();
  37201. /** Restores the window to a previously-saved size and position.
  37202. This restores the window's size, positon and full-screen status from an
  37203. string that was previously created with the getWindowStateAsString()
  37204. method.
  37205. @returns false if the string wasn't a valid window state
  37206. @see getWindowStateAsString
  37207. */
  37208. bool restoreWindowStateFromString (const String& previousState);
  37209. /** Returns the current content component.
  37210. This will be the component set by setContentComponent(), or 0 if none
  37211. has yet been specified.
  37212. @see setContentComponent
  37213. */
  37214. Component* getContentComponent() const throw() { return contentComponent; }
  37215. /** Changes the current content component.
  37216. This sets a component that will be placed in the centre of the ResizableWindow,
  37217. (leaving a space around the edge for the border).
  37218. You should never add components directly to a ResizableWindow (or any of its subclasses)
  37219. with addChildComponent(). Instead, add them to the content component.
  37220. @param newContentComponent the new component to use (or null to not use one) - this
  37221. component will be deleted either when replaced by another call
  37222. to this method, or when the ResizableWindow is deleted.
  37223. To remove a content component without deleting it, use
  37224. setContentComponent (0, false).
  37225. @param deleteOldOne if true, the previous content component will be deleted; if
  37226. false, the previous component will just be removed without
  37227. deleting it.
  37228. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  37229. it always fits around the size of the content component. If false, the
  37230. new content will be resized to fit the current space available.
  37231. */
  37232. void setContentComponent (Component* newContentComponent,
  37233. bool deleteOldOne = true,
  37234. bool resizeToFit = false);
  37235. /** Changes the window so that the content component ends up with the specified size.
  37236. This is basically a setSize call on the window, but which adds on the borders,
  37237. so you can specify the content component's target size.
  37238. */
  37239. void setContentComponentSize (int width, int height);
  37240. /** A set of colour IDs to use to change the colour of various aspects of the window.
  37241. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37242. methods.
  37243. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37244. */
  37245. enum ColourIds
  37246. {
  37247. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  37248. };
  37249. juce_UseDebuggingNewOperator
  37250. protected:
  37251. /** @internal */
  37252. void paint (Graphics& g);
  37253. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  37254. void moved();
  37255. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  37256. void resized();
  37257. /** @internal */
  37258. void mouseDown (const MouseEvent& e);
  37259. /** @internal */
  37260. void mouseDrag (const MouseEvent& e);
  37261. /** @internal */
  37262. void lookAndFeelChanged();
  37263. /** @internal */
  37264. void childBoundsChanged (Component* child);
  37265. /** @internal */
  37266. void parentSizeChanged();
  37267. /** @internal */
  37268. void visibilityChanged();
  37269. /** @internal */
  37270. void activeWindowStatusChanged();
  37271. /** @internal */
  37272. int getDesktopWindowStyleFlags() const;
  37273. /** Returns the width of the border to use around the window.
  37274. @see getContentComponentBorder
  37275. */
  37276. virtual const BorderSize getBorderThickness();
  37277. /** Returns the insets to use when positioning the content component.
  37278. @see getBorderThickness
  37279. */
  37280. virtual const BorderSize getContentComponentBorder();
  37281. #if JUCE_DEBUG
  37282. /** Overridden to warn people about adding components directly to this component
  37283. instead of using setContentComponent().
  37284. If you know what you're doing and are sure you really want to add a component, specify
  37285. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  37286. */
  37287. void addChildComponent (Component* child, int zOrder = -1);
  37288. /** Overridden to warn people about adding components directly to this component
  37289. instead of using setContentComponent().
  37290. If you know what you're doing and are sure you really want to add a component, specify
  37291. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  37292. */
  37293. void addAndMakeVisible (Component* child, int zOrder = -1);
  37294. #endif
  37295. ScopedPointer <ResizableCornerComponent> resizableCorner;
  37296. ScopedPointer <ResizableBorderComponent> resizableBorder;
  37297. private:
  37298. ScopedPointer <Component> contentComponent;
  37299. bool resizeToFitContent, fullscreen;
  37300. ComponentDragger dragger;
  37301. Rectangle<int> lastNonFullScreenPos;
  37302. ComponentBoundsConstrainer defaultConstrainer;
  37303. ComponentBoundsConstrainer* constrainer;
  37304. #if JUCE_DEBUG
  37305. bool hasBeenResized;
  37306. #endif
  37307. void updateLastPos();
  37308. ResizableWindow (const ResizableWindow&);
  37309. ResizableWindow& operator= (const ResizableWindow&);
  37310. // (xxx remove these eventually)
  37311. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  37312. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  37313. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  37314. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  37315. };
  37316. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  37317. /*** End of inlined file: juce_ResizableWindow.h ***/
  37318. /*** Start of inlined file: juce_GlyphArrangement.h ***/
  37319. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  37320. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  37321. /**
  37322. A glyph from a particular font, with a particular size, style,
  37323. typeface and position.
  37324. @see GlyphArrangement, Font
  37325. */
  37326. class JUCE_API PositionedGlyph
  37327. {
  37328. public:
  37329. PositionedGlyph (const PositionedGlyph& other);
  37330. /** Returns the character the glyph represents. */
  37331. juce_wchar getCharacter() const { return character; }
  37332. /** Checks whether the glyph is actually empty. */
  37333. bool isWhitespace() const { return CharacterFunctions::isWhitespace (character); }
  37334. /** Returns the position of the glyph's left-hand edge. */
  37335. float getLeft() const { return x; }
  37336. /** Returns the position of the glyph's right-hand edge. */
  37337. float getRight() const { return x + w; }
  37338. /** Returns the y position of the glyph's baseline. */
  37339. float getBaselineY() const { return y; }
  37340. /** Returns the y position of the top of the glyph. */
  37341. float getTop() const { return y - font.getAscent(); }
  37342. /** Returns the y position of the bottom of the glyph. */
  37343. float getBottom() const { return y + font.getDescent(); }
  37344. /** Returns the bounds of the glyph. */
  37345. const Rectangle<float> getBounds() const { return Rectangle<float> (x, getTop(), w, font.getHeight()); }
  37346. /** Shifts the glyph's position by a relative amount. */
  37347. void moveBy (float deltaX, float deltaY);
  37348. /** Draws the glyph into a graphics context. */
  37349. void draw (const Graphics& g) const;
  37350. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  37351. void draw (const Graphics& g, const AffineTransform& transform) const;
  37352. /** Returns the path for this glyph.
  37353. @param path the glyph's outline will be appended to this path
  37354. */
  37355. void createPath (Path& path) const;
  37356. /** Checks to see if a point lies within this glyph. */
  37357. bool hitTest (float x, float y) const;
  37358. juce_UseDebuggingNewOperator
  37359. private:
  37360. friend class GlyphArrangement;
  37361. float x, y, w;
  37362. Font font;
  37363. juce_wchar character;
  37364. int glyph;
  37365. PositionedGlyph (float x, float y, float w, const Font& font, juce_wchar character, int glyph);
  37366. };
  37367. /**
  37368. A set of glyphs, each with a position.
  37369. You can create a GlyphArrangement, text to it and then draw it onto a
  37370. graphics context. It's used internally by the text methods in the
  37371. Graphics class, but can be used directly if more control is needed.
  37372. @see Font, PositionedGlyph
  37373. */
  37374. class JUCE_API GlyphArrangement
  37375. {
  37376. public:
  37377. /** Creates an empty arrangement. */
  37378. GlyphArrangement();
  37379. /** Takes a copy of another arrangement. */
  37380. GlyphArrangement (const GlyphArrangement& other);
  37381. /** Copies another arrangement onto this one.
  37382. To add another arrangement without clearing this one, use addGlyphArrangement().
  37383. */
  37384. GlyphArrangement& operator= (const GlyphArrangement& other);
  37385. /** Destructor. */
  37386. ~GlyphArrangement();
  37387. /** Returns the total number of glyphs in the arrangement. */
  37388. int getNumGlyphs() const throw() { return glyphs.size(); }
  37389. /** Returns one of the glyphs from the arrangement.
  37390. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  37391. careful not to pass an out-of-range index here, as it
  37392. doesn't do any bounds-checking.
  37393. */
  37394. PositionedGlyph& getGlyph (int index) const;
  37395. /** Clears all text from the arrangement and resets it.
  37396. */
  37397. void clear();
  37398. /** Appends a line of text to the arrangement.
  37399. This will add the text as a single line, where x is the left-hand edge of the
  37400. first character, and y is the position for the text's baseline.
  37401. If the text contains new-lines or carriage-returns, this will ignore them - use
  37402. addJustifiedText() to add multi-line arrangements.
  37403. */
  37404. void addLineOfText (const Font& font,
  37405. const String& text,
  37406. float x, float y);
  37407. /** Adds a line of text, truncating it if it's wider than a specified size.
  37408. This is the same as addLineOfText(), but if the line's width exceeds the value
  37409. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  37410. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  37411. */
  37412. void addCurtailedLineOfText (const Font& font,
  37413. const String& text,
  37414. float x, float y,
  37415. float maxWidthPixels,
  37416. bool useEllipsis);
  37417. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  37418. This will add text to the arrangement, breaking it into new lines either where there
  37419. is a new-line or carriage-return character in the text, or where a line's width
  37420. exceeds the value set in maxLineWidth.
  37421. Each line that is added will be laid out using the flags set in horizontalLayout, so
  37422. the lines can be left- or right-justified, or centred horizontally in the space
  37423. between x and (x + maxLineWidth).
  37424. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  37425. lines will be placed below it, separated by a distance of font.getHeight().
  37426. */
  37427. void addJustifiedText (const Font& font,
  37428. const String& text,
  37429. float x, float y,
  37430. float maxLineWidth,
  37431. const Justification& horizontalLayout);
  37432. /** Tries to fit some text withing a given space.
  37433. This does its best to make the given text readable within the specified rectangle,
  37434. so it useful for labelling things.
  37435. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  37436. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  37437. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  37438. it's been truncated.
  37439. A Justification parameter lets you specify how the text is laid out within the rectangle,
  37440. both horizontally and vertically.
  37441. @see Graphics::drawFittedText
  37442. */
  37443. void addFittedText (const Font& font,
  37444. const String& text,
  37445. float x, float y, float width, float height,
  37446. const Justification& layout,
  37447. int maximumLinesToUse,
  37448. float minimumHorizontalScale = 0.7f);
  37449. /** Appends another glyph arrangement to this one. */
  37450. void addGlyphArrangement (const GlyphArrangement& other);
  37451. /** Draws this glyph arrangement to a graphics context.
  37452. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  37453. method, which renders the glyphs as filled vectors.
  37454. */
  37455. void draw (const Graphics& g) const;
  37456. /** Draws this glyph arrangement to a graphics context.
  37457. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  37458. method for non-transformed arrangements.
  37459. */
  37460. void draw (const Graphics& g, const AffineTransform& transform) const;
  37461. /** Converts the set of glyphs into a path.
  37462. @param path the glyphs' outlines will be appended to this path
  37463. */
  37464. void createPath (Path& path) const;
  37465. /** Looks for a glyph that contains the given co-ordinate.
  37466. @returns the index of the glyph, or -1 if none were found.
  37467. */
  37468. int findGlyphIndexAt (float x, float y) const;
  37469. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  37470. @param startIndex the first glyph to test
  37471. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  37472. startIndex will be included
  37473. @param includeWhitespace if true, the extent of any whitespace characters will also
  37474. be taken into account
  37475. */
  37476. const Rectangle<float> getBoundingBox (int startIndex, int numGlyphs, bool includeWhitespace) const;
  37477. /** Shifts a set of glyphs by a given amount.
  37478. @param startIndex the first glyph to transform
  37479. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  37480. startIndex will be used
  37481. @param deltaX the amount to add to their x-positions
  37482. @param deltaY the amount to add to their y-positions
  37483. */
  37484. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  37485. float deltaX, float deltaY);
  37486. /** Removes a set of glyphs from the arrangement.
  37487. @param startIndex the first glyph to remove
  37488. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  37489. startIndex will be deleted
  37490. */
  37491. void removeRangeOfGlyphs (int startIndex, int numGlyphs);
  37492. /** Expands or compresses a set of glyphs horizontally.
  37493. @param startIndex the first glyph to transform
  37494. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  37495. startIndex will be used
  37496. @param horizontalScaleFactor how much to scale their horizontal width by
  37497. */
  37498. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  37499. float horizontalScaleFactor);
  37500. /** Justifies a set of glyphs within a given space.
  37501. This moves the glyphs as a block so that the whole thing is located within the
  37502. given rectangle with the specified layout.
  37503. If the Justification::horizontallyJustified flag is specified, each line will
  37504. be stretched out to fill the specified width.
  37505. */
  37506. void justifyGlyphs (int startIndex, int numGlyphs,
  37507. float x, float y, float width, float height,
  37508. const Justification& justification);
  37509. juce_UseDebuggingNewOperator
  37510. private:
  37511. OwnedArray <PositionedGlyph> glyphs;
  37512. int insertEllipsis (const Font& font, float maxXPos, int startIndex, int endIndex);
  37513. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  37514. const Justification& justification, float minimumHorizontalScale);
  37515. void spreadOutLine (int start, int numGlyphs, float targetWidth);
  37516. };
  37517. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  37518. /*** End of inlined file: juce_GlyphArrangement.h ***/
  37519. /**
  37520. A file open/save dialog box.
  37521. This is a Juce-based file dialog box; to use a native file chooser, see the
  37522. FileChooser class.
  37523. To use one of these, create it and call its show() method. e.g.
  37524. @code
  37525. {
  37526. WildcardFileFilter wildcardFilter ("*.foo", "Foo files");
  37527. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  37528. File::nonexistent,
  37529. &wildcardFilter,
  37530. 0);
  37531. FileChooserDialogBox dialogBox ("Open some kind of file",
  37532. "Please choose some kind of file that you want to open...",
  37533. browser,
  37534. getLookAndFeel().alertWindowBackground);
  37535. if (dialogBox.show())
  37536. {
  37537. File selectedFile = browser.getCurrentFile();
  37538. ...
  37539. }
  37540. }
  37541. @endcode
  37542. @see FileChooser
  37543. */
  37544. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  37545. public ButtonListener,
  37546. public FileBrowserListener
  37547. {
  37548. public:
  37549. /** Creates a file chooser box.
  37550. @param title the main title to show at the top of the box
  37551. @param instructions an optional longer piece of text to show below the title in
  37552. a smaller font, describing in more detail what's required.
  37553. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  37554. box. Make sure you delete this after (but not before!) the
  37555. dialog box has been deleted.
  37556. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  37557. if they try to select a file that already exists. (This
  37558. flag is only used when saving files)
  37559. @param backgroundColour the background colour for the top level window
  37560. @see FileBrowserComponent, FilePreviewComponent
  37561. */
  37562. FileChooserDialogBox (const String& title,
  37563. const String& instructions,
  37564. FileBrowserComponent& browserComponent,
  37565. bool warnAboutOverwritingExistingFiles,
  37566. const Colour& backgroundColour);
  37567. /** Destructor. */
  37568. ~FileChooserDialogBox();
  37569. /** Displays and runs the dialog box modally.
  37570. This will show the box with the specified size, returning true if the user
  37571. pressed 'ok', or false if they cancelled.
  37572. Leave the width or height as 0 to use the default size
  37573. */
  37574. bool show (int width = 0,int height = 0);
  37575. /** A set of colour IDs to use to change the colour of various aspects of the box.
  37576. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37577. methods.
  37578. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37579. */
  37580. enum ColourIds
  37581. {
  37582. titleTextColourId = 0x1000850, /**< The colour to use to draw the box's title. */
  37583. };
  37584. /** @internal */
  37585. void buttonClicked (Button* button);
  37586. /** @internal */
  37587. void closeButtonPressed();
  37588. /** @internal */
  37589. void selectionChanged();
  37590. /** @internal */
  37591. void fileClicked (const File& file, const MouseEvent& e);
  37592. /** @internal */
  37593. void fileDoubleClicked (const File& file);
  37594. juce_UseDebuggingNewOperator
  37595. private:
  37596. class ContentComponent : public Component
  37597. {
  37598. public:
  37599. ContentComponent();
  37600. ~ContentComponent();
  37601. void paint (Graphics& g);
  37602. void resized();
  37603. String instructions;
  37604. GlyphArrangement text;
  37605. FileBrowserComponent* chooserComponent;
  37606. FilePreviewComponent* previewComponent;
  37607. TextButton* okButton;
  37608. TextButton* cancelButton;
  37609. };
  37610. ContentComponent* content;
  37611. const bool warnAboutOverwritingExistingFiles;
  37612. FileChooserDialogBox (const FileChooserDialogBox&);
  37613. FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  37614. };
  37615. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37616. /*** End of inlined file: juce_FileChooserDialogBox.h ***/
  37617. #endif
  37618. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  37619. #endif
  37620. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37621. /*** Start of inlined file: juce_FileListComponent.h ***/
  37622. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37623. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37624. /**
  37625. A component that displays the files in a directory as a listbox.
  37626. This implements the DirectoryContentsDisplayComponent base class so that
  37627. it can be used in a FileBrowserComponent.
  37628. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37629. class and the FileBrowserListener class.
  37630. @see DirectoryContentsList, FileTreeComponent
  37631. */
  37632. class JUCE_API FileListComponent : public ListBox,
  37633. public DirectoryContentsDisplayComponent,
  37634. private ListBoxModel,
  37635. private ChangeListener
  37636. {
  37637. public:
  37638. /** Creates a listbox to show the contents of a specified directory.
  37639. */
  37640. FileListComponent (DirectoryContentsList& listToShow);
  37641. /** Destructor. */
  37642. ~FileListComponent();
  37643. /** Returns the number of files the user has got selected.
  37644. @see getSelectedFile
  37645. */
  37646. int getNumSelectedFiles() const;
  37647. /** Returns one of the files that the user has currently selected.
  37648. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  37649. @see getNumSelectedFiles
  37650. */
  37651. const File getSelectedFile (int index = 0) const;
  37652. /** Deselects any files that are currently selected. */
  37653. void deselectAllFiles();
  37654. /** Scrolls to the top of the list. */
  37655. void scrollToTop();
  37656. /** @internal */
  37657. void changeListenerCallback (void*);
  37658. /** @internal */
  37659. int getNumRows();
  37660. /** @internal */
  37661. void paintListBoxItem (int, Graphics&, int, int, bool);
  37662. /** @internal */
  37663. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  37664. /** @internal */
  37665. void selectedRowsChanged (int lastRowSelected);
  37666. /** @internal */
  37667. void deleteKeyPressed (int currentSelectedRow);
  37668. /** @internal */
  37669. void returnKeyPressed (int currentSelectedRow);
  37670. juce_UseDebuggingNewOperator
  37671. private:
  37672. FileListComponent (const FileListComponent&);
  37673. FileListComponent& operator= (const FileListComponent&);
  37674. File lastDirectory;
  37675. };
  37676. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37677. /*** End of inlined file: juce_FileListComponent.h ***/
  37678. #endif
  37679. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37680. /*** Start of inlined file: juce_FilenameComponent.h ***/
  37681. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37682. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37683. class FilenameComponent;
  37684. /**
  37685. Listens for events happening to a FilenameComponent.
  37686. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  37687. register one of these objects for event callbacks when the filename is changed.
  37688. @see FilenameComponent
  37689. */
  37690. class JUCE_API FilenameComponentListener
  37691. {
  37692. public:
  37693. /** Destructor. */
  37694. virtual ~FilenameComponentListener() {}
  37695. /** This method is called after the FilenameComponent's file has been changed. */
  37696. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  37697. };
  37698. /**
  37699. Shows a filename as an editable text box, with a 'browse' button and a
  37700. drop-down list for recently selected files.
  37701. A handy component for dialogue boxes where you want the user to be able to
  37702. select a file or directory.
  37703. Attach an FilenameComponentListener using the addListener() method, and it will
  37704. get called each time the user changes the filename, either by browsing for a file
  37705. and clicking 'ok', or by typing a new filename into the box and pressing return.
  37706. @see FileChooser, ComboBox
  37707. */
  37708. class JUCE_API FilenameComponent : public Component,
  37709. public SettableTooltipClient,
  37710. public FileDragAndDropTarget,
  37711. private AsyncUpdater,
  37712. private ButtonListener,
  37713. private ComboBoxListener
  37714. {
  37715. public:
  37716. /** Creates a FilenameComponent.
  37717. @param name the name for this component.
  37718. @param currentFile the file to initially show in the box
  37719. @param canEditFilename if true, the user can manually edit the filename; if false,
  37720. they can only change it by browsing for a new file
  37721. @param isDirectory if true, the file will be treated as a directory, and
  37722. an appropriate directory browser used
  37723. @param isForSaving if true, the file browser will allow non-existent files to
  37724. be picked, as the file is assumed to be used for saving rather
  37725. than loading
  37726. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  37727. If an empty string is passed in, then the pattern is assumed to be "*"
  37728. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  37729. to any filenames that are entered or chosen
  37730. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  37731. will only appear if the initial file isn't valid)
  37732. */
  37733. FilenameComponent (const String& name,
  37734. const File& currentFile,
  37735. bool canEditFilename,
  37736. bool isDirectory,
  37737. bool isForSaving,
  37738. const String& fileBrowserWildcard,
  37739. const String& enforcedSuffix,
  37740. const String& textWhenNothingSelected);
  37741. /** Destructor. */
  37742. ~FilenameComponent();
  37743. /** Returns the currently displayed filename. */
  37744. const File getCurrentFile() const;
  37745. /** Changes the current filename.
  37746. If addToRecentlyUsedList is true, the filename will also be added to the
  37747. drop-down list of recent files.
  37748. If sendChangeNotification is false, then the listeners won't be told of the
  37749. change.
  37750. */
  37751. void setCurrentFile (File newFile,
  37752. bool addToRecentlyUsedList,
  37753. bool sendChangeNotification = true);
  37754. /** Changes whether the use can type into the filename box.
  37755. */
  37756. void setFilenameIsEditable (bool shouldBeEditable);
  37757. /** Sets a file or directory to be the default starting point for the browser to show.
  37758. This is only used if the current file hasn't been set.
  37759. */
  37760. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  37761. /** Returns all the entries on the recent files list.
  37762. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  37763. state of this list.
  37764. @see setRecentlyUsedFilenames
  37765. */
  37766. const StringArray getRecentlyUsedFilenames() const;
  37767. /** Sets all the entries on the recent files list.
  37768. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  37769. state of this list.
  37770. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  37771. */
  37772. void setRecentlyUsedFilenames (const StringArray& filenames);
  37773. /** Adds an entry to the recently-used files dropdown list.
  37774. If the file is already in the list, it will be moved to the top. A limit
  37775. is also placed on the number of items that are kept in the list.
  37776. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  37777. */
  37778. void addRecentlyUsedFile (const File& file);
  37779. /** Changes the limit for the number of files that will be stored in the recent-file list.
  37780. */
  37781. void setMaxNumberOfRecentFiles (int newMaximum);
  37782. /** Changes the text shown on the 'browse' button.
  37783. By default this button just says "..." but you can change it. The button itself
  37784. can be changed using the look-and-feel classes, so it might not actually have any
  37785. text on it.
  37786. */
  37787. void setBrowseButtonText (const String& browseButtonText);
  37788. /** Adds a listener that will be called when the selected file is changed. */
  37789. void addListener (FilenameComponentListener* listener);
  37790. /** Removes a previously-registered listener. */
  37791. void removeListener (FilenameComponentListener* listener);
  37792. /** Gives the component a tooltip. */
  37793. void setTooltip (const String& newTooltip);
  37794. /** @internal */
  37795. void paintOverChildren (Graphics& g);
  37796. /** @internal */
  37797. void resized();
  37798. /** @internal */
  37799. void lookAndFeelChanged();
  37800. /** @internal */
  37801. bool isInterestedInFileDrag (const StringArray& files);
  37802. /** @internal */
  37803. void filesDropped (const StringArray& files, int, int);
  37804. /** @internal */
  37805. void fileDragEnter (const StringArray& files, int, int);
  37806. /** @internal */
  37807. void fileDragExit (const StringArray& files);
  37808. juce_UseDebuggingNewOperator
  37809. private:
  37810. ComboBox filenameBox;
  37811. String lastFilename;
  37812. ScopedPointer<Button> browseButton;
  37813. int maxRecentFiles;
  37814. bool isDir, isSaving, isFileDragOver;
  37815. String wildcard, enforcedSuffix, browseButtonText;
  37816. ListenerList <FilenameComponentListener> listeners;
  37817. File defaultBrowseFile;
  37818. void comboBoxChanged (ComboBox*);
  37819. void buttonClicked (Button* button);
  37820. void handleAsyncUpdate();
  37821. FilenameComponent (const FilenameComponent&);
  37822. FilenameComponent& operator= (const FilenameComponent&);
  37823. };
  37824. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37825. /*** End of inlined file: juce_FilenameComponent.h ***/
  37826. #endif
  37827. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37828. #endif
  37829. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37830. /*** Start of inlined file: juce_FileSearchPathListComponent.h ***/
  37831. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37832. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37833. /**
  37834. Shows a set of file paths in a list, allowing them to be added, removed or
  37835. re-ordered.
  37836. @see FileSearchPath
  37837. */
  37838. class JUCE_API FileSearchPathListComponent : public Component,
  37839. public SettableTooltipClient,
  37840. public FileDragAndDropTarget,
  37841. private ButtonListener,
  37842. private ListBoxModel
  37843. {
  37844. public:
  37845. /** Creates an empty FileSearchPathListComponent.
  37846. */
  37847. FileSearchPathListComponent();
  37848. /** Destructor. */
  37849. ~FileSearchPathListComponent();
  37850. /** Returns the path as it is currently shown. */
  37851. const FileSearchPath& getPath() const throw() { return path; }
  37852. /** Changes the current path. */
  37853. void setPath (const FileSearchPath& newPath);
  37854. /** Sets a file or directory to be the default starting point for the browser to show.
  37855. This is only used if the current file hasn't been set.
  37856. */
  37857. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  37858. /** A set of colour IDs to use to change the colour of various aspects of the label.
  37859. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37860. methods.
  37861. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37862. */
  37863. enum ColourIds
  37864. {
  37865. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  37866. Make this transparent if you don't want the background to be filled. */
  37867. };
  37868. /** @internal */
  37869. int getNumRows();
  37870. /** @internal */
  37871. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  37872. /** @internal */
  37873. void deleteKeyPressed (int lastRowSelected);
  37874. /** @internal */
  37875. void returnKeyPressed (int lastRowSelected);
  37876. /** @internal */
  37877. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  37878. /** @internal */
  37879. void selectedRowsChanged (int lastRowSelected);
  37880. /** @internal */
  37881. void resized();
  37882. /** @internal */
  37883. void paint (Graphics& g);
  37884. /** @internal */
  37885. bool isInterestedInFileDrag (const StringArray& files);
  37886. /** @internal */
  37887. void filesDropped (const StringArray& files, int, int);
  37888. /** @internal */
  37889. void buttonClicked (Button* button);
  37890. juce_UseDebuggingNewOperator
  37891. private:
  37892. FileSearchPath path;
  37893. File defaultBrowseTarget;
  37894. ListBox* listBox;
  37895. Button* addButton;
  37896. Button* removeButton;
  37897. TextButton* changeButton;
  37898. DrawableButton* upButton;
  37899. DrawableButton* downButton;
  37900. void changed();
  37901. void updateButtons();
  37902. FileSearchPathListComponent (const FileSearchPathListComponent&);
  37903. FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  37904. };
  37905. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37906. /*** End of inlined file: juce_FileSearchPathListComponent.h ***/
  37907. #endif
  37908. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37909. /*** Start of inlined file: juce_FileTreeComponent.h ***/
  37910. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37911. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37912. /**
  37913. A component that displays the files in a directory as a treeview.
  37914. This implements the DirectoryContentsDisplayComponent base class so that
  37915. it can be used in a FileBrowserComponent.
  37916. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37917. class and the FileBrowserListener class.
  37918. @see DirectoryContentsList, FileListComponent
  37919. */
  37920. class JUCE_API FileTreeComponent : public TreeView,
  37921. public DirectoryContentsDisplayComponent
  37922. {
  37923. public:
  37924. /** Creates a listbox to show the contents of a specified directory.
  37925. */
  37926. FileTreeComponent (DirectoryContentsList& listToShow);
  37927. /** Destructor. */
  37928. ~FileTreeComponent();
  37929. /** Returns the number of files the user has got selected.
  37930. @see getSelectedFile
  37931. */
  37932. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  37933. /** Returns one of the files that the user has currently selected.
  37934. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  37935. @see getNumSelectedFiles
  37936. */
  37937. const File getSelectedFile (int index = 0) const;
  37938. /** Deselects any files that are currently selected. */
  37939. void deselectAllFiles();
  37940. /** Scrolls the list to the top. */
  37941. void scrollToTop();
  37942. /** Setting a name for this allows tree items to be dragged.
  37943. The string that you pass in here will be returned by the getDragSourceDescription()
  37944. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  37945. */
  37946. void setDragAndDropDescription (const String& description);
  37947. /** Returns the last value that was set by setDragAndDropDescription().
  37948. */
  37949. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  37950. juce_UseDebuggingNewOperator
  37951. private:
  37952. String dragAndDropDescription;
  37953. FileTreeComponent (const FileTreeComponent&);
  37954. FileTreeComponent& operator= (const FileTreeComponent&);
  37955. };
  37956. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37957. /*** End of inlined file: juce_FileTreeComponent.h ***/
  37958. #endif
  37959. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37960. /*** Start of inlined file: juce_ImagePreviewComponent.h ***/
  37961. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37962. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37963. /**
  37964. A simple preview component that shows thumbnails of image files.
  37965. @see FileChooserDialogBox, FilePreviewComponent
  37966. */
  37967. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  37968. private Timer
  37969. {
  37970. public:
  37971. /** Creates an ImagePreviewComponent. */
  37972. ImagePreviewComponent();
  37973. /** Destructor. */
  37974. ~ImagePreviewComponent();
  37975. /** @internal */
  37976. void selectedFileChanged (const File& newSelectedFile);
  37977. /** @internal */
  37978. void paint (Graphics& g);
  37979. /** @internal */
  37980. void timerCallback();
  37981. juce_UseDebuggingNewOperator
  37982. private:
  37983. File fileToLoad;
  37984. Image currentThumbnail;
  37985. String currentDetails;
  37986. void getThumbSize (int& w, int& h) const;
  37987. ImagePreviewComponent (const ImagePreviewComponent&);
  37988. ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  37989. };
  37990. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37991. /*** End of inlined file: juce_ImagePreviewComponent.h ***/
  37992. #endif
  37993. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37994. /*** Start of inlined file: juce_WildcardFileFilter.h ***/
  37995. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37996. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37997. /**
  37998. A type of FileFilter that works by wildcard pattern matching.
  37999. This filter only allows files that match one of the specified patterns, but
  38000. allows all directories through.
  38001. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  38002. */
  38003. class JUCE_API WildcardFileFilter : public FileFilter
  38004. {
  38005. public:
  38006. /**
  38007. Creates a wildcard filter for one or more patterns.
  38008. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  38009. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  38010. or .aiff.
  38011. The description is a name to show the user in a list of possible patterns, so
  38012. for the wav/aiff example, your description might be "audio files".
  38013. */
  38014. WildcardFileFilter (const String& fileWildcardPatterns,
  38015. const String& directoryWildcardPatterns,
  38016. const String& description);
  38017. /** Destructor. */
  38018. ~WildcardFileFilter();
  38019. /** Returns true if the filename matches one of the patterns specified. */
  38020. bool isFileSuitable (const File& file) const;
  38021. /** This always returns true. */
  38022. bool isDirectorySuitable (const File& file) const;
  38023. juce_UseDebuggingNewOperator
  38024. private:
  38025. StringArray fileWildcards, directoryWildcards;
  38026. static void parse (const String& pattern, StringArray& result);
  38027. static bool match (const File& file, const StringArray& wildcards);
  38028. };
  38029. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38030. /*** End of inlined file: juce_WildcardFileFilter.h ***/
  38031. #endif
  38032. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  38033. #endif
  38034. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  38035. #endif
  38036. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  38037. #endif
  38038. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  38039. #endif
  38040. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  38041. #endif
  38042. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38043. /*** Start of inlined file: juce_KeyMappingEditorComponent.h ***/
  38044. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38045. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38046. /*** Start of inlined file: juce_KeyPressMappingSet.h ***/
  38047. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38048. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38049. /**
  38050. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  38051. command in a ApplicationCommandManager.
  38052. Normally, you won't actually create a KeyPressMappingSet directly, because
  38053. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  38054. you'd create yourself an ApplicationCommandManager, and call its
  38055. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  38056. KeyPressMappingSet.
  38057. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  38058. to the top-level component for which you want to handle keystrokes. So for example:
  38059. @code
  38060. class MyMainWindow : public Component
  38061. {
  38062. ApplicationCommandManager* myCommandManager;
  38063. public:
  38064. MyMainWindow()
  38065. {
  38066. myCommandManager = new ApplicationCommandManager();
  38067. // first, make sure the command manager has registered all the commands that its
  38068. // targets can perform..
  38069. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  38070. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  38071. // this will use the command manager to initialise the KeyPressMappingSet with
  38072. // the default keypresses that were specified when the targets added their commands
  38073. // to the manager.
  38074. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  38075. // having set up the default key-mappings, you might now want to load the last set
  38076. // of mappings that the user configured.
  38077. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  38078. // Now tell our top-level window to send any keypresses that arrive to the
  38079. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  38080. addKeyListener (myCommandManager->getKeyMappings());
  38081. }
  38082. ...
  38083. }
  38084. @endcode
  38085. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  38086. register to be told when a command or mapping is added, removed, etc.
  38087. There's also a UI component called KeyMappingEditorComponent that can be used
  38088. to easily edit the key mappings.
  38089. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  38090. */
  38091. class JUCE_API KeyPressMappingSet : public KeyListener,
  38092. public ChangeBroadcaster,
  38093. public FocusChangeListener
  38094. {
  38095. public:
  38096. /** Creates a KeyPressMappingSet for a given command manager.
  38097. Normally, you won't actually create a KeyPressMappingSet directly, because
  38098. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  38099. best thing to do is to create your ApplicationCommandManager, and use the
  38100. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  38101. When a suitable keypress happens, the manager's invoke() method will be
  38102. used to invoke the appropriate command.
  38103. @see ApplicationCommandManager
  38104. */
  38105. explicit KeyPressMappingSet (ApplicationCommandManager* commandManager);
  38106. /** Creates an copy of a KeyPressMappingSet. */
  38107. KeyPressMappingSet (const KeyPressMappingSet& other);
  38108. /** Destructor. */
  38109. ~KeyPressMappingSet();
  38110. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  38111. /** Returns a list of keypresses that are assigned to a particular command.
  38112. @param commandID the command's ID
  38113. */
  38114. const Array <KeyPress> getKeyPressesAssignedToCommand (CommandID commandID) const;
  38115. /** Assigns a keypress to a command.
  38116. If the keypress is already assigned to a different command, it will first be
  38117. removed from that command, to avoid it triggering multiple functions.
  38118. @param commandID the ID of the command that you want to add a keypress to. If
  38119. this is 0, the keypress will be removed from anything that it
  38120. was previously assigned to, but not re-assigned
  38121. @param newKeyPress the new key-press
  38122. @param insertIndex if this is less than zero, the key will be appended to the
  38123. end of the list of keypresses; otherwise the new keypress will
  38124. be inserted into the existing list at this index
  38125. */
  38126. void addKeyPress (CommandID commandID,
  38127. const KeyPress& newKeyPress,
  38128. int insertIndex = -1);
  38129. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  38130. @see resetToDefaultMapping
  38131. */
  38132. void resetToDefaultMappings();
  38133. /** Resets all key-mappings to the defaults for a particular command.
  38134. @see resetToDefaultMappings
  38135. */
  38136. void resetToDefaultMapping (CommandID commandID);
  38137. /** Removes all keypresses that are assigned to any commands. */
  38138. void clearAllKeyPresses();
  38139. /** Removes all keypresses that are assigned to a particular command. */
  38140. void clearAllKeyPresses (CommandID commandID);
  38141. /** Removes one of the keypresses that are assigned to a command.
  38142. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  38143. which the keyPressIndex refers.
  38144. */
  38145. void removeKeyPress (CommandID commandID, int keyPressIndex);
  38146. /** Removes a keypress from any command that it may be assigned to.
  38147. */
  38148. void removeKeyPress (const KeyPress& keypress);
  38149. /** Returns true if the given command is linked to this key. */
  38150. bool containsMapping (CommandID commandID, const KeyPress& keyPress) const throw();
  38151. /** Looks for a command that corresponds to a keypress.
  38152. @returns the UID of the command or 0 if none was found
  38153. */
  38154. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  38155. /** Tries to recreate the mappings from a previously stored state.
  38156. The XML passed in must have been created by the createXml() method.
  38157. If the stored state makes any reference to commands that aren't
  38158. currently available, these will be ignored.
  38159. If the set of mappings being loaded was a set of differences (using createXml (true)),
  38160. then this will call resetToDefaultMappings() and then merge the saved mappings
  38161. on top. If the saved set was created with createXml (false), then this method
  38162. will first clear all existing mappings and load the saved ones as a complete set.
  38163. @returns true if it manages to load the XML correctly
  38164. @see createXml
  38165. */
  38166. bool restoreFromXml (const XmlElement& xmlVersion);
  38167. /** Creates an XML representation of the current mappings.
  38168. This will produce a lump of XML that can be later reloaded using
  38169. restoreFromXml() to recreate the current mapping state.
  38170. The object that is returned must be deleted by the caller.
  38171. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  38172. will be saved into the XML. If it's true, then the XML will
  38173. only store the differences between the current mappings and
  38174. the default mappings you'd get from calling resetToDefaultMappings().
  38175. The advantage of saving a set of differences from the default is that
  38176. if you change the default mappings (in a new version of your app, for
  38177. example), then these will be merged into a user's saved preferences.
  38178. @see restoreFromXml
  38179. */
  38180. XmlElement* createXml (bool saveDifferencesFromDefaultSet) const;
  38181. /** @internal */
  38182. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  38183. /** @internal */
  38184. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  38185. /** @internal */
  38186. void globalFocusChanged (Component* focusedComponent);
  38187. juce_UseDebuggingNewOperator
  38188. private:
  38189. ApplicationCommandManager* commandManager;
  38190. struct CommandMapping
  38191. {
  38192. CommandID commandID;
  38193. Array <KeyPress> keypresses;
  38194. bool wantsKeyUpDownCallbacks;
  38195. };
  38196. OwnedArray <CommandMapping> mappings;
  38197. struct KeyPressTime
  38198. {
  38199. KeyPress key;
  38200. uint32 timeWhenPressed;
  38201. };
  38202. OwnedArray <KeyPressTime> keysDown;
  38203. void handleMessage (const Message& message);
  38204. void invokeCommand (const CommandID commandID,
  38205. const KeyPress& keyPress,
  38206. const bool isKeyDown,
  38207. const int millisecsSinceKeyPressed,
  38208. Component* const originatingComponent) const;
  38209. KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  38210. };
  38211. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38212. /*** End of inlined file: juce_KeyPressMappingSet.h ***/
  38213. /**
  38214. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  38215. object.
  38216. @see KeyPressMappingSet
  38217. */
  38218. class JUCE_API KeyMappingEditorComponent : public Component,
  38219. public TreeViewItem,
  38220. public ChangeListener,
  38221. private ButtonListener
  38222. {
  38223. public:
  38224. /** Creates a KeyMappingEditorComponent.
  38225. @param mappingSet this is the set of mappings to display and
  38226. edit. Make sure the mappings object is not
  38227. deleted before this component!
  38228. @param showResetToDefaultButton if true, then at the bottom of the
  38229. list, the component will include a 'reset to
  38230. defaults' button.
  38231. */
  38232. KeyMappingEditorComponent (KeyPressMappingSet* mappingSet,
  38233. bool showResetToDefaultButton);
  38234. /** Destructor. */
  38235. virtual ~KeyMappingEditorComponent();
  38236. /** Sets up the colours to use for parts of the component.
  38237. @param mainBackground colour to use for most of the background
  38238. @param textColour colour to use for the text
  38239. */
  38240. void setColours (const Colour& mainBackground,
  38241. const Colour& textColour);
  38242. /** Returns the KeyPressMappingSet that this component is acting upon.
  38243. */
  38244. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  38245. /** Can be overridden if some commands need to be excluded from the list.
  38246. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  38247. method to decide what to return, but you can override it to handle special cases.
  38248. */
  38249. virtual bool shouldCommandBeIncluded (CommandID commandID);
  38250. /** Can be overridden to indicate that some commands are shown as read-only.
  38251. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  38252. method to decide what to return, but you can override it to handle special cases.
  38253. */
  38254. virtual bool isCommandReadOnly (CommandID commandID);
  38255. /** This can be overridden to let you change the format of the string used
  38256. to describe a keypress.
  38257. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  38258. keys that are triggered by something else externally. If you override the
  38259. method, be sure to let the base class's method handle keys you're not
  38260. interested in.
  38261. */
  38262. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  38263. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  38264. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38265. methods.
  38266. To change the colours of the menu that pops up
  38267. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38268. */
  38269. enum ColourIds
  38270. {
  38271. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  38272. textColourId = 0x100ad01, /**< The colour for the text. */
  38273. };
  38274. /** @internal */
  38275. void parentHierarchyChanged();
  38276. /** @internal */
  38277. void resized();
  38278. /** @internal */
  38279. void changeListenerCallback (void*);
  38280. /** @internal */
  38281. bool mightContainSubItems();
  38282. /** @internal */
  38283. const String getUniqueName() const;
  38284. /** @internal */
  38285. void buttonClicked (Button* button);
  38286. juce_UseDebuggingNewOperator
  38287. private:
  38288. KeyPressMappingSet* mappings;
  38289. TreeView* tree;
  38290. friend class KeyMappingTreeViewItem;
  38291. friend class KeyCategoryTreeViewItem;
  38292. friend class KeyMappingItemComponent;
  38293. friend class KeyMappingChangeButton;
  38294. TextButton* resetButton;
  38295. void assignNewKey (CommandID commandID, int index);
  38296. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  38297. KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  38298. };
  38299. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38300. /*** End of inlined file: juce_KeyMappingEditorComponent.h ***/
  38301. #endif
  38302. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  38303. #endif
  38304. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38305. #endif
  38306. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  38307. #endif
  38308. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  38309. #endif
  38310. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  38311. #endif
  38312. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  38313. #endif
  38314. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38315. /*** Start of inlined file: juce_ComponentMovementWatcher.h ***/
  38316. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38317. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38318. /** An object that watches for any movement of a component or any of its parent components.
  38319. This makes it easy to check when a component is moved relative to its top-level
  38320. peer window. The normal Component::moved() method is only called when a component
  38321. moves relative to its immediate parent, and sometimes you want to know if any of
  38322. components higher up the tree have moved (which of course will affect the overall
  38323. position of all their sub-components).
  38324. It also includes a callback that lets you know when the top-level peer is changed.
  38325. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  38326. because they need to keep their custom windows in the right place and respond to
  38327. changes in the peer.
  38328. */
  38329. class JUCE_API ComponentMovementWatcher : public ComponentListener
  38330. {
  38331. public:
  38332. /** Creates a ComponentMovementWatcher to watch a given target component. */
  38333. ComponentMovementWatcher (Component* component);
  38334. /** Destructor. */
  38335. ~ComponentMovementWatcher();
  38336. /** This callback happens when the component that is being watched is moved
  38337. relative to its top-level peer window, or when it is resized.
  38338. */
  38339. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  38340. /** This callback happens when the component's top-level peer is changed.
  38341. */
  38342. virtual void componentPeerChanged() = 0;
  38343. juce_UseDebuggingNewOperator
  38344. /** @internal */
  38345. void componentParentHierarchyChanged (Component& component);
  38346. /** @internal */
  38347. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  38348. private:
  38349. Component::SafePointer<Component> component;
  38350. ComponentPeer* lastPeer;
  38351. Array <Component*> registeredParentComps;
  38352. bool reentrant;
  38353. Rectangle<int> lastBounds;
  38354. void unregister() throw();
  38355. void registerWithParentComps() throw();
  38356. ComponentMovementWatcher (const ComponentMovementWatcher&);
  38357. ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  38358. };
  38359. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38360. /*** End of inlined file: juce_ComponentMovementWatcher.h ***/
  38361. #endif
  38362. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38363. /*** Start of inlined file: juce_GroupComponent.h ***/
  38364. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38365. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38366. /**
  38367. A component that draws an outline around itself and has an optional title at
  38368. the top, for drawing an outline around a group of controls.
  38369. */
  38370. class JUCE_API GroupComponent : public Component
  38371. {
  38372. public:
  38373. /** Creates a GroupComponent.
  38374. @param componentName the name to give the component
  38375. @param labelText the text to show at the top of the outline
  38376. */
  38377. GroupComponent (const String& componentName = String::empty,
  38378. const String& labelText = String::empty);
  38379. /** Destructor. */
  38380. ~GroupComponent();
  38381. /** Changes the text that's shown at the top of the component. */
  38382. void setText (const String& newText);
  38383. /** Returns the currently displayed text label. */
  38384. const String getText() const;
  38385. /** Sets the positioning of the text label.
  38386. (The default is Justification::left)
  38387. @see getTextLabelPosition
  38388. */
  38389. void setTextLabelPosition (const Justification& justification);
  38390. /** Returns the current text label position.
  38391. @see setTextLabelPosition
  38392. */
  38393. const Justification getTextLabelPosition() const throw() { return justification; }
  38394. /** A set of colour IDs to use to change the colour of various aspects of the component.
  38395. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38396. methods.
  38397. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38398. */
  38399. enum ColourIds
  38400. {
  38401. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  38402. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  38403. };
  38404. /** @internal */
  38405. void paint (Graphics& g);
  38406. /** @internal */
  38407. void enablementChanged();
  38408. /** @internal */
  38409. void colourChanged();
  38410. private:
  38411. String text;
  38412. Justification justification;
  38413. GroupComponent (const GroupComponent&);
  38414. GroupComponent& operator= (const GroupComponent&);
  38415. };
  38416. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38417. /*** End of inlined file: juce_GroupComponent.h ***/
  38418. #endif
  38419. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  38420. /*** Start of inlined file: juce_MultiDocumentPanel.h ***/
  38421. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  38422. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  38423. /*** Start of inlined file: juce_TabbedComponent.h ***/
  38424. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  38425. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  38426. /*** Start of inlined file: juce_TabbedButtonBar.h ***/
  38427. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  38428. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  38429. class TabbedButtonBar;
  38430. /** In a TabbedButtonBar, this component is used for each of the buttons.
  38431. If you want to create a TabbedButtonBar with custom tab components, derive
  38432. your component from this class, and override the TabbedButtonBar::createTabButton()
  38433. method to create it instead of the default one.
  38434. @see TabbedButtonBar
  38435. */
  38436. class JUCE_API TabBarButton : public Button
  38437. {
  38438. public:
  38439. /** Creates the tab button. */
  38440. TabBarButton (const String& name,
  38441. TabbedButtonBar* ownerBar,
  38442. int tabIndex);
  38443. /** Destructor. */
  38444. ~TabBarButton();
  38445. /** Chooses the best length for the tab, given the specified depth.
  38446. If the tab is horizontal, this should return its width, and the depth
  38447. specifies its height. If it's vertical, it should return the height, and
  38448. the depth is actually its width.
  38449. */
  38450. virtual int getBestTabLength (int depth);
  38451. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  38452. void clicked (const ModifierKeys& mods);
  38453. bool hitTest (int x, int y);
  38454. juce_UseDebuggingNewOperator
  38455. protected:
  38456. friend class TabbedButtonBar;
  38457. TabbedButtonBar* const owner;
  38458. int tabIndex, overlapPixels;
  38459. DropShadowEffect shadow;
  38460. /** Returns an area of the component that's safe to draw in.
  38461. This deals with the orientation of the tabs, which affects which side is
  38462. touching the tabbed box's content component.
  38463. */
  38464. void getActiveArea (int& x, int& y, int& w, int& h);
  38465. private:
  38466. TabBarButton (const TabBarButton&);
  38467. TabBarButton& operator= (const TabBarButton&);
  38468. };
  38469. /**
  38470. A vertical or horizontal bar containing tabs that you can select.
  38471. You can use one of these to generate things like a dialog box that has
  38472. tabbed pages you can flip between. Attach a ChangeListener to the
  38473. button bar to be told when the user changes the page.
  38474. An easier method than doing this is to use a TabbedComponent, which
  38475. contains its own TabbedButtonBar and which takes care of the layout
  38476. and other housekeeping.
  38477. @see TabbedComponent
  38478. */
  38479. class JUCE_API TabbedButtonBar : public Component,
  38480. public ChangeBroadcaster,
  38481. public ButtonListener
  38482. {
  38483. public:
  38484. /** The placement of the tab-bar
  38485. @see setOrientation, getOrientation
  38486. */
  38487. enum Orientation
  38488. {
  38489. TabsAtTop,
  38490. TabsAtBottom,
  38491. TabsAtLeft,
  38492. TabsAtRight
  38493. };
  38494. /** Creates a TabbedButtonBar with a given placement.
  38495. You can change the orientation later if you need to.
  38496. */
  38497. TabbedButtonBar (Orientation orientation);
  38498. /** Destructor. */
  38499. ~TabbedButtonBar();
  38500. /** Changes the bar's orientation.
  38501. This won't change the bar's actual size - you'll need to do that yourself,
  38502. but this determines which direction the tabs go in, and which side they're
  38503. stuck to.
  38504. */
  38505. void setOrientation (Orientation orientation);
  38506. /** Returns the current orientation.
  38507. @see setOrientation
  38508. */
  38509. Orientation getOrientation() const throw() { return orientation; }
  38510. /** Deletes all the tabs from the bar.
  38511. @see addTab
  38512. */
  38513. void clearTabs();
  38514. /** Adds a tab to the bar.
  38515. Tabs are added in left-to-right reading order.
  38516. If this is the first tab added, it'll also be automatically selected.
  38517. */
  38518. void addTab (const String& tabName,
  38519. const Colour& tabBackgroundColour,
  38520. int insertIndex = -1);
  38521. /** Changes the name of one of the tabs. */
  38522. void setTabName (int tabIndex,
  38523. const String& newName);
  38524. /** Gets rid of one of the tabs. */
  38525. void removeTab (int tabIndex);
  38526. /** Moves a tab to a new index in the list.
  38527. Pass -1 as the index to move it to the end of the list.
  38528. */
  38529. void moveTab (int currentIndex, int newIndex);
  38530. /** Returns the number of tabs in the bar. */
  38531. int getNumTabs() const;
  38532. /** Returns a list of all the tab names in the bar. */
  38533. const StringArray getTabNames() const;
  38534. /** Changes the currently selected tab.
  38535. This will send a change message and cause a synchronous callback to
  38536. the currentTabChanged() method. (But if the given tab is already selected,
  38537. nothing will be done).
  38538. To deselect all the tabs, use an index of -1.
  38539. */
  38540. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  38541. /** Returns the name of the currently selected tab.
  38542. This could be an empty string if none are selected.
  38543. */
  38544. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  38545. /** Returns the index of the currently selected tab.
  38546. This could return -1 if none are selected.
  38547. */
  38548. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  38549. /** Returns the button for a specific tab.
  38550. The button that is returned may be deleted later by this component, so don't hang
  38551. on to the pointer that is returned. A null pointer may be returned if the index is
  38552. out of range.
  38553. */
  38554. TabBarButton* getTabButton (int index) const;
  38555. /** Callback method to indicate the selected tab has been changed.
  38556. @see setCurrentTabIndex
  38557. */
  38558. virtual void currentTabChanged (int newCurrentTabIndex,
  38559. const String& newCurrentTabName);
  38560. /** Callback method to indicate that the user has right-clicked on a tab.
  38561. (Or ctrl-clicked on the Mac)
  38562. */
  38563. virtual void popupMenuClickOnTab (int tabIndex, const String& tabName);
  38564. /** Returns the colour of a tab.
  38565. This is the colour that was specified in addTab().
  38566. */
  38567. const Colour getTabBackgroundColour (int tabIndex);
  38568. /** Changes the background colour of a tab.
  38569. @see addTab, getTabBackgroundColour
  38570. */
  38571. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  38572. /** A set of colour IDs to use to change the colour of various aspects of the component.
  38573. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38574. methods.
  38575. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38576. */
  38577. enum ColourIds
  38578. {
  38579. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  38580. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  38581. the look and feel will choose an appropriate colour. */
  38582. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  38583. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  38584. this isn't specified, the look and feel will choose an appropriate
  38585. colour. */
  38586. };
  38587. /** @internal */
  38588. void resized();
  38589. /** @internal */
  38590. void buttonClicked (Button* button);
  38591. /** @internal */
  38592. void lookAndFeelChanged();
  38593. juce_UseDebuggingNewOperator
  38594. protected:
  38595. /** This creates one of the tabs.
  38596. If you need to use custom tab components, you can override this method and
  38597. return your own class instead of the default.
  38598. */
  38599. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  38600. private:
  38601. Orientation orientation;
  38602. StringArray tabs;
  38603. Array <Colour> tabColours;
  38604. int currentTabIndex;
  38605. Component* behindFrontTab;
  38606. ScopedPointer<Button> extraTabsButton;
  38607. TabbedButtonBar (const TabbedButtonBar&);
  38608. TabbedButtonBar& operator= (const TabbedButtonBar&);
  38609. };
  38610. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  38611. /*** End of inlined file: juce_TabbedButtonBar.h ***/
  38612. /**
  38613. A component with a TabbedButtonBar along one of its sides.
  38614. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  38615. with addTab(), and this will take care of showing the pages for you when the
  38616. user clicks on a different tab.
  38617. @see TabbedButtonBar
  38618. */
  38619. class JUCE_API TabbedComponent : public Component
  38620. {
  38621. public:
  38622. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  38623. Once created, add some tabs with the addTab() method.
  38624. */
  38625. explicit TabbedComponent (TabbedButtonBar::Orientation orientation);
  38626. /** Destructor. */
  38627. ~TabbedComponent();
  38628. /** Changes the placement of the tabs.
  38629. This will rearrange the layout to place the tabs along the appropriate
  38630. side of this component, and will shift the content component accordingly.
  38631. @see TabbedButtonBar::setOrientation
  38632. */
  38633. void setOrientation (TabbedButtonBar::Orientation orientation);
  38634. /** Returns the current tab placement.
  38635. @see setOrientation, TabbedButtonBar::getOrientation
  38636. */
  38637. TabbedButtonBar::Orientation getOrientation() const throw();
  38638. /** Specifies how many pixels wide or high the tab-bar should be.
  38639. If the tabs are placed along the top or bottom, this specified the height
  38640. of the bar; if they're along the left or right edges, it'll be the width
  38641. of the bar.
  38642. */
  38643. void setTabBarDepth (int newDepth);
  38644. /** Returns the current thickness of the tab bar.
  38645. @see setTabBarDepth
  38646. */
  38647. int getTabBarDepth() const throw() { return tabDepth; }
  38648. /** Specifies the thickness of an outline that should be drawn around the content component.
  38649. If this thickness is > 0, a line will be drawn around the three sides of the content
  38650. component which don't touch the tab-bar, and the content component will be inset by this amount.
  38651. To set the colour of the line, use setColour (outlineColourId, ...).
  38652. */
  38653. void setOutline (int newThickness);
  38654. /** Specifies a gap to leave around the edge of the content component.
  38655. Each edge of the content component will be indented by the given number of pixels.
  38656. */
  38657. void setIndent (int indentThickness);
  38658. /** Removes all the tabs from the bar.
  38659. @see TabbedButtonBar::clearTabs
  38660. */
  38661. void clearTabs();
  38662. /** Adds a tab to the tab-bar.
  38663. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  38664. is true, it will be deleted when the tab is removed or when this object is
  38665. deleted.
  38666. @see TabbedButtonBar::addTab
  38667. */
  38668. void addTab (const String& tabName,
  38669. const Colour& tabBackgroundColour,
  38670. Component* contentComponent,
  38671. bool deleteComponentWhenNotNeeded,
  38672. int insertIndex = -1);
  38673. /** Changes the name of one of the tabs. */
  38674. void setTabName (int tabIndex, const String& newName);
  38675. /** Gets rid of one of the tabs. */
  38676. void removeTab (int tabIndex);
  38677. /** Returns the number of tabs in the bar. */
  38678. int getNumTabs() const;
  38679. /** Returns a list of all the tab names in the bar. */
  38680. const StringArray getTabNames() const;
  38681. /** Returns the content component that was added for the given index.
  38682. Be sure not to use or delete the components that are returned, as this may interfere
  38683. with the TabbedComponent's use of them.
  38684. */
  38685. Component* getTabContentComponent (int tabIndex) const throw();
  38686. /** Returns the colour of one of the tabs. */
  38687. const Colour getTabBackgroundColour (int tabIndex) const throw();
  38688. /** Changes the background colour of one of the tabs. */
  38689. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  38690. /** Changes the currently-selected tab.
  38691. To deselect all the tabs, pass -1 as the index.
  38692. @see TabbedButtonBar::setCurrentTabIndex
  38693. */
  38694. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  38695. /** Returns the index of the currently selected tab.
  38696. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  38697. */
  38698. int getCurrentTabIndex() const;
  38699. /** Returns the name of the currently selected tab.
  38700. @see addTab, TabbedButtonBar::getCurrentTabName()
  38701. */
  38702. const String& getCurrentTabName() const;
  38703. /** Returns the current component that's filling the panel.
  38704. This will return 0 if there isn't one.
  38705. */
  38706. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  38707. /** Callback method to indicate the selected tab has been changed.
  38708. @see setCurrentTabIndex
  38709. */
  38710. virtual void currentTabChanged (int newCurrentTabIndex,
  38711. const String& newCurrentTabName);
  38712. /** Callback method to indicate that the user has right-clicked on a tab.
  38713. (Or ctrl-clicked on the Mac)
  38714. */
  38715. virtual void popupMenuClickOnTab (int tabIndex,
  38716. const String& tabName);
  38717. /** Returns the tab button bar component that is being used.
  38718. */
  38719. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  38720. /** A set of colour IDs to use to change the colour of various aspects of the component.
  38721. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38722. methods.
  38723. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38724. */
  38725. enum ColourIds
  38726. {
  38727. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  38728. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  38729. (See setOutline) */
  38730. };
  38731. /** @internal */
  38732. void paint (Graphics& g);
  38733. /** @internal */
  38734. void resized();
  38735. /** @internal */
  38736. void lookAndFeelChanged();
  38737. juce_UseDebuggingNewOperator
  38738. protected:
  38739. TabbedButtonBar* tabs;
  38740. /** This creates one of the tab buttons.
  38741. If you need to use custom tab components, you can override this method and
  38742. return your own class instead of the default.
  38743. */
  38744. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  38745. private:
  38746. Array <Component*> contentComponents;
  38747. Component* panelComponent;
  38748. int tabDepth;
  38749. int outlineThickness, edgeIndent;
  38750. static const Identifier deleteComponentId;
  38751. friend class TabCompButtonBar;
  38752. void changeCallback (int newCurrentTabIndex, const String& newTabName);
  38753. TabbedComponent (const TabbedComponent&);
  38754. TabbedComponent& operator= (const TabbedComponent&);
  38755. };
  38756. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  38757. /*** End of inlined file: juce_TabbedComponent.h ***/
  38758. /*** Start of inlined file: juce_DocumentWindow.h ***/
  38759. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  38760. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  38761. /*** Start of inlined file: juce_MenuBarComponent.h ***/
  38762. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  38763. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  38764. /*** Start of inlined file: juce_MenuBarModel.h ***/
  38765. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  38766. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  38767. class MenuBarModel;
  38768. /**
  38769. A class to receive callbacks when a MenuBarModel changes.
  38770. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  38771. */
  38772. class JUCE_API MenuBarModelListener
  38773. {
  38774. public:
  38775. /** Destructor. */
  38776. virtual ~MenuBarModelListener() {}
  38777. /** This callback is made when items are changed in the menu bar model.
  38778. */
  38779. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  38780. /** This callback is made when an application command is invoked that
  38781. is represented by one of the items in the menu bar model.
  38782. */
  38783. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  38784. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  38785. };
  38786. /**
  38787. A class for controlling MenuBar components.
  38788. This class is used to tell a MenuBar what menus to show, and to respond
  38789. to a menu being selected.
  38790. @see MenuBarModelListener, MenuBarComponent, PopupMenu
  38791. */
  38792. class JUCE_API MenuBarModel : private AsyncUpdater,
  38793. private ApplicationCommandManagerListener
  38794. {
  38795. public:
  38796. MenuBarModel() throw();
  38797. /** Destructor. */
  38798. virtual ~MenuBarModel();
  38799. /** Call this when some of your menu items have changed.
  38800. This method will cause a callback to any MenuBarListener objects that
  38801. are registered with this model.
  38802. If this model is displaying items from an ApplicationCommandManager, you
  38803. can use the setApplicationCommandManagerToWatch() method to cause
  38804. change messages to be sent automatically when the ApplicationCommandManager
  38805. is changed.
  38806. @see addListener, removeListener, MenuBarListener
  38807. */
  38808. void menuItemsChanged();
  38809. /** Tells the menu bar to listen to the specified command manager, and to update
  38810. itself when the commands change.
  38811. This will also allow it to flash a menu name when a command from that menu
  38812. is invoked using a keystroke.
  38813. */
  38814. void setApplicationCommandManagerToWatch (ApplicationCommandManager* manager) throw();
  38815. /** Registers a listener for callbacks when the menu items in this model change.
  38816. The listener object will get callbacks when this object's menuItemsChanged()
  38817. method is called.
  38818. @see removeListener
  38819. */
  38820. void addListener (MenuBarModelListener* listenerToAdd) throw();
  38821. /** Removes a listener.
  38822. @see addListener
  38823. */
  38824. void removeListener (MenuBarModelListener* listenerToRemove) throw();
  38825. /** This method must return a list of the names of the menus. */
  38826. virtual const StringArray getMenuBarNames() = 0;
  38827. /** This should return the popup menu to display for a given top-level menu.
  38828. @param topLevelMenuIndex the index of the top-level menu to show
  38829. @param menuName the name of the top-level menu item to show
  38830. */
  38831. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  38832. const String& menuName) = 0;
  38833. /** This is called when a menu item has been clicked on.
  38834. @param menuItemID the item ID of the PopupMenu item that was selected
  38835. @param topLevelMenuIndex the index of the top-level menu from which the item was
  38836. chosen (just in case you've used duplicate ID numbers
  38837. on more than one of the popup menus)
  38838. */
  38839. virtual void menuItemSelected (int menuItemID,
  38840. int topLevelMenuIndex) = 0;
  38841. #if JUCE_MAC || DOXYGEN
  38842. /** MAC ONLY - Sets the model that is currently being shown as the main
  38843. menu bar at the top of the screen on the Mac.
  38844. You can pass 0 to stop the current model being displayed. Be careful
  38845. not to delete a model while it is being used.
  38846. An optional extra menu can be specified, containing items to add to the top of
  38847. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  38848. an apple, it's the one next to it, with your application's name at the top
  38849. and the services menu etc on it). When one of these items is selected, the
  38850. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  38851. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  38852. object then newMenuBarModel must be non-null.
  38853. */
  38854. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  38855. const PopupMenu* extraAppleMenuItems = 0);
  38856. /** MAC ONLY - Returns the menu model that is currently being shown as
  38857. the main menu bar.
  38858. */
  38859. static MenuBarModel* getMacMainMenu();
  38860. #endif
  38861. /** @internal */
  38862. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  38863. /** @internal */
  38864. void applicationCommandListChanged();
  38865. /** @internal */
  38866. void handleAsyncUpdate();
  38867. juce_UseDebuggingNewOperator
  38868. private:
  38869. ApplicationCommandManager* manager;
  38870. ListenerList <MenuBarModelListener> listeners;
  38871. MenuBarModel (const MenuBarModel&);
  38872. MenuBarModel& operator= (const MenuBarModel&);
  38873. };
  38874. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  38875. /*** End of inlined file: juce_MenuBarModel.h ***/
  38876. /**
  38877. A menu bar component.
  38878. @see MenuBarModel
  38879. */
  38880. class JUCE_API MenuBarComponent : public Component,
  38881. private MenuBarModelListener,
  38882. private Timer
  38883. {
  38884. public:
  38885. /** Creates a menu bar.
  38886. @param model the model object to use to control this bar. You can
  38887. pass 0 into this if you like, and set the model later
  38888. using the setModel() method
  38889. */
  38890. MenuBarComponent (MenuBarModel* model);
  38891. /** Destructor. */
  38892. ~MenuBarComponent();
  38893. /** Changes the model object to use to control the bar.
  38894. This can be 0, in which case the bar will be empty. Don't delete the object
  38895. that is passed-in while it's still being used by this MenuBar.
  38896. */
  38897. void setModel (MenuBarModel* newModel);
  38898. /** Pops up one of the menu items.
  38899. This lets you manually open one of the menus - it could be triggered by a
  38900. key shortcut, for example.
  38901. */
  38902. void showMenu (int menuIndex);
  38903. /** @internal */
  38904. void paint (Graphics& g);
  38905. /** @internal */
  38906. void resized();
  38907. /** @internal */
  38908. void mouseEnter (const MouseEvent& e);
  38909. /** @internal */
  38910. void mouseExit (const MouseEvent& e);
  38911. /** @internal */
  38912. void mouseDown (const MouseEvent& e);
  38913. /** @internal */
  38914. void mouseDrag (const MouseEvent& e);
  38915. /** @internal */
  38916. void mouseUp (const MouseEvent& e);
  38917. /** @internal */
  38918. void mouseMove (const MouseEvent& e);
  38919. /** @internal */
  38920. void inputAttemptWhenModal();
  38921. /** @internal */
  38922. void handleCommandMessage (int commandId);
  38923. /** @internal */
  38924. bool keyPressed (const KeyPress& key);
  38925. /** @internal */
  38926. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  38927. /** @internal */
  38928. void menuCommandInvoked (MenuBarModel* menuBarModel,
  38929. const ApplicationCommandTarget::InvocationInfo& info);
  38930. juce_UseDebuggingNewOperator
  38931. private:
  38932. MenuBarModel* model;
  38933. StringArray menuNames;
  38934. Array <int> xPositions;
  38935. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked, indexToShowAgain;
  38936. int lastMouseX, lastMouseY;
  38937. bool inModalState;
  38938. ScopedPointer <Component> currentPopup;
  38939. int getItemAt (int x, int y);
  38940. void updateItemUnderMouse (int x, int y);
  38941. void hideCurrentMenu();
  38942. void timerCallback();
  38943. void repaintMenuItem (int index);
  38944. MenuBarComponent (const MenuBarComponent&);
  38945. MenuBarComponent& operator= (const MenuBarComponent&);
  38946. };
  38947. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  38948. /*** End of inlined file: juce_MenuBarComponent.h ***/
  38949. /**
  38950. A resizable window with a title bar and maximise, minimise and close buttons.
  38951. This subclass of ResizableWindow creates a fairly standard type of window with
  38952. a title bar and various buttons. The name of the component is shown in the
  38953. title bar, and an icon can optionally be specified with setIcon().
  38954. All the methods available to a ResizableWindow are also available to this,
  38955. so it can easily be made resizable, minimised, maximised, etc.
  38956. It's not advisable to add child components directly to a DocumentWindow: put them
  38957. inside your content component instead. And overriding methods like resized(), moved(), etc
  38958. is also not recommended - instead override these methods for your content component.
  38959. (If for some obscure reason you do need to override these methods, always remember to
  38960. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  38961. decorations correctly).
  38962. You can also automatically add a menu bar to the window, using the setMenuBar()
  38963. method.
  38964. @see ResizableWindow, DialogWindow
  38965. */
  38966. class JUCE_API DocumentWindow : public ResizableWindow
  38967. {
  38968. public:
  38969. /** The set of available button-types that can be put on the title bar.
  38970. @see setTitleBarButtonsRequired
  38971. */
  38972. enum TitleBarButtons
  38973. {
  38974. minimiseButton = 1,
  38975. maximiseButton = 2,
  38976. closeButton = 4,
  38977. /** A combination of all the buttons above. */
  38978. allButtons = 7
  38979. };
  38980. /** Creates a DocumentWindow.
  38981. @param name the name to give the component - this is also
  38982. the title shown at the top of the window. To change
  38983. this later, use setName()
  38984. @param backgroundColour the colour to use for filling the window's background.
  38985. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  38986. should be shown on the title bar. This value is a bitwise
  38987. combination of values from the TitleBarButtons enum. Note
  38988. that it can be "allButtons" to get them all. You
  38989. can change this later with the setTitleBarButtonsRequired()
  38990. method, which can also specify where they are positioned.
  38991. @param addToDesktop if true, the window will be automatically added to the
  38992. desktop; if false, you can use it as a child component
  38993. @see TitleBarButtons
  38994. */
  38995. DocumentWindow (const String& name,
  38996. const Colour& backgroundColour,
  38997. int requiredButtons,
  38998. bool addToDesktop = true);
  38999. /** Destructor.
  39000. If a content component has been set with setContentComponent(), it
  39001. will be deleted.
  39002. */
  39003. ~DocumentWindow();
  39004. /** Changes the component's name.
  39005. (This is overridden from Component::setName() to cause a repaint, as
  39006. the name is what gets drawn across the window's title bar).
  39007. */
  39008. void setName (const String& newName);
  39009. /** Sets an icon to show in the title bar, next to the title.
  39010. A copy is made internally of the image, so the caller can delete the
  39011. image after calling this. If 0 is passed-in, any existing icon will be
  39012. removed.
  39013. */
  39014. void setIcon (const Image& imageToUse);
  39015. /** Changes the height of the title-bar. */
  39016. void setTitleBarHeight (int newHeight);
  39017. /** Returns the current title bar height. */
  39018. int getTitleBarHeight() const;
  39019. /** Changes the set of title-bar buttons being shown.
  39020. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  39021. should be shown on the title bar. This value is a bitwise
  39022. combination of values from the TitleBarButtons enum. Note
  39023. that it can be "allButtons" to get them all.
  39024. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  39025. left side of the bar; if false, they'll be placed at the right
  39026. */
  39027. void setTitleBarButtonsRequired (int requiredButtons,
  39028. bool positionTitleBarButtonsOnLeft);
  39029. /** Sets whether the title should be centred within the window.
  39030. If true, the title text is shown in the middle of the title-bar; if false,
  39031. it'll be shown at the left of the bar.
  39032. */
  39033. void setTitleBarTextCentred (bool textShouldBeCentred);
  39034. /** Creates a menu inside this window.
  39035. @param menuBarModel this specifies a MenuBarModel that should be used to
  39036. generate the contents of a menu bar that will be placed
  39037. just below the title bar, and just above any content
  39038. component. If this value is zero, any existing menu bar
  39039. will be removed from the component; if non-zero, one will
  39040. be added if it's required.
  39041. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  39042. or less to use the look-and-feel's default size.
  39043. */
  39044. void setMenuBar (MenuBarModel* menuBarModel,
  39045. int menuBarHeight = 0);
  39046. /** This method is called when the user tries to close the window.
  39047. This is triggered by the user clicking the close button, or using some other
  39048. OS-specific key shortcut or OS menu for getting rid of a window.
  39049. If the window is just a pop-up, you should override this closeButtonPressed()
  39050. method and make it delete the window in whatever way is appropriate for your
  39051. app. E.g. you might just want to call "delete this".
  39052. If your app is centred around this window such that the whole app should quit when
  39053. the window is closed, then you will probably want to use this method as an opportunity
  39054. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  39055. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  39056. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  39057. or closing it via the taskbar icon on Windows).
  39058. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  39059. redirects it to call this method, so any methods of closing the window that are
  39060. caught by userTriedToCloseWindow() will also end up here).
  39061. */
  39062. virtual void closeButtonPressed();
  39063. /** Callback that is triggered when the minimise button is pressed.
  39064. The default implementation of this calls ResizableWindow::setMinimised(), but
  39065. you can override it to do more customised behaviour.
  39066. */
  39067. virtual void minimiseButtonPressed();
  39068. /** Callback that is triggered when the maximise button is pressed, or when the
  39069. title-bar is double-clicked.
  39070. The default implementation of this calls ResizableWindow::setFullScreen(), but
  39071. you can override it to do more customised behaviour.
  39072. */
  39073. virtual void maximiseButtonPressed();
  39074. /** Returns the close button, (or 0 if there isn't one). */
  39075. Button* getCloseButton() const throw();
  39076. /** Returns the minimise button, (or 0 if there isn't one). */
  39077. Button* getMinimiseButton() const throw();
  39078. /** Returns the maximise button, (or 0 if there isn't one). */
  39079. Button* getMaximiseButton() const throw();
  39080. /** A set of colour IDs to use to change the colour of various aspects of the window.
  39081. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39082. methods.
  39083. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39084. */
  39085. enum ColourIds
  39086. {
  39087. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  39088. and feel class how this is used. */
  39089. };
  39090. /** @internal */
  39091. void paint (Graphics& g);
  39092. /** @internal */
  39093. void resized();
  39094. /** @internal */
  39095. void lookAndFeelChanged();
  39096. /** @internal */
  39097. const BorderSize getBorderThickness();
  39098. /** @internal */
  39099. const BorderSize getContentComponentBorder();
  39100. /** @internal */
  39101. void mouseDoubleClick (const MouseEvent& e);
  39102. /** @internal */
  39103. void userTriedToCloseWindow();
  39104. /** @internal */
  39105. void activeWindowStatusChanged();
  39106. /** @internal */
  39107. int getDesktopWindowStyleFlags() const;
  39108. /** @internal */
  39109. void parentHierarchyChanged();
  39110. /** @internal */
  39111. const Rectangle<int> getTitleBarArea();
  39112. juce_UseDebuggingNewOperator
  39113. private:
  39114. int titleBarHeight, menuBarHeight, requiredButtons;
  39115. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  39116. ScopedPointer <Button> titleBarButtons [3];
  39117. Image titleBarIcon;
  39118. ScopedPointer <MenuBarComponent> menuBar;
  39119. MenuBarModel* menuBarModel;
  39120. class ButtonListenerProxy;
  39121. friend class ScopedPointer <ButtonListenerProxy>;
  39122. ScopedPointer <ButtonListenerProxy> buttonListener;
  39123. void repaintTitleBar();
  39124. DocumentWindow (const DocumentWindow&);
  39125. DocumentWindow& operator= (const DocumentWindow&);
  39126. };
  39127. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  39128. /*** End of inlined file: juce_DocumentWindow.h ***/
  39129. class MultiDocumentPanel;
  39130. class MDITabbedComponentInternal;
  39131. /**
  39132. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  39133. component.
  39134. It's like a normal DocumentWindow but has some extra functionality to make sure
  39135. everything works nicely inside a MultiDocumentPanel.
  39136. @see MultiDocumentPanel
  39137. */
  39138. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  39139. {
  39140. public:
  39141. /**
  39142. */
  39143. MultiDocumentPanelWindow (const Colour& backgroundColour);
  39144. /** Destructor. */
  39145. ~MultiDocumentPanelWindow();
  39146. /** @internal */
  39147. void maximiseButtonPressed();
  39148. /** @internal */
  39149. void closeButtonPressed();
  39150. /** @internal */
  39151. void activeWindowStatusChanged();
  39152. /** @internal */
  39153. void broughtToFront();
  39154. juce_UseDebuggingNewOperator
  39155. private:
  39156. void updateOrder();
  39157. MultiDocumentPanel* getOwner() const throw();
  39158. };
  39159. /**
  39160. A component that contains a set of other components either in floating windows
  39161. or tabs.
  39162. This acts as a panel that can be used to hold a set of open document windows, with
  39163. different layout modes.
  39164. Use addDocument() and closeDocument() to add or remove components from the
  39165. panel - never use any of the Component methods to access the panel's child
  39166. components directly, as these are managed internally.
  39167. */
  39168. class JUCE_API MultiDocumentPanel : public Component,
  39169. private ComponentListener
  39170. {
  39171. public:
  39172. /** Creates an empty panel.
  39173. Use addDocument() and closeDocument() to add or remove components from the
  39174. panel - never use any of the Component methods to access the panel's child
  39175. components directly, as these are managed internally.
  39176. */
  39177. MultiDocumentPanel();
  39178. /** Destructor.
  39179. When deleted, this will call closeAllDocuments (false) to make sure all its
  39180. components are deleted. If you need to make sure all documents are saved
  39181. before closing, then you should call closeAllDocuments (true) and check that
  39182. it returns true before deleting the panel.
  39183. */
  39184. ~MultiDocumentPanel();
  39185. /** Tries to close all the documents.
  39186. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  39187. be called for each open document, and any of these calls fails, this method
  39188. will stop and return false, leaving some documents still open.
  39189. If checkItsOkToCloseFirst is false, then all documents will be closed
  39190. unconditionally.
  39191. @see closeDocument
  39192. */
  39193. bool closeAllDocuments (bool checkItsOkToCloseFirst);
  39194. /** Adds a document component to the panel.
  39195. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  39196. this will fail and return false. (If it does fail, the component passed-in will not be
  39197. deleted, even if deleteWhenRemoved was set to true).
  39198. The MultiDocumentPanel will deal with creating a window border to go around your component,
  39199. so just pass in the bare content component here, no need to give it a ResizableWindow
  39200. or DocumentWindow.
  39201. @param component the component to add
  39202. @param backgroundColour the background colour to use to fill the component's
  39203. window or tab
  39204. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  39205. or closeAllDocuments(), then it will be deleted. If false, then
  39206. the caller must handle the component's deletion
  39207. */
  39208. bool addDocument (Component* component,
  39209. const Colour& backgroundColour,
  39210. bool deleteWhenRemoved);
  39211. /** Closes one of the documents.
  39212. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  39213. be called, and if it fails, this method will return false without closing the
  39214. document.
  39215. If checkItsOkToCloseFirst is false, then the documents will be closed
  39216. unconditionally.
  39217. The component will be deleted if the deleteWhenRemoved parameter was set to
  39218. true when it was added with addDocument.
  39219. @see addDocument, closeAllDocuments
  39220. */
  39221. bool closeDocument (Component* component,
  39222. bool checkItsOkToCloseFirst);
  39223. /** Returns the number of open document windows.
  39224. @see getDocument
  39225. */
  39226. int getNumDocuments() const throw();
  39227. /** Returns one of the open documents.
  39228. The order of the documents in this array may change when they are added, removed
  39229. or moved around.
  39230. @see getNumDocuments
  39231. */
  39232. Component* getDocument (int index) const throw();
  39233. /** Returns the document component that is currently focused or on top.
  39234. If currently using floating windows, then this will be the component in the currently
  39235. active window, or the top component if none are active.
  39236. If it's currently in tabbed mode, then it'll return the component in the active tab.
  39237. @see setActiveDocument
  39238. */
  39239. Component* getActiveDocument() const throw();
  39240. /** Makes one of the components active and brings it to the top.
  39241. @see getActiveDocument
  39242. */
  39243. void setActiveDocument (Component* component);
  39244. /** Callback which gets invoked when the currently-active document changes. */
  39245. virtual void activeDocumentChanged();
  39246. /** Sets a limit on how many windows can be open at once.
  39247. If this is zero or less there's no limit (the default). addDocument() will fail
  39248. if this number is exceeded.
  39249. */
  39250. void setMaximumNumDocuments (int maximumNumDocuments);
  39251. /** Sets an option to make the document fullscreen if there's only one document open.
  39252. If set to true, then if there's only one document, it'll fill the whole of this
  39253. component without tabs or a window border. If false, then tabs or a window
  39254. will always be shown, even if there's only one document. If there's more than
  39255. one document open, then this option makes no difference.
  39256. */
  39257. void useFullscreenWhenOneDocument (bool shouldUseTabs);
  39258. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  39259. */
  39260. bool isFullscreenWhenOneDocument() const throw();
  39261. /** The different layout modes available. */
  39262. enum LayoutMode
  39263. {
  39264. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  39265. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  39266. };
  39267. /** Changes the panel's mode.
  39268. @see LayoutMode, getLayoutMode
  39269. */
  39270. void setLayoutMode (LayoutMode newLayoutMode);
  39271. /** Returns the current layout mode. */
  39272. LayoutMode getLayoutMode() const throw() { return mode; }
  39273. /** Sets the background colour for the whole panel.
  39274. Each document has its own background colour, but this is the one used to fill the areas
  39275. behind them.
  39276. */
  39277. void setBackgroundColour (const Colour& newBackgroundColour);
  39278. /** Returns the current background colour.
  39279. @see setBackgroundColour
  39280. */
  39281. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  39282. /** A subclass must override this to say whether its currently ok for a document
  39283. to be closed.
  39284. This method is called by closeDocument() and closeAllDocuments() to indicate that
  39285. a document should be saved if possible, ready for it to be closed.
  39286. If this method returns true, then it means the document is ok and can be closed.
  39287. If it returns false, then it means that the closeDocument() method should stop
  39288. and not close.
  39289. Normally, you'd use this method to ask the user if they want to save any changes,
  39290. then return true if the save operation went ok. If the user cancelled the save
  39291. operation you could return false here to abort the close operation.
  39292. If your component is based on the FileBasedDocument class, then you'd probably want
  39293. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  39294. FileBasedDocument::savedOk
  39295. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  39296. */
  39297. virtual bool tryToCloseDocument (Component* component) = 0;
  39298. /** Creates a new window to be used for a document.
  39299. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  39300. but you might want to override it to return a custom component.
  39301. */
  39302. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  39303. /** @internal */
  39304. void paint (Graphics& g);
  39305. /** @internal */
  39306. void resized();
  39307. /** @internal */
  39308. void componentNameChanged (Component&);
  39309. juce_UseDebuggingNewOperator
  39310. private:
  39311. LayoutMode mode;
  39312. Array <Component*> components;
  39313. TabbedComponent* tabComponent;
  39314. Colour backgroundColour;
  39315. int maximumNumDocuments, numDocsBeforeTabsUsed;
  39316. friend class MultiDocumentPanelWindow;
  39317. friend class MDITabbedComponentInternal;
  39318. Component* getContainerComp (Component* c) const;
  39319. void updateOrder();
  39320. void addWindow (Component* component);
  39321. };
  39322. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  39323. /*** End of inlined file: juce_MultiDocumentPanel.h ***/
  39324. #endif
  39325. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  39326. #endif
  39327. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  39328. #endif
  39329. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  39330. #endif
  39331. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39332. /*** Start of inlined file: juce_StretchableLayoutManager.h ***/
  39333. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39334. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39335. /**
  39336. For laying out a set of components, where the components have preferred sizes
  39337. and size limits, but where they are allowed to stretch to fill the available
  39338. space.
  39339. For example, if you have a component containing several other components, and
  39340. each one should be given a share of the total size, you could use one of these
  39341. to resize the child components when the parent component is resized. Then
  39342. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  39343. A StretchableLayoutManager operates only in one dimension, so if you have a set
  39344. of components stacked vertically on top of each other, you'd use one to manage their
  39345. heights. To build up complex arrangements of components, e.g. for applications
  39346. with multiple nested panels, you would use more than one StretchableLayoutManager.
  39347. E.g. by using two (one vertical, one horizontal), you could create a resizable
  39348. spreadsheet-style table.
  39349. E.g.
  39350. @code
  39351. class MyComp : public Component
  39352. {
  39353. StretchableLayoutManager myLayout;
  39354. MyComp()
  39355. {
  39356. myLayout.setItemLayout (0, // for item 0
  39357. 50, 100, // must be between 50 and 100 pixels in size
  39358. -0.6); // and its preferred size is 60% of the total available space
  39359. myLayout.setItemLayout (1, // for item 1
  39360. -0.2, -0.6, // size must be between 20% and 60% of the available space
  39361. 50); // and its preferred size is 50 pixels
  39362. }
  39363. void resized()
  39364. {
  39365. // make a list of two of our child components that we want to reposition
  39366. Component* comps[] = { myComp1, myComp2 };
  39367. // this will position the 2 components, one above the other, to fit
  39368. // vertically into the rectangle provided.
  39369. myLayout.layOutComponents (comps, 2,
  39370. 0, 0, getWidth(), getHeight(),
  39371. true);
  39372. }
  39373. };
  39374. @endcode
  39375. @see StretchableLayoutResizerBar
  39376. */
  39377. class JUCE_API StretchableLayoutManager
  39378. {
  39379. public:
  39380. /** Creates an empty layout.
  39381. You'll need to add some item properties to the layout before it can be used
  39382. to resize things - see setItemLayout().
  39383. */
  39384. StretchableLayoutManager();
  39385. /** Destructor. */
  39386. ~StretchableLayoutManager();
  39387. /** For a numbered item, this sets its size limits and preferred size.
  39388. @param itemIndex the index of the item to change.
  39389. @param minimumSize the minimum size that this item is allowed to be - a positive number
  39390. indicates an absolute size in pixels. A negative number indicates a
  39391. proportion of the available space (e.g -0.5 is 50%)
  39392. @param maximumSize the maximum size that this item is allowed to be - a positive number
  39393. indicates an absolute size in pixels. A negative number indicates a
  39394. proportion of the available space
  39395. @param preferredSize the size that this item would like to be, if there's enough room. A
  39396. positive number indicates an absolute size in pixels. A negative number
  39397. indicates a proportion of the available space
  39398. @see getItemLayout
  39399. */
  39400. void setItemLayout (int itemIndex,
  39401. double minimumSize,
  39402. double maximumSize,
  39403. double preferredSize);
  39404. /** For a numbered item, this returns its size limits and preferred size.
  39405. @param itemIndex the index of the item.
  39406. @param minimumSize the minimum size that this item is allowed to be - a positive number
  39407. indicates an absolute size in pixels. A negative number indicates a
  39408. proportion of the available space (e.g -0.5 is 50%)
  39409. @param maximumSize the maximum size that this item is allowed to be - a positive number
  39410. indicates an absolute size in pixels. A negative number indicates a
  39411. proportion of the available space
  39412. @param preferredSize the size that this item would like to be, if there's enough room. A
  39413. positive number indicates an absolute size in pixels. A negative number
  39414. indicates a proportion of the available space
  39415. @returns false if the item's properties hadn't been set
  39416. @see setItemLayout
  39417. */
  39418. bool getItemLayout (int itemIndex,
  39419. double& minimumSize,
  39420. double& maximumSize,
  39421. double& preferredSize) const;
  39422. /** Clears all the properties that have been set with setItemLayout() and resets
  39423. this object to its initial state.
  39424. */
  39425. void clearAllItems();
  39426. /** Takes a set of components that correspond to the layout's items, and positions
  39427. them to fill a space.
  39428. This will try to give each item its preferred size, whether that's a relative size
  39429. or an absolute one.
  39430. @param components an array of components that correspond to each of the
  39431. numbered items that the StretchableLayoutManager object
  39432. has been told about with setItemLayout()
  39433. @param numComponents the number of components in the array that is passed-in. This
  39434. should be the same as the number of items this object has been
  39435. told about.
  39436. @param x the left of the rectangle in which the components should
  39437. be laid out
  39438. @param y the top of the rectangle in which the components should
  39439. be laid out
  39440. @param width the width of the rectangle in which the components should
  39441. be laid out
  39442. @param height the height of the rectangle in which the components should
  39443. be laid out
  39444. @param vertically if true, the components will be positioned in a vertical stack,
  39445. so that they fill the height of the rectangle. If false, they
  39446. will be placed side-by-side in a horizontal line, filling the
  39447. available width
  39448. @param resizeOtherDimension if true, this means that the components will have their
  39449. other dimension resized to fit the space - i.e. if the 'vertically'
  39450. parameter is true, their x-positions and widths are adjusted to fit
  39451. the x and width parameters; if 'vertically' is false, their y-positions
  39452. and heights are adjusted to fit the y and height parameters.
  39453. */
  39454. void layOutComponents (Component** components,
  39455. int numComponents,
  39456. int x, int y, int width, int height,
  39457. bool vertically,
  39458. bool resizeOtherDimension);
  39459. /** Returns the current position of one of the items.
  39460. This is only a valid call after layOutComponents() has been called, as it
  39461. returns the last position that this item was placed at. If the layout was
  39462. vertical, the value returned will be the y position of the top of the item,
  39463. relative to the top of the rectangle in which the items were placed (so for
  39464. example, item 0 will always have position of 0, even in the rectangle passed
  39465. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  39466. the position returned is the item's left-hand position, again relative to the
  39467. x position of the rectangle used.
  39468. @see getItemCurrentSize, setItemPosition
  39469. */
  39470. int getItemCurrentPosition (int itemIndex) const;
  39471. /** Returns the current size of one of the items.
  39472. This is only meaningful after layOutComponents() has been called, as it
  39473. returns the last size that this item was given. If the layout was done
  39474. vertically, it'll return the item's height in pixels; if it was horizontal,
  39475. it'll return its width.
  39476. @see getItemCurrentRelativeSize
  39477. */
  39478. int getItemCurrentAbsoluteSize (int itemIndex) const;
  39479. /** Returns the current size of one of the items.
  39480. This is only meaningful after layOutComponents() has been called, as it
  39481. returns the last size that this item was given. If the layout was done
  39482. vertically, it'll return a negative value representing the item's height relative
  39483. to the last size used for laying the components out; if the layout was done
  39484. horizontally it'll be the proportion of its width.
  39485. @see getItemCurrentAbsoluteSize
  39486. */
  39487. double getItemCurrentRelativeSize (int itemIndex) const;
  39488. /** Moves one of the items, shifting along any other items as necessary in
  39489. order to get it to the desired position.
  39490. Calling this method will also update the preferred sizes of the items it
  39491. shuffles along, so that they reflect their new positions.
  39492. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  39493. about when it's dragged).
  39494. @param itemIndex the item to move
  39495. @param newPosition the absolute position that you'd like this item to move
  39496. to. The item might not be able to always reach exactly this position,
  39497. because other items may have minimum sizes that constrain how
  39498. far it can go
  39499. */
  39500. void setItemPosition (int itemIndex,
  39501. int newPosition);
  39502. juce_UseDebuggingNewOperator
  39503. private:
  39504. struct ItemLayoutProperties
  39505. {
  39506. int itemIndex;
  39507. int currentSize;
  39508. double minSize, maxSize, preferredSize;
  39509. };
  39510. OwnedArray <ItemLayoutProperties> items;
  39511. int totalSize;
  39512. static int sizeToRealSize (double size, int totalSpace);
  39513. ItemLayoutProperties* getInfoFor (int itemIndex) const;
  39514. void setTotalSize (int newTotalSize);
  39515. int fitComponentsIntoSpace (int startIndex, int endIndex, int availableSpace, int startPos);
  39516. int getMinimumSizeOfItems (int startIndex, int endIndex) const;
  39517. int getMaximumSizeOfItems (int startIndex, int endIndex) const;
  39518. void updatePrefSizesToMatchCurrentPositions();
  39519. StretchableLayoutManager (const StretchableLayoutManager&);
  39520. StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  39521. };
  39522. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39523. /*** End of inlined file: juce_StretchableLayoutManager.h ***/
  39524. #endif
  39525. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39526. /*** Start of inlined file: juce_StretchableLayoutResizerBar.h ***/
  39527. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39528. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39529. /**
  39530. A component that acts as one of the vertical or horizontal bars you see being
  39531. used to resize panels in a window.
  39532. One of these acts with a StretchableLayoutManager to resize the other components.
  39533. @see StretchableLayoutManager
  39534. */
  39535. class JUCE_API StretchableLayoutResizerBar : public Component
  39536. {
  39537. public:
  39538. /** Creates a resizer bar for use on a specified layout.
  39539. @param layoutToUse the layout that will be affected when this bar
  39540. is dragged
  39541. @param itemIndexInLayout the item index in the layout that corresponds to
  39542. this bar component. You'll need to set up the item
  39543. properties in a suitable way for a divider bar, e.g.
  39544. for an 8-pixel wide bar which, you could call
  39545. myLayout->setItemLayout (barIndex, 8, 8, 8)
  39546. @param isBarVertical true if it's an upright bar that you drag left and
  39547. right; false for a horizontal one that you drag up and
  39548. down
  39549. */
  39550. StretchableLayoutResizerBar (StretchableLayoutManager* layoutToUse,
  39551. int itemIndexInLayout,
  39552. bool isBarVertical);
  39553. /** Destructor. */
  39554. ~StretchableLayoutResizerBar();
  39555. /** This is called when the bar is dragged.
  39556. This method must update the positions of any components whose position is
  39557. determined by the StretchableLayoutManager, because they might have just
  39558. moved.
  39559. The default implementation calls the resized() method of this component's
  39560. parent component, because that's often where you're likely to apply the
  39561. layout, but it can be overridden for more specific needs.
  39562. */
  39563. virtual void hasBeenMoved();
  39564. /** @internal */
  39565. void paint (Graphics& g);
  39566. /** @internal */
  39567. void mouseDown (const MouseEvent& e);
  39568. /** @internal */
  39569. void mouseDrag (const MouseEvent& e);
  39570. juce_UseDebuggingNewOperator
  39571. private:
  39572. StretchableLayoutManager* layout;
  39573. int itemIndex, mouseDownPos;
  39574. bool isVertical;
  39575. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  39576. StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  39577. };
  39578. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39579. /*** End of inlined file: juce_StretchableLayoutResizerBar.h ***/
  39580. #endif
  39581. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39582. /*** Start of inlined file: juce_StretchableObjectResizer.h ***/
  39583. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39584. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39585. /**
  39586. A utility class for fitting a set of objects whose sizes can vary between
  39587. a minimum and maximum size, into a space.
  39588. This is a trickier algorithm than it would first seem, so I've put it in this
  39589. class to allow it to be shared by various bits of code.
  39590. To use it, create one of these objects, call addItem() to add the list of items
  39591. you need, then call resizeToFit(), which will change all their sizes. You can
  39592. then retrieve the new sizes with getItemSize() and getNumItems().
  39593. It's currently used by the TableHeaderComponent for stretching out the table
  39594. headings to fill the table's width.
  39595. */
  39596. class StretchableObjectResizer
  39597. {
  39598. public:
  39599. /** Creates an empty object resizer. */
  39600. StretchableObjectResizer();
  39601. /** Destructor. */
  39602. ~StretchableObjectResizer();
  39603. /** Adds an item to the list.
  39604. The order parameter lets you specify groups of items that are resized first when some
  39605. space needs to be found. Those items with an order of 0 will be the first ones to be
  39606. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  39607. will then try resizing the items with an order of 1, then 2, and so on.
  39608. */
  39609. void addItem (double currentSize,
  39610. double minSize,
  39611. double maxSize,
  39612. int order = 0);
  39613. /** Resizes all the items to fit this amount of space.
  39614. This will attempt to fit them in without exceeding each item's miniumum and
  39615. maximum sizes. In cases where none of the items can be expanded or enlarged any
  39616. further, the final size may be greater or less than the size passed in.
  39617. After calling this method, you can retrieve the new sizes with the getItemSize()
  39618. method.
  39619. */
  39620. void resizeToFit (double targetSize);
  39621. /** Returns the number of items that have been added. */
  39622. int getNumItems() const throw() { return items.size(); }
  39623. /** Returns the size of one of the items. */
  39624. double getItemSize (int index) const throw();
  39625. juce_UseDebuggingNewOperator
  39626. private:
  39627. struct Item
  39628. {
  39629. double size;
  39630. double minSize;
  39631. double maxSize;
  39632. int order;
  39633. };
  39634. OwnedArray <Item> items;
  39635. StretchableObjectResizer (const StretchableObjectResizer&);
  39636. StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  39637. };
  39638. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39639. /*** End of inlined file: juce_StretchableObjectResizer.h ***/
  39640. #endif
  39641. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  39642. #endif
  39643. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  39644. #endif
  39645. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  39646. #endif
  39647. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39648. /*** Start of inlined file: juce_LookAndFeel.h ***/
  39649. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39650. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  39651. /*** Start of inlined file: juce_AlertWindow.h ***/
  39652. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  39653. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  39654. /*** Start of inlined file: juce_TextLayout.h ***/
  39655. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  39656. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  39657. class Graphics;
  39658. /**
  39659. A laid-out arrangement of text.
  39660. You can add text in different fonts to a TextLayout object, then call its
  39661. layout() method to word-wrap it into lines. The layout can then be drawn
  39662. using a graphics context.
  39663. It's handy if you've got a message to display, because you can format it,
  39664. measure the extent of the layout, and then create a suitably-sized window
  39665. to show it in.
  39666. @see Font, Graphics::drawFittedText, GlyphArrangement
  39667. */
  39668. class JUCE_API TextLayout
  39669. {
  39670. public:
  39671. /** Creates an empty text layout.
  39672. Text can then be appended using the appendText() method.
  39673. */
  39674. TextLayout();
  39675. /** Creates a copy of another layout object. */
  39676. TextLayout (const TextLayout& other);
  39677. /** Creates a text layout from an initial string and font. */
  39678. TextLayout (const String& text, const Font& font);
  39679. /** Destructor. */
  39680. ~TextLayout();
  39681. /** Copies another layout onto this one. */
  39682. TextLayout& operator= (const TextLayout& layoutToCopy);
  39683. /** Clears the layout, removing all its text. */
  39684. void clear();
  39685. /** Adds a string to the end of the arrangement.
  39686. The string will be broken onto new lines wherever it contains
  39687. carriage-returns or linefeeds. After adding it, you can call layout()
  39688. to wrap long lines into a paragraph and justify it.
  39689. */
  39690. void appendText (const String& textToAppend,
  39691. const Font& fontToUse);
  39692. /** Replaces all the text with a new string.
  39693. This is equivalent to calling clear() followed by appendText().
  39694. */
  39695. void setText (const String& newText,
  39696. const Font& fontToUse);
  39697. /** Breaks the text up to form a paragraph with the given width.
  39698. @param maximumWidth any text wider than this will be split
  39699. across multiple lines
  39700. @param justification how the lines are to be laid-out horizontally
  39701. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  39702. width that keeps all the lines of text at a
  39703. similar length - this is good when you're displaying
  39704. a short message and don't want it to get split
  39705. onto two lines with only a couple of words on
  39706. the second line, which looks untidy.
  39707. */
  39708. void layout (int maximumWidth,
  39709. const Justification& justification,
  39710. bool attemptToBalanceLineLengths);
  39711. /** Returns the overall width of the entire text layout. */
  39712. int getWidth() const;
  39713. /** Returns the overall height of the entire text layout. */
  39714. int getHeight() const;
  39715. /** Returns the total number of lines of text. */
  39716. int getNumLines() const { return totalLines; }
  39717. /** Returns the width of a particular line of text.
  39718. @param lineNumber the line, from 0 to (getNumLines() - 1)
  39719. */
  39720. int getLineWidth (int lineNumber) const;
  39721. /** Renders the text at a specified position using a graphics context.
  39722. */
  39723. void draw (Graphics& g, int topLeftX, int topLeftY) const;
  39724. /** Renders the text within a specified rectangle using a graphics context.
  39725. The justification flags dictate how the block of text should be positioned
  39726. within the rectangle.
  39727. */
  39728. void drawWithin (Graphics& g,
  39729. int x, int y, int w, int h,
  39730. const Justification& layoutFlags) const;
  39731. juce_UseDebuggingNewOperator
  39732. private:
  39733. class Token;
  39734. friend class OwnedArray <Token>;
  39735. OwnedArray <Token> tokens;
  39736. int totalLines;
  39737. };
  39738. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  39739. /*** End of inlined file: juce_TextLayout.h ***/
  39740. /** A window that displays a message and has buttons for the user to react to it.
  39741. For simple dialog boxes with just a couple of buttons on them, there are
  39742. some static methods for running these.
  39743. For more complex dialogs, an AlertWindow can be created, then it can have some
  39744. buttons and components added to it, and its runModalLoop() method is then used to
  39745. show it. The value returned by runModalLoop() shows which button the
  39746. user pressed to dismiss the box.
  39747. @see ThreadWithProgressWindow
  39748. */
  39749. class JUCE_API AlertWindow : public TopLevelWindow,
  39750. private ButtonListener
  39751. {
  39752. public:
  39753. /** The type of icon to show in the dialog box. */
  39754. enum AlertIconType
  39755. {
  39756. NoIcon, /**< No icon will be shown on the dialog box. */
  39757. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  39758. user to answer a question. */
  39759. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  39760. warning about something and shouldn't be ignored. */
  39761. InfoIcon /**< An icon that indicates that the dialog box is just
  39762. giving the user some information, which doesn't require
  39763. a response from them. */
  39764. };
  39765. /** Creates an AlertWindow.
  39766. @param title the headline to show at the top of the dialog box
  39767. @param message a longer, more descriptive message to show underneath the
  39768. headline
  39769. @param iconType the type of icon to display
  39770. @param associatedComponent if this is non-zero, it specifies the component that the
  39771. alert window should be associated with. Depending on the look
  39772. and feel, this might be used for positioning of the alert window.
  39773. */
  39774. AlertWindow (const String& title,
  39775. const String& message,
  39776. AlertIconType iconType,
  39777. Component* associatedComponent = 0);
  39778. /** Destroys the AlertWindow */
  39779. ~AlertWindow();
  39780. /** Returns the type of alert icon that was specified when the window
  39781. was created. */
  39782. AlertIconType getAlertType() const throw() { return alertIconType; }
  39783. /** Changes the dialog box's message.
  39784. This will also resize the window to fit the new message if required.
  39785. */
  39786. void setMessage (const String& message);
  39787. /** Adds a button to the window.
  39788. @param name the text to show on the button
  39789. @param returnValue the value that should be returned from runModalLoop()
  39790. if this is the button that the user presses.
  39791. @param shortcutKey1 an optional key that can be pressed to trigger this button
  39792. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  39793. */
  39794. void addButton (const String& name,
  39795. int returnValue,
  39796. const KeyPress& shortcutKey1 = KeyPress(),
  39797. const KeyPress& shortcutKey2 = KeyPress());
  39798. /** Returns the number of buttons that the window currently has. */
  39799. int getNumButtons() const;
  39800. /** Invokes a click of one of the buttons. */
  39801. void triggerButtonClick (const String& buttonName);
  39802. /** Adds a textbox to the window for entering strings.
  39803. @param name an internal name for the text-box. This is the name to pass to
  39804. the getTextEditorContents() method to find out what the
  39805. user typed-in.
  39806. @param initialContents a string to show in the text box when it's first shown
  39807. @param onScreenLabel if this is non-empty, it will be displayed next to the
  39808. text-box to label it.
  39809. @param isPasswordBox if true, the text editor will display asterisks instead of
  39810. the actual text
  39811. @see getTextEditorContents
  39812. */
  39813. void addTextEditor (const String& name,
  39814. const String& initialContents,
  39815. const String& onScreenLabel = String::empty,
  39816. bool isPasswordBox = false);
  39817. /** Returns the contents of a named textbox.
  39818. After showing an AlertWindow that contains a text editor, this can be
  39819. used to find out what the user has typed into it.
  39820. @param nameOfTextEditor the name of the text box that you're interested in
  39821. @see addTextEditor
  39822. */
  39823. const String getTextEditorContents (const String& nameOfTextEditor) const;
  39824. /** Adds a drop-down list of choices to the box.
  39825. After the box has been shown, the getComboBoxComponent() method can
  39826. be used to find out which item the user picked.
  39827. @param name the label to use for the drop-down list
  39828. @param items the list of items to show in it
  39829. @param onScreenLabel if this is non-empty, it will be displayed next to the
  39830. combo-box to label it.
  39831. @see getComboBoxComponent
  39832. */
  39833. void addComboBox (const String& name,
  39834. const StringArray& items,
  39835. const String& onScreenLabel = String::empty);
  39836. /** Returns a drop-down list that was added to the AlertWindow.
  39837. @param nameOfList the name that was passed into the addComboBox() method
  39838. when creating the drop-down
  39839. @returns the ComboBox component, or 0 if none was found for the given name.
  39840. */
  39841. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  39842. /** Adds a block of text.
  39843. This is handy for adding a multi-line note next to a textbox or combo-box,
  39844. to provide more details about what's going on.
  39845. */
  39846. void addTextBlock (const String& text);
  39847. /** Adds a progress-bar to the window.
  39848. @param progressValue a variable that will be repeatedly checked while the
  39849. dialog box is visible, to see how far the process has
  39850. got. The value should be in the range 0 to 1.0
  39851. */
  39852. void addProgressBarComponent (double& progressValue);
  39853. /** Adds a user-defined component to the dialog box.
  39854. @param component the component to add - its size should be set up correctly
  39855. before it is passed in. The caller is responsible for deleting
  39856. the component later on - the AlertWindow won't delete it.
  39857. */
  39858. void addCustomComponent (Component* component);
  39859. /** Returns the number of custom components in the dialog box.
  39860. @see getCustomComponent, addCustomComponent
  39861. */
  39862. int getNumCustomComponents() const;
  39863. /** Returns one of the custom components in the dialog box.
  39864. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  39865. will return 0
  39866. @see getNumCustomComponents, addCustomComponent
  39867. */
  39868. Component* getCustomComponent (int index) const;
  39869. /** Removes one of the custom components in the dialog box.
  39870. Note that this won't delete it, it just removes the component from the window
  39871. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  39872. will return 0
  39873. @returns the component that was removed (or zero)
  39874. @see getNumCustomComponents, addCustomComponent
  39875. */
  39876. Component* removeCustomComponent (int index);
  39877. /** Returns true if the window contains any components other than just buttons.*/
  39878. bool containsAnyExtraComponents() const;
  39879. // easy-to-use message box functions:
  39880. /** Shows a dialog box that just has a message and a single button to get rid of it.
  39881. The box is shown modally, and the method returns after the user
  39882. has clicked the button (or pressed the escape or return keys).
  39883. @param iconType the type of icon to show
  39884. @param title the headline to show at the top of the box
  39885. @param message a longer, more descriptive message to show underneath the
  39886. headline
  39887. @param buttonText the text to show in the button - if this string is empty, the
  39888. default string "ok" (or a localised version) will be used.
  39889. @param associatedComponent if this is non-zero, it specifies the component that the
  39890. alert window should be associated with. Depending on the look
  39891. and feel, this might be used for positioning of the alert window.
  39892. */
  39893. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  39894. const String& title,
  39895. const String& message,
  39896. const String& buttonText = String::empty,
  39897. Component* associatedComponent = 0);
  39898. /** Shows a dialog box with two buttons.
  39899. Ideal for ok/cancel or yes/no choices. The return key can also be used
  39900. to trigger the first button, and the escape key for the second button.
  39901. @param iconType the type of icon to show
  39902. @param title the headline to show at the top of the box
  39903. @param message a longer, more descriptive message to show underneath the
  39904. headline
  39905. @param button1Text the text to show in the first button - if this string is
  39906. empty, the default string "ok" (or a localised version of it)
  39907. will be used.
  39908. @param button2Text the text to show in the second button - if this string is
  39909. empty, the default string "cancel" (or a localised version of it)
  39910. will be used.
  39911. @param associatedComponent if this is non-zero, it specifies the component that the
  39912. alert window should be associated with. Depending on the look
  39913. and feel, this might be used for positioning of the alert window.
  39914. @returns true if button 1 was clicked, false if it was button 2
  39915. */
  39916. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  39917. const String& title,
  39918. const String& message,
  39919. const String& button1Text = String::empty,
  39920. const String& button2Text = String::empty,
  39921. Component* associatedComponent = 0);
  39922. /** Shows a dialog box with three buttons.
  39923. Ideal for yes/no/cancel boxes.
  39924. The escape key can be used to trigger the third button.
  39925. @param iconType the type of icon to show
  39926. @param title the headline to show at the top of the box
  39927. @param message a longer, more descriptive message to show underneath the
  39928. headline
  39929. @param button1Text the text to show in the first button - if an empty string, then
  39930. "yes" will be used (or a localised version of it)
  39931. @param button2Text the text to show in the first button - if an empty string, then
  39932. "no" will be used (or a localised version of it)
  39933. @param button3Text the text to show in the first button - if an empty string, then
  39934. "cancel" will be used (or a localised version of it)
  39935. @param associatedComponent if this is non-zero, it specifies the component that the
  39936. alert window should be associated with. Depending on the look
  39937. and feel, this might be used for positioning of the alert window.
  39938. @returns one of the following values:
  39939. - 0 if the third button was pressed (normally used for 'cancel')
  39940. - 1 if the first button was pressed (normally used for 'yes')
  39941. - 2 if the middle button was pressed (normally used for 'no')
  39942. */
  39943. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  39944. const String& title,
  39945. const String& message,
  39946. const String& button1Text = String::empty,
  39947. const String& button2Text = String::empty,
  39948. const String& button3Text = String::empty,
  39949. Component* associatedComponent = 0);
  39950. /** Shows an operating-system native dialog box.
  39951. @param title the title to use at the top
  39952. @param bodyText the longer message to show
  39953. @param isOkCancel if true, this will show an ok/cancel box, if false,
  39954. it'll show a box with just an ok button
  39955. @returns true if the ok button was pressed, false if they pressed cancel.
  39956. */
  39957. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  39958. const String& bodyText,
  39959. bool isOkCancel);
  39960. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  39961. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39962. methods.
  39963. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39964. */
  39965. enum ColourIds
  39966. {
  39967. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  39968. textColourId = 0x1001810, /**< The colour for the text. */
  39969. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  39970. };
  39971. juce_UseDebuggingNewOperator
  39972. protected:
  39973. /** @internal */
  39974. void paint (Graphics& g);
  39975. /** @internal */
  39976. void mouseDown (const MouseEvent& e);
  39977. /** @internal */
  39978. void mouseDrag (const MouseEvent& e);
  39979. /** @internal */
  39980. bool keyPressed (const KeyPress& key);
  39981. /** @internal */
  39982. void buttonClicked (Button* button);
  39983. /** @internal */
  39984. void lookAndFeelChanged();
  39985. /** @internal */
  39986. void userTriedToCloseWindow();
  39987. /** @internal */
  39988. int getDesktopWindowStyleFlags() const;
  39989. private:
  39990. String text;
  39991. TextLayout textLayout;
  39992. AlertIconType alertIconType;
  39993. ComponentBoundsConstrainer constrainer;
  39994. ComponentDragger dragger;
  39995. Rectangle<int> textArea;
  39996. Array<void*> buttons, textBoxes, comboBoxes;
  39997. Array<void*> progressBars, customComps, textBlocks, allComps;
  39998. StringArray textboxNames, comboBoxNames;
  39999. Font font;
  40000. Component* associatedComponent;
  40001. void updateLayout (bool onlyIncreaseSize);
  40002. // disable copy constructor
  40003. AlertWindow (const AlertWindow&);
  40004. AlertWindow& operator= (const AlertWindow&);
  40005. };
  40006. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  40007. /*** End of inlined file: juce_AlertWindow.h ***/
  40008. class ToggleButton;
  40009. class TextButton;
  40010. class AlertWindow;
  40011. class TextLayout;
  40012. class ScrollBar;
  40013. class BubbleComponent;
  40014. class ComboBox;
  40015. class Button;
  40016. class FilenameComponent;
  40017. class DocumentWindow;
  40018. class ResizableWindow;
  40019. class GroupComponent;
  40020. class MenuBarComponent;
  40021. class DropShadower;
  40022. class GlyphArrangement;
  40023. class PropertyComponent;
  40024. class TableHeaderComponent;
  40025. class Toolbar;
  40026. class ToolbarItemComponent;
  40027. class PopupMenu;
  40028. class ProgressBar;
  40029. class FileBrowserComponent;
  40030. class DirectoryContentsDisplayComponent;
  40031. class FilePreviewComponent;
  40032. class ImageButton;
  40033. class CallOutBox;
  40034. /**
  40035. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  40036. can be used to apply different 'skins' to the application.
  40037. */
  40038. class JUCE_API LookAndFeel
  40039. {
  40040. public:
  40041. /** Creates the default JUCE look and feel. */
  40042. LookAndFeel();
  40043. /** Destructor. */
  40044. virtual ~LookAndFeel();
  40045. /** Returns the current default look-and-feel for a component to use when it
  40046. hasn't got one explicitly set.
  40047. @see setDefaultLookAndFeel
  40048. */
  40049. static LookAndFeel& getDefaultLookAndFeel() throw();
  40050. /** Changes the default look-and-feel.
  40051. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  40052. set to 0, it will revert to using the default one. The
  40053. object passed-in must be deleted by the caller when
  40054. it's no longer needed.
  40055. @see getDefaultLookAndFeel
  40056. */
  40057. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  40058. /** Looks for a colour that has been registered with the given colour ID number.
  40059. If a colour has been set for this ID number using setColour(), then it is
  40060. returned. If none has been set, it will just return Colours::black.
  40061. The colour IDs for various purposes are stored as enums in the components that
  40062. they are relevent to - for an example, see Slider::ColourIds,
  40063. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  40064. If you're looking up a colour for use in drawing a component, it's usually
  40065. best not to call this directly, but to use the Component::findColour() method
  40066. instead. That will first check whether a suitable colour has been registered
  40067. directly with the component, and will fall-back on calling the component's
  40068. LookAndFeel's findColour() method if none is found.
  40069. @see setColour, Component::findColour, Component::setColour
  40070. */
  40071. const Colour findColour (int colourId) const throw();
  40072. /** Registers a colour to be used for a particular purpose.
  40073. For more details, see the comments for findColour().
  40074. @see findColour, Component::findColour, Component::setColour
  40075. */
  40076. void setColour (int colourId, const Colour& colour) throw();
  40077. /** Returns true if the specified colour ID has been explicitly set using the
  40078. setColour() method.
  40079. */
  40080. bool isColourSpecified (int colourId) const throw();
  40081. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  40082. /** Allows you to change the default sans-serif font.
  40083. If you need to supply your own Typeface object for any of the default fonts, rather
  40084. than just supplying the name (e.g. if you want to use an embedded font), then
  40085. you should instead override getTypefaceForFont() to create and return the typeface.
  40086. */
  40087. void setDefaultSansSerifTypefaceName (const String& newName);
  40088. /** Override this to get the chance to swap a component's mouse cursor for a
  40089. customised one.
  40090. */
  40091. virtual const MouseCursor getMouseCursorFor (Component& component);
  40092. /** Draws the lozenge-shaped background for a standard button. */
  40093. virtual void drawButtonBackground (Graphics& g,
  40094. Button& button,
  40095. const Colour& backgroundColour,
  40096. bool isMouseOverButton,
  40097. bool isButtonDown);
  40098. virtual const Font getFontForTextButton (TextButton& button);
  40099. /** Draws the text for a TextButton. */
  40100. virtual void drawButtonText (Graphics& g,
  40101. TextButton& button,
  40102. bool isMouseOverButton,
  40103. bool isButtonDown);
  40104. /** Draws the contents of a standard ToggleButton. */
  40105. virtual void drawToggleButton (Graphics& g,
  40106. ToggleButton& button,
  40107. bool isMouseOverButton,
  40108. bool isButtonDown);
  40109. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  40110. virtual void drawTickBox (Graphics& g,
  40111. Component& component,
  40112. float x, float y, float w, float h,
  40113. bool ticked,
  40114. bool isEnabled,
  40115. bool isMouseOverButton,
  40116. bool isButtonDown);
  40117. /* AlertWindow handling..
  40118. */
  40119. virtual AlertWindow* createAlertWindow (const String& title,
  40120. const String& message,
  40121. const String& button1,
  40122. const String& button2,
  40123. const String& button3,
  40124. AlertWindow::AlertIconType iconType,
  40125. int numButtons,
  40126. Component* associatedComponent);
  40127. virtual void drawAlertBox (Graphics& g,
  40128. AlertWindow& alert,
  40129. const Rectangle<int>& textArea,
  40130. TextLayout& textLayout);
  40131. virtual int getAlertBoxWindowFlags();
  40132. virtual int getAlertWindowButtonHeight();
  40133. virtual const Font getAlertWindowFont();
  40134. /** Draws a progress bar.
  40135. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  40136. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  40137. isn't known). It can use the current time as a basis for playing an animation.
  40138. (Used by progress bars in AlertWindow).
  40139. */
  40140. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  40141. int width, int height,
  40142. double progress, const String& textToShow);
  40143. // Draws a small image that spins to indicate that something's happening..
  40144. // This method should use the current time to animate itself, so just keep
  40145. // repainting it every so often.
  40146. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  40147. int x, int y, int w, int h);
  40148. /** Draws one of the buttons on a scrollbar.
  40149. @param g the context to draw into
  40150. @param scrollbar the bar itself
  40151. @param width the width of the button
  40152. @param height the height of the button
  40153. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  40154. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  40155. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  40156. @param isButtonDown whether the mouse button's held down
  40157. */
  40158. virtual void drawScrollbarButton (Graphics& g,
  40159. ScrollBar& scrollbar,
  40160. int width, int height,
  40161. int buttonDirection,
  40162. bool isScrollbarVertical,
  40163. bool isMouseOverButton,
  40164. bool isButtonDown);
  40165. /** Draws the thumb area of a scrollbar.
  40166. @param g the context to draw into
  40167. @param scrollbar the bar itself
  40168. @param x the x position of the left edge of the thumb area to draw in
  40169. @param y the y position of the top edge of the thumb area to draw in
  40170. @param width the width of the thumb area to draw in
  40171. @param height the height of the thumb area to draw in
  40172. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  40173. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  40174. thumb, or its x position for horizontal bars
  40175. @param thumbSize for vertical bars, the height of the thumb, or its width for
  40176. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  40177. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  40178. currently dragging the thumb
  40179. @param isMouseDown whether the mouse is currently dragging the scrollbar
  40180. */
  40181. virtual void drawScrollbar (Graphics& g,
  40182. ScrollBar& scrollbar,
  40183. int x, int y,
  40184. int width, int height,
  40185. bool isScrollbarVertical,
  40186. int thumbStartPosition,
  40187. int thumbSize,
  40188. bool isMouseOver,
  40189. bool isMouseDown);
  40190. /** Returns the component effect to use for a scrollbar */
  40191. virtual ImageEffectFilter* getScrollbarEffect();
  40192. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  40193. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  40194. /** Returns the default thickness to use for a scrollbar. */
  40195. virtual int getDefaultScrollbarWidth();
  40196. /** Returns the length in pixels to use for a scrollbar button. */
  40197. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  40198. /** Returns a tick shape for use in yes/no boxes, etc. */
  40199. virtual const Path getTickShape (float height);
  40200. /** Returns a cross shape for use in yes/no boxes, etc. */
  40201. virtual const Path getCrossShape (float height);
  40202. /** Draws the + or - box in a treeview. */
  40203. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  40204. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  40205. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  40206. // these return an image from the ImageCache, so use ImageCache::release() to free it
  40207. virtual const Image getDefaultFolderImage();
  40208. virtual const Image getDefaultDocumentFileImage();
  40209. virtual void createFileChooserHeaderText (const String& title,
  40210. const String& instructions,
  40211. GlyphArrangement& destArrangement,
  40212. int width);
  40213. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  40214. const String& filename, Image* icon,
  40215. const String& fileSizeDescription,
  40216. const String& fileTimeDescription,
  40217. bool isDirectory,
  40218. bool isItemSelected,
  40219. int itemIndex);
  40220. virtual Button* createFileBrowserGoUpButton();
  40221. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  40222. DirectoryContentsDisplayComponent* fileListComponent,
  40223. FilePreviewComponent* previewComp,
  40224. ComboBox* currentPathBox,
  40225. TextEditor* filenameBox,
  40226. Button* goUpButton);
  40227. virtual void drawBubble (Graphics& g,
  40228. float tipX, float tipY,
  40229. float boxX, float boxY, float boxW, float boxH);
  40230. /** Fills the background of a popup menu component. */
  40231. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40232. /** Draws one of the items in a popup menu. */
  40233. virtual void drawPopupMenuItem (Graphics& g,
  40234. int width, int height,
  40235. bool isSeparator,
  40236. bool isActive,
  40237. bool isHighlighted,
  40238. bool isTicked,
  40239. bool hasSubMenu,
  40240. const String& text,
  40241. const String& shortcutKeyText,
  40242. Image* image,
  40243. const Colour* const textColour);
  40244. /** Returns the size and style of font to use in popup menus. */
  40245. virtual const Font getPopupMenuFont();
  40246. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  40247. int width, int height,
  40248. bool isScrollUpArrow);
  40249. /** Finds the best size for an item in a popup menu. */
  40250. virtual void getIdealPopupMenuItemSize (const String& text,
  40251. bool isSeparator,
  40252. int standardMenuItemHeight,
  40253. int& idealWidth,
  40254. int& idealHeight);
  40255. virtual int getMenuWindowFlags();
  40256. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40257. bool isMouseOverBar,
  40258. MenuBarComponent& menuBar);
  40259. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40260. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40261. virtual void drawMenuBarItem (Graphics& g,
  40262. int width, int height,
  40263. int itemIndex,
  40264. const String& itemText,
  40265. bool isMouseOverItem,
  40266. bool isMenuOpen,
  40267. bool isMouseOverBar,
  40268. MenuBarComponent& menuBar);
  40269. virtual void drawComboBox (Graphics& g, int width, int height,
  40270. bool isButtonDown,
  40271. int buttonX, int buttonY,
  40272. int buttonW, int buttonH,
  40273. ComboBox& box);
  40274. virtual const Font getComboBoxFont (ComboBox& box);
  40275. virtual Label* createComboBoxTextBox (ComboBox& box);
  40276. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  40277. virtual void drawLabel (Graphics& g, Label& label);
  40278. virtual void drawLinearSlider (Graphics& g,
  40279. int x, int y,
  40280. int width, int height,
  40281. float sliderPos,
  40282. float minSliderPos,
  40283. float maxSliderPos,
  40284. const Slider::SliderStyle style,
  40285. Slider& slider);
  40286. virtual void drawLinearSliderBackground (Graphics& g,
  40287. int x, int y,
  40288. int width, int height,
  40289. float sliderPos,
  40290. float minSliderPos,
  40291. float maxSliderPos,
  40292. const Slider::SliderStyle style,
  40293. Slider& slider);
  40294. virtual void drawLinearSliderThumb (Graphics& g,
  40295. int x, int y,
  40296. int width, int height,
  40297. float sliderPos,
  40298. float minSliderPos,
  40299. float maxSliderPos,
  40300. const Slider::SliderStyle style,
  40301. Slider& slider);
  40302. virtual int getSliderThumbRadius (Slider& slider);
  40303. virtual void drawRotarySlider (Graphics& g,
  40304. int x, int y,
  40305. int width, int height,
  40306. float sliderPosProportional,
  40307. float rotaryStartAngle,
  40308. float rotaryEndAngle,
  40309. Slider& slider);
  40310. virtual Button* createSliderButton (bool isIncrement);
  40311. virtual Label* createSliderTextBox (Slider& slider);
  40312. virtual ImageEffectFilter* getSliderEffect();
  40313. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  40314. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  40315. virtual Button* createFilenameComponentBrowseButton (const String& text);
  40316. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  40317. ComboBox* filenameBox, Button* browseButton);
  40318. virtual void drawCornerResizer (Graphics& g,
  40319. int w, int h,
  40320. bool isMouseOver,
  40321. bool isMouseDragging);
  40322. virtual void drawResizableFrame (Graphics& g,
  40323. int w, int h,
  40324. const BorderSize& borders);
  40325. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  40326. const BorderSize& border,
  40327. ResizableWindow& window);
  40328. virtual void drawResizableWindowBorder (Graphics& g,
  40329. int w, int h,
  40330. const BorderSize& border,
  40331. ResizableWindow& window);
  40332. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  40333. Graphics& g, int w, int h,
  40334. int titleSpaceX, int titleSpaceW,
  40335. const Image* icon,
  40336. bool drawTitleTextOnLeft);
  40337. virtual Button* createDocumentWindowButton (int buttonType);
  40338. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40339. int titleBarX, int titleBarY,
  40340. int titleBarW, int titleBarH,
  40341. Button* minimiseButton,
  40342. Button* maximiseButton,
  40343. Button* closeButton,
  40344. bool positionTitleBarButtonsOnLeft);
  40345. virtual int getDefaultMenuBarHeight();
  40346. virtual DropShadower* createDropShadowerForComponent (Component* component);
  40347. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  40348. int w, int h,
  40349. bool isVerticalBar,
  40350. bool isMouseOver,
  40351. bool isMouseDragging);
  40352. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  40353. const String& text,
  40354. const Justification& position,
  40355. GroupComponent& group);
  40356. virtual void createTabButtonShape (Path& p,
  40357. int width, int height,
  40358. int tabIndex,
  40359. const String& text,
  40360. Button& button,
  40361. TabbedButtonBar::Orientation orientation,
  40362. bool isMouseOver,
  40363. bool isMouseDown,
  40364. bool isFrontTab);
  40365. virtual void fillTabButtonShape (Graphics& g,
  40366. const Path& path,
  40367. const Colour& preferredBackgroundColour,
  40368. int tabIndex,
  40369. const String& text,
  40370. Button& button,
  40371. TabbedButtonBar::Orientation orientation,
  40372. bool isMouseOver,
  40373. bool isMouseDown,
  40374. bool isFrontTab);
  40375. virtual void drawTabButtonText (Graphics& g,
  40376. int x, int y, int w, int h,
  40377. const Colour& preferredBackgroundColour,
  40378. int tabIndex,
  40379. const String& text,
  40380. Button& button,
  40381. TabbedButtonBar::Orientation orientation,
  40382. bool isMouseOver,
  40383. bool isMouseDown,
  40384. bool isFrontTab);
  40385. virtual int getTabButtonOverlap (int tabDepth);
  40386. virtual int getTabButtonSpaceAroundImage();
  40387. virtual int getTabButtonBestWidth (int tabIndex,
  40388. const String& text,
  40389. int tabDepth,
  40390. Button& button);
  40391. virtual void drawTabButton (Graphics& g,
  40392. int w, int h,
  40393. const Colour& preferredColour,
  40394. int tabIndex,
  40395. const String& text,
  40396. Button& button,
  40397. TabbedButtonBar::Orientation orientation,
  40398. bool isMouseOver,
  40399. bool isMouseDown,
  40400. bool isFrontTab);
  40401. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  40402. int w, int h,
  40403. TabbedButtonBar& tabBar,
  40404. TabbedButtonBar::Orientation orientation);
  40405. virtual Button* createTabBarExtrasButton();
  40406. virtual void drawImageButton (Graphics& g, Image* image,
  40407. int imageX, int imageY, int imageW, int imageH,
  40408. const Colour& overlayColour,
  40409. float imageOpacity,
  40410. ImageButton& button);
  40411. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  40412. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  40413. int width, int height,
  40414. bool isMouseOver, bool isMouseDown,
  40415. int columnFlags);
  40416. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  40417. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  40418. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  40419. bool isMouseOver, bool isMouseDown,
  40420. ToolbarItemComponent& component);
  40421. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  40422. const String& text, ToolbarItemComponent& component);
  40423. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  40424. bool isOpen, int width, int height);
  40425. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  40426. PropertyComponent& component);
  40427. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  40428. PropertyComponent& component);
  40429. virtual const Rectangle<int> getPropertyComponentContentPosition (PropertyComponent& component);
  40430. void drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path);
  40431. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  40432. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  40433. /**
  40434. */
  40435. virtual void playAlertSound();
  40436. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  40437. static void drawGlassSphere (Graphics& g,
  40438. float x, float y,
  40439. float diameter,
  40440. const Colour& colour,
  40441. float outlineThickness) throw();
  40442. static void drawGlassPointer (Graphics& g,
  40443. float x, float y,
  40444. float diameter,
  40445. const Colour& colour, float outlineThickness,
  40446. int direction) throw();
  40447. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  40448. static void drawGlassLozenge (Graphics& g,
  40449. float x, float y,
  40450. float width, float height,
  40451. const Colour& colour,
  40452. float outlineThickness,
  40453. float cornerSize,
  40454. bool flatOnLeft, bool flatOnRight,
  40455. bool flatOnTop, bool flatOnBottom) throw();
  40456. juce_UseDebuggingNewOperator
  40457. private:
  40458. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  40459. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  40460. Array <int> colourIds;
  40461. Array <Colour> colours;
  40462. // default typeface names
  40463. String defaultSans, defaultSerif, defaultFixed;
  40464. void drawShinyButtonShape (Graphics& g,
  40465. float x, float y, float w, float h, float maxCornerSize,
  40466. const Colour& baseColour,
  40467. float strokeWidth,
  40468. bool flatOnLeft,
  40469. bool flatOnRight,
  40470. bool flatOnTop,
  40471. bool flatOnBottom) throw();
  40472. LookAndFeel (const LookAndFeel&);
  40473. LookAndFeel& operator= (const LookAndFeel&);
  40474. };
  40475. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  40476. /*** End of inlined file: juce_LookAndFeel.h ***/
  40477. #endif
  40478. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40479. /*** Start of inlined file: juce_OldSchoolLookAndFeel.h ***/
  40480. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40481. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40482. /**
  40483. The original Juce look-and-feel.
  40484. */
  40485. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  40486. {
  40487. public:
  40488. /** Creates the default JUCE look and feel. */
  40489. OldSchoolLookAndFeel();
  40490. /** Destructor. */
  40491. virtual ~OldSchoolLookAndFeel();
  40492. /** Draws the lozenge-shaped background for a standard button. */
  40493. virtual void drawButtonBackground (Graphics& g,
  40494. Button& button,
  40495. const Colour& backgroundColour,
  40496. bool isMouseOverButton,
  40497. bool isButtonDown);
  40498. /** Draws the contents of a standard ToggleButton. */
  40499. virtual void drawToggleButton (Graphics& g,
  40500. ToggleButton& button,
  40501. bool isMouseOverButton,
  40502. bool isButtonDown);
  40503. virtual void drawTickBox (Graphics& g,
  40504. Component& component,
  40505. float x, float y, float w, float h,
  40506. bool ticked,
  40507. bool isEnabled,
  40508. bool isMouseOverButton,
  40509. bool isButtonDown);
  40510. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  40511. int width, int height,
  40512. double progress, const String& textToShow);
  40513. virtual void drawScrollbarButton (Graphics& g,
  40514. ScrollBar& scrollbar,
  40515. int width, int height,
  40516. int buttonDirection,
  40517. bool isScrollbarVertical,
  40518. bool isMouseOverButton,
  40519. bool isButtonDown);
  40520. virtual void drawScrollbar (Graphics& g,
  40521. ScrollBar& scrollbar,
  40522. int x, int y,
  40523. int width, int height,
  40524. bool isScrollbarVertical,
  40525. int thumbStartPosition,
  40526. int thumbSize,
  40527. bool isMouseOver,
  40528. bool isMouseDown);
  40529. virtual ImageEffectFilter* getScrollbarEffect();
  40530. virtual void drawTextEditorOutline (Graphics& g,
  40531. int width, int height,
  40532. TextEditor& textEditor);
  40533. /** Fills the background of a popup menu component. */
  40534. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40535. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40536. bool isMouseOverBar,
  40537. MenuBarComponent& menuBar);
  40538. virtual void drawComboBox (Graphics& g, int width, int height,
  40539. bool isButtonDown,
  40540. int buttonX, int buttonY,
  40541. int buttonW, int buttonH,
  40542. ComboBox& box);
  40543. virtual const Font getComboBoxFont (ComboBox& box);
  40544. virtual void drawLinearSlider (Graphics& g,
  40545. int x, int y,
  40546. int width, int height,
  40547. float sliderPos,
  40548. float minSliderPos,
  40549. float maxSliderPos,
  40550. const Slider::SliderStyle style,
  40551. Slider& slider);
  40552. virtual int getSliderThumbRadius (Slider& slider);
  40553. virtual Button* createSliderButton (bool isIncrement);
  40554. virtual ImageEffectFilter* getSliderEffect();
  40555. virtual void drawCornerResizer (Graphics& g,
  40556. int w, int h,
  40557. bool isMouseOver,
  40558. bool isMouseDragging);
  40559. virtual Button* createDocumentWindowButton (int buttonType);
  40560. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40561. int titleBarX, int titleBarY,
  40562. int titleBarW, int titleBarH,
  40563. Button* minimiseButton,
  40564. Button* maximiseButton,
  40565. Button* closeButton,
  40566. bool positionTitleBarButtonsOnLeft);
  40567. juce_UseDebuggingNewOperator
  40568. private:
  40569. DropShadowEffect scrollbarShadow;
  40570. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  40571. OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  40572. };
  40573. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40574. /*** End of inlined file: juce_OldSchoolLookAndFeel.h ***/
  40575. #endif
  40576. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  40577. #endif
  40578. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  40579. #endif
  40580. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  40581. #endif
  40582. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40583. /*** Start of inlined file: juce_PopupMenuCustomComponent.h ***/
  40584. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40585. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40586. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  40587. @see PopupMenu::addCustomItem
  40588. */
  40589. class JUCE_API PopupMenuCustomComponent : public Component,
  40590. public ReferenceCountedObject
  40591. {
  40592. public:
  40593. /** Destructor. */
  40594. ~PopupMenuCustomComponent();
  40595. /** Chooses the size that this component would like to have.
  40596. Note that the size which this method returns isn't necessarily the one that
  40597. the menu will give it, as it will be stretched to fit the other items in
  40598. the menu.
  40599. */
  40600. virtual void getIdealSize (int& idealWidth,
  40601. int& idealHeight) = 0;
  40602. /** Dismisses the menu indicating that this item has been chosen.
  40603. This will cause the menu to exit from its modal state, returning
  40604. this item's id as the result.
  40605. */
  40606. void triggerMenuItem();
  40607. /** Returns true if this item should be highlighted because the mouse is
  40608. over it.
  40609. You can call this method in your paint() method to find out whether
  40610. to draw a highlight.
  40611. */
  40612. bool isItemHighlighted() const throw() { return isHighlighted; }
  40613. protected:
  40614. /** Constructor.
  40615. If isTriggeredAutomatically is true, then the menu will automatically detect
  40616. a click on this component and use that to trigger it. If it's false, then it's
  40617. up to your class to manually trigger the item if it wants to.
  40618. */
  40619. PopupMenuCustomComponent (bool isTriggeredAutomatically = true);
  40620. private:
  40621. friend class PopupMenu;
  40622. friend class PopupMenu::ItemComponent;
  40623. friend class PopupMenu::Window;
  40624. bool isHighlighted, isTriggeredAutomatically;
  40625. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  40626. PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  40627. };
  40628. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40629. /*** End of inlined file: juce_PopupMenuCustomComponent.h ***/
  40630. #endif
  40631. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  40632. #endif
  40633. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  40634. #endif
  40635. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  40636. #endif
  40637. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  40638. #endif
  40639. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  40640. /*** Start of inlined file: juce_LassoComponent.h ***/
  40641. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  40642. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  40643. /*** Start of inlined file: juce_SelectedItemSet.h ***/
  40644. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40645. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40646. /** Manages a list of selectable items.
  40647. Use one of these to keep a track of things that the user has highlighted, like
  40648. icons or things in a list.
  40649. The class is templated so that you can use it to hold either a set of pointers
  40650. to objects, or a set of ID numbers or handles, for cases where each item may
  40651. not always have a corresponding object.
  40652. To be informed when items are selected/deselected, register a ChangeListener with
  40653. this object.
  40654. @see SelectableObject
  40655. */
  40656. template <class SelectableItemType>
  40657. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  40658. {
  40659. public:
  40660. typedef SelectableItemType ItemType;
  40661. typedef PARAMETER_TYPE (SelectableItemType) ParameterType;
  40662. /** Creates an empty set. */
  40663. SelectedItemSet()
  40664. {
  40665. }
  40666. /** Creates a set based on an array of items. */
  40667. explicit SelectedItemSet (const Array <SelectableItemType>& items)
  40668. : selectedItems (items)
  40669. {
  40670. }
  40671. /** Creates a copy of another set. */
  40672. SelectedItemSet (const SelectedItemSet& other)
  40673. : selectedItems (other.selectedItems)
  40674. {
  40675. }
  40676. /** Creates a copy of another set. */
  40677. SelectedItemSet& operator= (const SelectedItemSet& other)
  40678. {
  40679. if (selectedItems != other.selectedItems)
  40680. {
  40681. selectedItems = other.selectedItems;
  40682. changed();
  40683. }
  40684. return *this;
  40685. }
  40686. /** Destructor. */
  40687. ~SelectedItemSet()
  40688. {
  40689. }
  40690. /** Clears any other currently selected items, and selects this item.
  40691. If this item is already the only thing selected, no change notification
  40692. will be sent out.
  40693. @see addToSelection, addToSelectionBasedOnModifiers
  40694. */
  40695. void selectOnly (ParameterType item)
  40696. {
  40697. if (isSelected (item))
  40698. {
  40699. for (int i = selectedItems.size(); --i >= 0;)
  40700. {
  40701. if (selectedItems.getUnchecked(i) != item)
  40702. {
  40703. deselect (selectedItems.getUnchecked(i));
  40704. i = jmin (i, selectedItems.size());
  40705. }
  40706. }
  40707. }
  40708. else
  40709. {
  40710. deselectAll();
  40711. changed();
  40712. selectedItems.add (item);
  40713. itemSelected (item);
  40714. }
  40715. }
  40716. /** Selects an item.
  40717. If the item is already selected, no change notification will be sent out.
  40718. @see selectOnly, addToSelectionBasedOnModifiers
  40719. */
  40720. void addToSelection (ParameterType item)
  40721. {
  40722. if (! isSelected (item))
  40723. {
  40724. changed();
  40725. selectedItems.add (item);
  40726. itemSelected (item);
  40727. }
  40728. }
  40729. /** Selects or deselects an item.
  40730. This will use the modifier keys to decide whether to deselect other items
  40731. first.
  40732. So if the shift key is held down, the item will be added without deselecting
  40733. anything (same as calling addToSelection() )
  40734. If no modifiers are down, the current selection will be cleared first (same
  40735. as calling selectOnly() )
  40736. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  40737. so it'll be added to the set unless it's already there, in which case it'll be
  40738. deselected.
  40739. If the items that you're selecting can also be dragged, you may need to use the
  40740. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  40741. subtleties of this kind of usage.
  40742. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  40743. */
  40744. void addToSelectionBasedOnModifiers (ParameterType item,
  40745. const ModifierKeys& modifiers)
  40746. {
  40747. if (modifiers.isShiftDown())
  40748. {
  40749. addToSelection (item);
  40750. }
  40751. else if (modifiers.isCommandDown())
  40752. {
  40753. if (isSelected (item))
  40754. deselect (item);
  40755. else
  40756. addToSelection (item);
  40757. }
  40758. else
  40759. {
  40760. selectOnly (item);
  40761. }
  40762. }
  40763. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  40764. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  40765. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  40766. makes it easy to handle multiple-selection of sets of objects that can also
  40767. be dragged.
  40768. For example, if you have several items already selected, and you click on
  40769. one of them (without dragging), then you'd expect this to deselect the other, and
  40770. just select the item you clicked on. But if you had clicked on this item and
  40771. dragged it, you'd have expected them all to stay selected.
  40772. When you call this method, you'll need to store the boolean result, because the
  40773. addToSelectionOnMouseUp() method will need to be know this value.
  40774. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  40775. */
  40776. bool addToSelectionOnMouseDown (ParameterType item,
  40777. const ModifierKeys& modifiers)
  40778. {
  40779. if (isSelected (item))
  40780. {
  40781. return ! modifiers.isPopupMenu();
  40782. }
  40783. else
  40784. {
  40785. addToSelectionBasedOnModifiers (item, modifiers);
  40786. return false;
  40787. }
  40788. }
  40789. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  40790. Call this during a mouseUp callback, when you have previously called the
  40791. addToSelectionOnMouseDown() method during your mouseDown event.
  40792. See addToSelectionOnMouseDown() for more info
  40793. @param item the item to select (or deselect)
  40794. @param modifiers the modifiers from the mouse-up event
  40795. @param wasItemDragged true if your item was dragged during the mouse click
  40796. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  40797. back from the addToSelectionOnMouseDown() call that you
  40798. should have made during the matching mouseDown event
  40799. */
  40800. void addToSelectionOnMouseUp (ParameterType item,
  40801. const ModifierKeys& modifiers,
  40802. const bool wasItemDragged,
  40803. const bool resultOfMouseDownSelectMethod)
  40804. {
  40805. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  40806. addToSelectionBasedOnModifiers (item, modifiers);
  40807. }
  40808. /** Deselects an item. */
  40809. void deselect (ParameterType item)
  40810. {
  40811. const int i = selectedItems.indexOf (item);
  40812. if (i >= 0)
  40813. {
  40814. changed();
  40815. itemDeselected (selectedItems.remove (i));
  40816. }
  40817. }
  40818. /** Deselects all items. */
  40819. void deselectAll()
  40820. {
  40821. if (selectedItems.size() > 0)
  40822. {
  40823. changed();
  40824. for (int i = selectedItems.size(); --i >= 0;)
  40825. {
  40826. itemDeselected (selectedItems.remove (i));
  40827. i = jmin (i, selectedItems.size());
  40828. }
  40829. }
  40830. }
  40831. /** Returns the number of currently selected items.
  40832. @see getSelectedItem
  40833. */
  40834. int getNumSelected() const throw()
  40835. {
  40836. return selectedItems.size();
  40837. }
  40838. /** Returns one of the currently selected items.
  40839. Returns 0 if the index is out-of-range.
  40840. @see getNumSelected
  40841. */
  40842. SelectableItemType getSelectedItem (const int index) const throw()
  40843. {
  40844. return selectedItems [index];
  40845. }
  40846. /** True if this item is currently selected. */
  40847. bool isSelected (ParameterType item) const throw()
  40848. {
  40849. return selectedItems.contains (item);
  40850. }
  40851. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  40852. /** Can be overridden to do special handling when an item is selected.
  40853. For example, if the item is an object, you might want to call it and tell
  40854. it that it's being selected.
  40855. */
  40856. virtual void itemSelected (SelectableItemType item) { (void) item; }
  40857. /** Can be overridden to do special handling when an item is deselected.
  40858. For example, if the item is an object, you might want to call it and tell
  40859. it that it's being deselected.
  40860. */
  40861. virtual void itemDeselected (SelectableItemType item) { (void) item; }
  40862. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  40863. */
  40864. void changed (const bool synchronous = false)
  40865. {
  40866. if (synchronous)
  40867. sendSynchronousChangeMessage (this);
  40868. else
  40869. sendChangeMessage (this);
  40870. }
  40871. juce_UseDebuggingNewOperator
  40872. private:
  40873. Array <SelectableItemType> selectedItems;
  40874. };
  40875. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40876. /*** End of inlined file: juce_SelectedItemSet.h ***/
  40877. /**
  40878. A class used by the LassoComponent to manage the things that it selects.
  40879. This allows the LassoComponent to find out which items are within the lasso,
  40880. and to change the list of selected items.
  40881. @see LassoComponent, SelectedItemSet
  40882. */
  40883. template <class SelectableItemType>
  40884. class LassoSource
  40885. {
  40886. public:
  40887. /** Destructor. */
  40888. virtual ~LassoSource() {}
  40889. /** Returns the set of items that lie within a given lassoable region.
  40890. Your implementation of this method must find all the relevent items that lie
  40891. within the given rectangle. and add them to the itemsFound array.
  40892. The co-ordinates are relative to the top-left of the lasso component's parent
  40893. component. (i.e. they are the same as the size and position of the lasso
  40894. component itself).
  40895. */
  40896. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  40897. const Rectangle<int>& area) = 0;
  40898. /** Returns the SelectedItemSet that the lasso should update.
  40899. This set will be continuously updated by the LassoComponent as it gets
  40900. dragged around, so make sure that you've got a ChangeListener attached to
  40901. the set so that your UI objects will know when the selection changes and
  40902. be able to update themselves appropriately.
  40903. */
  40904. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  40905. };
  40906. /**
  40907. A component that acts as a rectangular selection region, which you drag with
  40908. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  40909. To use one of these:
  40910. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  40911. component, and call its beginLasso() method, giving it a
  40912. suitable LassoSource object that it can use to find out which items are in
  40913. the active area.
  40914. - Each time your parent component gets a mouseDrag event, call dragLasso()
  40915. to update the lasso's position - it will use its LassoSource to calculate and
  40916. update the current selection.
  40917. - After the drag has finished and you get a mouseUp callback, you should call
  40918. endLasso() to clean up. This will make the lasso component invisible, and you
  40919. can remove it from the parent component, or delete it.
  40920. The class takes into account the modifier keys that are being held down while
  40921. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  40922. be added to the original selection; if ctrl or command is pressed, they will be
  40923. xor'ed with any previously selected items.
  40924. @see LassoSource, SelectedItemSet
  40925. */
  40926. template <class SelectableItemType>
  40927. class LassoComponent : public Component
  40928. {
  40929. public:
  40930. /** Creates a Lasso component.
  40931. The fill colour is used to fill the lasso'ed rectangle, and the outline
  40932. colour is used to draw a line around its edge.
  40933. */
  40934. explicit LassoComponent (const int outlineThickness_ = 1)
  40935. : source (0),
  40936. outlineThickness (outlineThickness_)
  40937. {
  40938. }
  40939. /** Destructor. */
  40940. ~LassoComponent()
  40941. {
  40942. }
  40943. /** Call this in your mouseDown event, to initialise a drag.
  40944. Pass in a suitable LassoSource object which the lasso will use to find
  40945. the items and change the selection.
  40946. After using this method to initialise the lasso, repeatedly call dragLasso()
  40947. in your component's mouseDrag callback.
  40948. @see dragLasso, endLasso, LassoSource
  40949. */
  40950. void beginLasso (const MouseEvent& e,
  40951. LassoSource <SelectableItemType>* const lassoSource)
  40952. {
  40953. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  40954. jassert (lassoSource != 0); // the source can't be null!
  40955. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  40956. source = lassoSource;
  40957. if (lassoSource != 0)
  40958. originalSelection = lassoSource->getLassoSelection().getItemArray();
  40959. setSize (0, 0);
  40960. dragStartPos = e.getMouseDownPosition();
  40961. }
  40962. /** Call this in your mouseDrag event, to update the lasso's position.
  40963. This must be repeatedly calling when the mouse is dragged, after you've
  40964. first initialised the lasso with beginLasso().
  40965. This method takes into account the modifier keys that are being held down, so
  40966. if shift is pressed, then the lassoed items will be added to any that were
  40967. previously selected; if ctrl or command is pressed, then they will be xor'ed
  40968. with previously selected items.
  40969. @see beginLasso, endLasso
  40970. */
  40971. void dragLasso (const MouseEvent& e)
  40972. {
  40973. if (source != 0)
  40974. {
  40975. setBounds (Rectangle<int> (dragStartPos, e.getPosition()));
  40976. setVisible (true);
  40977. Array <SelectableItemType> itemsInLasso;
  40978. source->findLassoItemsInArea (itemsInLasso, getBounds());
  40979. if (e.mods.isShiftDown())
  40980. {
  40981. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  40982. itemsInLasso.addArray (originalSelection);
  40983. }
  40984. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  40985. {
  40986. Array <SelectableItemType> originalMinusNew (originalSelection);
  40987. originalMinusNew.removeValuesIn (itemsInLasso);
  40988. itemsInLasso.removeValuesIn (originalSelection);
  40989. itemsInLasso.addArray (originalMinusNew);
  40990. }
  40991. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  40992. }
  40993. }
  40994. /** Call this in your mouseUp event, after the lasso has been dragged.
  40995. @see beginLasso, dragLasso
  40996. */
  40997. void endLasso()
  40998. {
  40999. source = 0;
  41000. originalSelection.clear();
  41001. setVisible (false);
  41002. }
  41003. /** A set of colour IDs to use to change the colour of various aspects of the label.
  41004. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41005. methods.
  41006. Note that you can also use the constants from TextEditor::ColourIds to change the
  41007. colour of the text editor that is opened when a label is editable.
  41008. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41009. */
  41010. enum ColourIds
  41011. {
  41012. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  41013. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  41014. };
  41015. /** @internal */
  41016. void paint (Graphics& g)
  41017. {
  41018. g.fillAll (findColour (lassoFillColourId));
  41019. g.setColour (findColour (lassoOutlineColourId));
  41020. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  41021. // this suggests that you've left a lasso comp lying around after the
  41022. // mouse drag has finished.. Be careful to call endLasso() when you get a
  41023. // mouse-up event.
  41024. jassert (isMouseButtonDownAnywhere());
  41025. }
  41026. /** @internal */
  41027. bool hitTest (int, int) { return false; }
  41028. juce_UseDebuggingNewOperator
  41029. private:
  41030. Array <SelectableItemType> originalSelection;
  41031. LassoSource <SelectableItemType>* source;
  41032. int outlineThickness;
  41033. Point<int> dragStartPos;
  41034. };
  41035. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  41036. /*** End of inlined file: juce_LassoComponent.h ***/
  41037. #endif
  41038. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  41039. #endif
  41040. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  41041. #endif
  41042. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41043. /*** Start of inlined file: juce_MouseHoverDetector.h ***/
  41044. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41045. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41046. /**
  41047. Monitors a component for mouse activity, and triggers a callback
  41048. when the mouse hovers in one place for a specified length of time.
  41049. To use a hover-detector, just create one and call its setHoverComponent()
  41050. method to start it watching a component. You can call setHoverComponent (0)
  41051. to make it inactive.
  41052. (Be careful not to delete a component that's being monitored without first
  41053. stopping or deleting the hover detector).
  41054. */
  41055. class JUCE_API MouseHoverDetector
  41056. {
  41057. public:
  41058. /** Creates a hover detector.
  41059. Initially the object is inactive, and you need to tell it which component
  41060. to monitor, using the setHoverComponent() method.
  41061. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  41062. needs to stay still before the mouseHovered() method
  41063. is invoked. You can change this setting later with
  41064. the setHoverTimeMillisecs() method
  41065. */
  41066. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  41067. /** Destructor. */
  41068. virtual ~MouseHoverDetector();
  41069. /** Changes the time for which the mouse has to stay still before it's considered
  41070. to be hovering.
  41071. */
  41072. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  41073. /** Changes the component that's being monitored for hovering.
  41074. Be careful not to delete a component that's being monitored without first
  41075. stopping or deleting the hover detector.
  41076. */
  41077. void setHoverComponent (Component* const newSourceComponent);
  41078. protected:
  41079. /** Called back when the mouse hovers.
  41080. After the mouse has stayed still over the component for the length of time
  41081. specified by setHoverTimeMillisecs(), this method will be invoked.
  41082. When the mouse is first moved after this callback has occurred, the
  41083. mouseMovedAfterHover() method will be called.
  41084. @param mouseX the mouse's X position relative to the component being monitored
  41085. @param mouseY the mouse's Y position relative to the component being monitored
  41086. */
  41087. virtual void mouseHovered (int mouseX,
  41088. int mouseY) = 0;
  41089. /** Called when the mouse is moved away after just having hovered. */
  41090. virtual void mouseMovedAfterHover() = 0;
  41091. private:
  41092. class JUCE_API HoverDetectorInternal : public MouseListener,
  41093. public Timer
  41094. {
  41095. public:
  41096. MouseHoverDetector* owner;
  41097. int lastX, lastY;
  41098. void timerCallback();
  41099. void mouseEnter (const MouseEvent&);
  41100. void mouseExit (const MouseEvent&);
  41101. void mouseDown (const MouseEvent&);
  41102. void mouseUp (const MouseEvent&);
  41103. void mouseMove (const MouseEvent&);
  41104. void mouseWheelMove (const MouseEvent&, float, float);
  41105. } internalTimer;
  41106. friend class HoverDetectorInternal;
  41107. Component* source;
  41108. int hoverTimeMillisecs;
  41109. bool hasJustHovered;
  41110. void hoverTimerCallback();
  41111. void checkJustHoveredCallback();
  41112. MouseHoverDetector (const MouseHoverDetector&);
  41113. MouseHoverDetector& operator= (const MouseHoverDetector&);
  41114. };
  41115. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41116. /*** End of inlined file: juce_MouseHoverDetector.h ***/
  41117. #endif
  41118. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41119. /*** Start of inlined file: juce_MouseInputSource.h ***/
  41120. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41121. #define __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41122. class Component;
  41123. class ComponentPeer;
  41124. class MouseInputSourceInternal;
  41125. /**
  41126. Represents a linear source of mouse events from a mouse device or individual finger
  41127. in a multi-touch environment.
  41128. Each MouseEvent object contains a reference to the MouseInputSource that generated
  41129. it. In an environment with a single mouse for input, all events will come from the
  41130. same source, but in a multi-touch system, there may be multiple MouseInputSource
  41131. obects active, each representing a stream of events coming from a particular finger.
  41132. Events coming from a single MouseInputSource are always sent in a fixed and predictable
  41133. order: a mouseMove will never be called without a mouseEnter having been sent beforehand,
  41134. the only events that can happen between a mouseDown and its corresponding mouseUp are
  41135. mouseDrags, etc.
  41136. When there are multiple touches arriving from multiple MouseInputSources, their
  41137. event streams may arrive in an interleaved order, so you should use the getIndex()
  41138. method to find out which finger each event came from.
  41139. @see MouseEvent
  41140. */
  41141. class JUCE_API MouseInputSource
  41142. {
  41143. public:
  41144. /** Creates a MouseInputSource.
  41145. You should never actually create a MouseInputSource in your own code - the
  41146. library takes care of managing these objects.
  41147. */
  41148. MouseInputSource (int index, bool isMouseDevice);
  41149. /** Destructor. */
  41150. ~MouseInputSource();
  41151. /** Returns true if this object represents a normal desk-based mouse device. */
  41152. bool isMouse() const;
  41153. /** Returns true if this object represents a source of touch events - i.e. a finger or stylus. */
  41154. bool isTouch() const;
  41155. /** Returns true if this source has an on-screen pointer that can hover over
  41156. items without clicking them.
  41157. */
  41158. bool canHover() const;
  41159. /** Returns true if this source may have a scroll wheel. */
  41160. bool hasMouseWheel() const;
  41161. /** Returns this source's index in the global list of possible sources.
  41162. If the system only has a single mouse, there will only be a single MouseInputSource
  41163. with an index of 0.
  41164. If the system supports multi-touch input, then the index will represent a finger
  41165. number, starting from 0. When the first touch event begins, it will have finger
  41166. number 0, and then if a second touch happens while the first is still down, it
  41167. will have index 1, etc.
  41168. */
  41169. int getIndex() const;
  41170. /** Returns true if this device is currently being pressed. */
  41171. bool isDragging() const;
  41172. /** Returns the last-known screen position of this source. */
  41173. const Point<int> getScreenPosition() const;
  41174. /** Returns a set of modifiers that indicate which buttons are currently
  41175. held down on this device.
  41176. */
  41177. const ModifierKeys getCurrentModifiers() const;
  41178. /** Returns the component that was last known to be under this pointer. */
  41179. Component* getComponentUnderMouse() const;
  41180. /** Tells the device to dispatch a mouse-move event.
  41181. This is asynchronous - the event will occur on the message thread.
  41182. */
  41183. void triggerFakeMove() const;
  41184. /** Returns the number of clicks that should be counted as belonging to the
  41185. current mouse event.
  41186. So the mouse is currently down and it's the second click of a double-click, this
  41187. will return 2.
  41188. */
  41189. int getNumberOfMultipleClicks() const throw();
  41190. /** Returns the time at which the last mouse-down occurred. */
  41191. const Time getLastMouseDownTime() const throw();
  41192. /** Returns the screen position at which the last mouse-down occurred. */
  41193. const Point<int> getLastMouseDownPosition() const throw();
  41194. /** Returns true if this mouse is currently down, and if it has been dragged more
  41195. than a couple of pixels from the place it was pressed.
  41196. */
  41197. bool hasMouseMovedSignificantlySincePressed() const throw();
  41198. bool hasMouseCursor() const throw();
  41199. void showMouseCursor (const MouseCursor& cursor);
  41200. void hideCursor();
  41201. void revealCursor();
  41202. void forceMouseCursorUpdate();
  41203. bool canDoUnboundedMovement() const throw();
  41204. /** Allows the mouse to move beyond the edges of the screen.
  41205. Calling this method when the mouse button is currently pressed will remove the cursor
  41206. from the screen and allow the mouse to (seem to) move beyond the edges of the screen.
  41207. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  41208. can be used for things like custom slider controls or dragging objects around, where
  41209. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  41210. The unbounded mode is automatically turned off when the mouse button is released, or
  41211. it can be turned off explicitly by calling this method again.
  41212. @param isEnabled whether to turn this mode on or off
  41213. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  41214. hidden; if true, it will only be hidden when it
  41215. is moved beyond the edge of the screen
  41216. */
  41217. void enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen = false);
  41218. juce_UseDebuggingNewOperator
  41219. /** @internal */
  41220. void handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, const ModifierKeys& mods);
  41221. /** @internal */
  41222. void handleWheel (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  41223. private:
  41224. friend class Desktop;
  41225. friend class ComponentPeer;
  41226. friend class MouseInputSourceInternal;
  41227. ScopedPointer<MouseInputSourceInternal> pimpl;
  41228. MouseInputSource (const MouseInputSource&);
  41229. MouseInputSource& operator= (const MouseInputSource&);
  41230. };
  41231. #endif // __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41232. /*** End of inlined file: juce_MouseInputSource.h ***/
  41233. #endif
  41234. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  41235. #endif
  41236. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  41237. #endif
  41238. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41239. /*** Start of inlined file: juce_BooleanPropertyComponent.h ***/
  41240. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41241. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41242. /**
  41243. A PropertyComponent that contains an on/off toggle button.
  41244. This type of property component can be used if you have a boolean value to
  41245. toggle on/off.
  41246. @see PropertyComponent
  41247. */
  41248. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  41249. private ButtonListener
  41250. {
  41251. protected:
  41252. /** Creates a button component.
  41253. If you use this constructor, you must override the getState() and setState()
  41254. methods.
  41255. @param propertyName the property name to be passed to the PropertyComponent
  41256. @param buttonTextWhenTrue the text shown in the button when the value is true
  41257. @param buttonTextWhenFalse the text shown in the button when the value is false
  41258. */
  41259. BooleanPropertyComponent (const String& propertyName,
  41260. const String& buttonTextWhenTrue,
  41261. const String& buttonTextWhenFalse);
  41262. public:
  41263. /** Creates a button component.
  41264. @param valueToControl a Value object that this property should refer to.
  41265. @param propertyName the property name to be passed to the PropertyComponent
  41266. @param buttonText the text shown in the ToggleButton component
  41267. */
  41268. BooleanPropertyComponent (const Value& valueToControl,
  41269. const String& propertyName,
  41270. const String& buttonText);
  41271. /** Destructor. */
  41272. ~BooleanPropertyComponent();
  41273. /** Called to change the state of the boolean value. */
  41274. virtual void setState (bool newState);
  41275. /** Must return the current value of the property. */
  41276. virtual bool getState() const;
  41277. /** @internal */
  41278. void paint (Graphics& g);
  41279. /** @internal */
  41280. void refresh();
  41281. /** @internal */
  41282. void buttonClicked (Button*);
  41283. juce_UseDebuggingNewOperator
  41284. private:
  41285. ToggleButton button;
  41286. String onText, offText;
  41287. BooleanPropertyComponent (const BooleanPropertyComponent&);
  41288. BooleanPropertyComponent& operator= (const BooleanPropertyComponent&);
  41289. };
  41290. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41291. /*** End of inlined file: juce_BooleanPropertyComponent.h ***/
  41292. #endif
  41293. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41294. /*** Start of inlined file: juce_ButtonPropertyComponent.h ***/
  41295. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41296. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41297. /**
  41298. A PropertyComponent that contains a button.
  41299. This type of property component can be used if you need a button to trigger some
  41300. kind of action.
  41301. @see PropertyComponent
  41302. */
  41303. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  41304. private ButtonListener
  41305. {
  41306. public:
  41307. /** Creates a button component.
  41308. @param propertyName the property name to be passed to the PropertyComponent
  41309. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  41310. */
  41311. ButtonPropertyComponent (const String& propertyName,
  41312. bool triggerOnMouseDown);
  41313. /** Destructor. */
  41314. ~ButtonPropertyComponent();
  41315. /** Called when the user clicks the button.
  41316. */
  41317. virtual void buttonClicked() = 0;
  41318. /** Returns the string that should be displayed in the button.
  41319. If you need to change this string, call refresh() to update the component.
  41320. */
  41321. virtual const String getButtonText() const = 0;
  41322. /** @internal */
  41323. void refresh();
  41324. /** @internal */
  41325. void buttonClicked (Button*);
  41326. juce_UseDebuggingNewOperator
  41327. private:
  41328. TextButton button;
  41329. ButtonPropertyComponent (const ButtonPropertyComponent&);
  41330. ButtonPropertyComponent& operator= (const ButtonPropertyComponent&);
  41331. };
  41332. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41333. /*** End of inlined file: juce_ButtonPropertyComponent.h ***/
  41334. #endif
  41335. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41336. /*** Start of inlined file: juce_ChoicePropertyComponent.h ***/
  41337. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41338. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41339. /**
  41340. A PropertyComponent that shows its value as a combo box.
  41341. This type of property component contains a list of options and has a
  41342. combo box to choose one.
  41343. Your subclass's constructor must add some strings to the choices StringArray
  41344. and these are shown in the list.
  41345. The getIndex() method will be called to find out which option is the currently
  41346. selected one. If you call refresh() it will call getIndex() to check whether
  41347. the value has changed, and will update the combo box if needed.
  41348. If the user selects a different item from the list, setIndex() will be
  41349. called to let your class process this.
  41350. @see PropertyComponent, PropertyPanel
  41351. */
  41352. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  41353. private ComboBoxListener
  41354. {
  41355. protected:
  41356. /** Creates the component.
  41357. Your subclass's constructor must add a list of options to the choices
  41358. member variable.
  41359. */
  41360. ChoicePropertyComponent (const String& propertyName);
  41361. public:
  41362. /** Creates the component.
  41363. @param valueToControl the value that the combo box will read and control
  41364. @param propertyName the name of the property
  41365. @param choices the list of possible values that the drop-down list will contain
  41366. @param correspondingValues a list of values corresponding to each item in the 'choices' StringArray.
  41367. These are the values that will be read and written to the
  41368. valueToControl value. This array must contain the same number of items
  41369. as the choices array
  41370. */
  41371. ChoicePropertyComponent (const Value& valueToControl,
  41372. const String& propertyName,
  41373. const StringArray& choices,
  41374. const Array <var>& correspondingValues);
  41375. /** Destructor. */
  41376. ~ChoicePropertyComponent();
  41377. /** Called when the user selects an item from the combo box.
  41378. Your subclass must use this callback to update the value that this component
  41379. represents. The index is the index of the chosen item in the choices
  41380. StringArray.
  41381. */
  41382. virtual void setIndex (int newIndex);
  41383. /** Returns the index of the item that should currently be shown.
  41384. This is the index of the item in the choices StringArray that will be
  41385. shown.
  41386. */
  41387. virtual int getIndex() const;
  41388. /** Returns the list of options. */
  41389. const StringArray& getChoices() const;
  41390. /** @internal */
  41391. void refresh();
  41392. /** @internal */
  41393. void comboBoxChanged (ComboBox*);
  41394. juce_UseDebuggingNewOperator
  41395. protected:
  41396. /** The list of options that will be shown in the combo box.
  41397. Your subclass must populate this array in its constructor. If any empty
  41398. strings are added, these will be replaced with horizontal separators (see
  41399. ComboBox::addSeparator() for more info).
  41400. */
  41401. StringArray choices;
  41402. private:
  41403. ComboBox comboBox;
  41404. bool isCustomClass;
  41405. class RemapperValueSource;
  41406. void createComboBox();
  41407. ChoicePropertyComponent (const ChoicePropertyComponent&);
  41408. ChoicePropertyComponent& operator= (const ChoicePropertyComponent&);
  41409. };
  41410. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41411. /*** End of inlined file: juce_ChoicePropertyComponent.h ***/
  41412. #endif
  41413. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  41414. #endif
  41415. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  41416. #endif
  41417. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41418. /*** Start of inlined file: juce_SliderPropertyComponent.h ***/
  41419. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41420. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41421. /**
  41422. A PropertyComponent that shows its value as a slider.
  41423. @see PropertyComponent, Slider
  41424. */
  41425. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  41426. private SliderListener
  41427. {
  41428. protected:
  41429. /** Creates the property component.
  41430. The ranges, interval and skew factor are passed to the Slider component.
  41431. If you need to customise the slider in other ways, your constructor can
  41432. access the slider member variable and change it directly.
  41433. */
  41434. SliderPropertyComponent (const String& propertyName,
  41435. double rangeMin,
  41436. double rangeMax,
  41437. double interval,
  41438. double skewFactor = 1.0);
  41439. public:
  41440. /** Creates the property component.
  41441. The ranges, interval and skew factor are passed to the Slider component.
  41442. If you need to customise the slider in other ways, your constructor can
  41443. access the slider member variable and change it directly.
  41444. */
  41445. SliderPropertyComponent (const Value& valueToControl,
  41446. const String& propertyName,
  41447. double rangeMin,
  41448. double rangeMax,
  41449. double interval,
  41450. double skewFactor = 1.0);
  41451. /** Destructor. */
  41452. ~SliderPropertyComponent();
  41453. /** Called when the user moves the slider to change its value.
  41454. Your subclass must use this method to update whatever item this property
  41455. represents.
  41456. */
  41457. virtual void setValue (double newValue);
  41458. /** Returns the value that the slider should show. */
  41459. virtual double getValue() const;
  41460. /** @internal */
  41461. void refresh();
  41462. /** @internal */
  41463. void changeListenerCallback (void*);
  41464. /** @internal */
  41465. void sliderValueChanged (Slider*);
  41466. juce_UseDebuggingNewOperator
  41467. protected:
  41468. /** The slider component being used in this component.
  41469. Your subclass has access to this in case it needs to customise it in some way.
  41470. */
  41471. Slider slider;
  41472. SliderPropertyComponent (const SliderPropertyComponent&);
  41473. SliderPropertyComponent& operator= (const SliderPropertyComponent&);
  41474. };
  41475. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41476. /*** End of inlined file: juce_SliderPropertyComponent.h ***/
  41477. #endif
  41478. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41479. /*** Start of inlined file: juce_TextPropertyComponent.h ***/
  41480. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41481. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41482. /**
  41483. A PropertyComponent that shows its value as editable text.
  41484. @see PropertyComponent
  41485. */
  41486. class JUCE_API TextPropertyComponent : public PropertyComponent
  41487. {
  41488. protected:
  41489. /** Creates a text property component.
  41490. The maxNumChars is used to set the length of string allowable, and isMultiLine
  41491. sets whether the text editor allows carriage returns.
  41492. @see TextEditor
  41493. */
  41494. TextPropertyComponent (const String& propertyName,
  41495. int maxNumChars,
  41496. bool isMultiLine);
  41497. public:
  41498. /** Creates a text property component.
  41499. The maxNumChars is used to set the length of string allowable, and isMultiLine
  41500. sets whether the text editor allows carriage returns.
  41501. @see TextEditor
  41502. */
  41503. TextPropertyComponent (const Value& valueToControl,
  41504. const String& propertyName,
  41505. int maxNumChars,
  41506. bool isMultiLine);
  41507. /** Destructor. */
  41508. ~TextPropertyComponent();
  41509. /** Called when the user edits the text.
  41510. Your subclass must use this callback to change the value of whatever item
  41511. this property component represents.
  41512. */
  41513. virtual void setText (const String& newText);
  41514. /** Returns the text that should be shown in the text editor.
  41515. */
  41516. virtual const String getText() const;
  41517. /** @internal */
  41518. void refresh();
  41519. /** @internal */
  41520. void textWasEdited();
  41521. juce_UseDebuggingNewOperator
  41522. private:
  41523. Label* textEditor;
  41524. void createEditor (int maxNumChars, bool isMultiLine);
  41525. TextPropertyComponent (const TextPropertyComponent&);
  41526. TextPropertyComponent& operator= (const TextPropertyComponent&);
  41527. };
  41528. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41529. /*** End of inlined file: juce_TextPropertyComponent.h ***/
  41530. #endif
  41531. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41532. /*** Start of inlined file: juce_ActiveXControlComponent.h ***/
  41533. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41534. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41535. #if JUCE_WINDOWS || DOXYGEN
  41536. /**
  41537. A Windows-specific class that can create and embed an ActiveX control inside
  41538. itself.
  41539. To use it, create one of these, put it in place and make sure it's visible in a
  41540. window, then use createControl() to instantiate an ActiveX control. The control
  41541. will then be moved and resized to follow the movements of this component.
  41542. Of course, since the control is a heavyweight window, it'll obliterate any
  41543. juce components that may overlap this component, but that's life.
  41544. */
  41545. class JUCE_API ActiveXControlComponent : public Component
  41546. {
  41547. public:
  41548. /** Create an initially-empty container. */
  41549. ActiveXControlComponent();
  41550. /** Destructor. */
  41551. ~ActiveXControlComponent();
  41552. /** Tries to create an ActiveX control and embed it in this peer.
  41553. The peer controlIID is a pointer to an IID structure - it's treated
  41554. as a void* because when including the Juce headers, you might not always
  41555. have included windows.h first, in which case IID wouldn't be defined.
  41556. e.g. @code
  41557. const IID myIID = __uuidof (QTControl);
  41558. myControlComp->createControl (&myIID);
  41559. @endcode
  41560. */
  41561. bool createControl (const void* controlIID);
  41562. /** Deletes the ActiveX control, if one has been created.
  41563. */
  41564. void deleteControl();
  41565. /** Returns true if a control is currently in use. */
  41566. bool isControlOpen() const throw() { return control != 0; }
  41567. /** Does a QueryInterface call on the embedded control object.
  41568. This allows you to cast the control to whatever type of COM object you need.
  41569. The iid parameter is a pointer to an IID structure - it's treated
  41570. as a void* because when including the Juce headers, you might not always
  41571. have included windows.h first, in which case IID wouldn't be defined, but
  41572. you should just pass a pointer to an IID.
  41573. e.g. @code
  41574. const IID iid = __uuidof (IOleWindow);
  41575. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  41576. if (oleWindow != 0)
  41577. {
  41578. HWND hwnd;
  41579. oleWindow->GetWindow (&hwnd);
  41580. ...
  41581. oleWindow->Release();
  41582. }
  41583. @endcode
  41584. */
  41585. void* queryInterface (const void* iid) const;
  41586. /** Set this to false to stop mouse events being allowed through to the control.
  41587. */
  41588. void setMouseEventsAllowed (bool eventsCanReachControl);
  41589. /** Returns true if mouse events are allowed to get through to the control.
  41590. */
  41591. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  41592. /** @internal */
  41593. void paint (Graphics& g);
  41594. /** @internal */
  41595. void* originalWndProc;
  41596. juce_UseDebuggingNewOperator
  41597. private:
  41598. class Pimpl;
  41599. friend class Pimpl;
  41600. friend class ScopedPointer <Pimpl>;
  41601. ScopedPointer <Pimpl> control;
  41602. bool mouseEventsAllowed;
  41603. void setControlBounds (const Rectangle<int>& bounds) const;
  41604. void setControlVisible (bool b) const;
  41605. ActiveXControlComponent (const ActiveXControlComponent&);
  41606. ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  41607. };
  41608. #endif
  41609. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41610. /*** End of inlined file: juce_ActiveXControlComponent.h ***/
  41611. #endif
  41612. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41613. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  41614. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41615. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41616. /**
  41617. A component containing controls to let the user change the audio settings of
  41618. an AudioDeviceManager object.
  41619. Very easy to use - just create one of these and show it to the user.
  41620. @see AudioDeviceManager
  41621. */
  41622. class JUCE_API AudioDeviceSelectorComponent : public Component,
  41623. public ComboBoxListener,
  41624. public ButtonListener,
  41625. public ChangeListener
  41626. {
  41627. public:
  41628. /** Creates the component.
  41629. If your app needs only output channels, you might ask for a maximum of 0 input
  41630. channels, and the component won't display any options for choosing the input
  41631. channels. And likewise if you're doing an input-only app.
  41632. @param deviceManager the device manager that this component should control
  41633. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  41634. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  41635. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  41636. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  41637. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  41638. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  41639. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  41640. treated as a set of separate mono channels.
  41641. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  41642. are shown, with an "advanced" button that shows the rest of them
  41643. */
  41644. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  41645. const int minAudioInputChannels,
  41646. const int maxAudioInputChannels,
  41647. const int minAudioOutputChannels,
  41648. const int maxAudioOutputChannels,
  41649. const bool showMidiInputOptions,
  41650. const bool showMidiOutputSelector,
  41651. const bool showChannelsAsStereoPairs,
  41652. const bool hideAdvancedOptionsWithButton);
  41653. /** Destructor */
  41654. ~AudioDeviceSelectorComponent();
  41655. /** @internal */
  41656. void resized();
  41657. /** @internal */
  41658. void comboBoxChanged (ComboBox*);
  41659. /** @internal */
  41660. void buttonClicked (Button*);
  41661. /** @internal */
  41662. void changeListenerCallback (void*);
  41663. /** @internal */
  41664. void childBoundsChanged (Component*);
  41665. juce_UseDebuggingNewOperator
  41666. private:
  41667. AudioDeviceManager& deviceManager;
  41668. ScopedPointer<ComboBox> deviceTypeDropDown;
  41669. ScopedPointer<Label> deviceTypeDropDownLabel;
  41670. ScopedPointer<Component> audioDeviceSettingsComp;
  41671. String audioDeviceSettingsCompType;
  41672. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  41673. const bool showChannelsAsStereoPairs;
  41674. const bool hideAdvancedOptionsWithButton;
  41675. class MidiInputSelectorComponentListBox;
  41676. friend class ScopedPointer<MidiInputSelectorComponentListBox>;
  41677. ScopedPointer<MidiInputSelectorComponentListBox> midiInputsList;
  41678. ScopedPointer<ComboBox> midiOutputSelector;
  41679. ScopedPointer<Label> midiInputsLabel, midiOutputLabel;
  41680. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  41681. AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  41682. };
  41683. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41684. /*** End of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  41685. #endif
  41686. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  41687. /*** Start of inlined file: juce_BubbleComponent.h ***/
  41688. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  41689. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  41690. /**
  41691. A component for showing a message or other graphics inside a speech-bubble-shaped
  41692. outline, pointing at a location on the screen.
  41693. This is a base class that just draws and positions the bubble shape, but leaves
  41694. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  41695. that draws a text message.
  41696. To use it, create your subclass, then either add it to a parent component or
  41697. put it on the desktop with addToDesktop (0), use setPosition() to
  41698. resize and position it, then make it visible.
  41699. @see BubbleMessageComponent
  41700. */
  41701. class JUCE_API BubbleComponent : public Component
  41702. {
  41703. protected:
  41704. /** Creates a BubbleComponent.
  41705. Your subclass will need to implement the getContentSize() and paintContent()
  41706. methods to draw the bubble's contents.
  41707. */
  41708. BubbleComponent();
  41709. public:
  41710. /** Destructor. */
  41711. ~BubbleComponent();
  41712. /** A list of permitted placements for the bubble, relative to the co-ordinates
  41713. at which it should be pointing.
  41714. @see setAllowedPlacement
  41715. */
  41716. enum BubblePlacement
  41717. {
  41718. above = 1,
  41719. below = 2,
  41720. left = 4,
  41721. right = 8
  41722. };
  41723. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  41724. point at which it's pointing.
  41725. By default when setPosition() is called, the bubble will place itself either
  41726. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  41727. the values in BubblePlacement to restrict this choice.
  41728. E.g. if you only want your bubble to appear above or below the target area,
  41729. use setAllowedPlacement (above | below);
  41730. @see BubblePlacement
  41731. */
  41732. void setAllowedPlacement (int newPlacement);
  41733. /** Moves and resizes the bubble to point at a given component.
  41734. This will resize the bubble to fit its content, then find a position for it
  41735. so that it's next to, but doesn't overlap the given component.
  41736. It'll put itself either above, below, or to the side of the component depending
  41737. on where there's the most space, honouring any restrictions that were set
  41738. with setAllowedPlacement().
  41739. */
  41740. void setPosition (Component* componentToPointTo);
  41741. /** Moves and resizes the bubble to point at a given point.
  41742. This will resize the bubble to fit its content, then position it
  41743. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  41744. are relative to either the bubble component's parent component if it has one, or
  41745. they are screen co-ordinates if not.
  41746. It'll put itself either above, below, or to the side of this point, depending
  41747. on where there's the most space, honouring any restrictions that were set
  41748. with setAllowedPlacement().
  41749. */
  41750. void setPosition (int arrowTipX,
  41751. int arrowTipY);
  41752. /** Moves and resizes the bubble to point at a given rectangle.
  41753. This will resize the bubble to fit its content, then find a position for it
  41754. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  41755. co-ordinates are relative to either the bubble component's parent component
  41756. if it has one, or they are screen co-ordinates if not.
  41757. It'll put itself either above, below, or to the side of the component depending
  41758. on where there's the most space, honouring any restrictions that were set
  41759. with setAllowedPlacement().
  41760. */
  41761. void setPosition (const Rectangle<int>& rectangleToPointTo);
  41762. protected:
  41763. /** Subclasses should override this to return the size of the content they
  41764. want to draw inside the bubble.
  41765. */
  41766. virtual void getContentSize (int& width, int& height) = 0;
  41767. /** Subclasses should override this to draw their bubble's contents.
  41768. The graphics object's clip region and the dimensions passed in here are
  41769. set up to paint just the rectangle inside the bubble.
  41770. */
  41771. virtual void paintContent (Graphics& g, int width, int height) = 0;
  41772. public:
  41773. /** @internal */
  41774. void paint (Graphics& g);
  41775. juce_UseDebuggingNewOperator
  41776. private:
  41777. Rectangle<int> content;
  41778. int side, allowablePlacements;
  41779. float arrowTipX, arrowTipY;
  41780. DropShadowEffect shadow;
  41781. BubbleComponent (const BubbleComponent&);
  41782. BubbleComponent& operator= (const BubbleComponent&);
  41783. };
  41784. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  41785. /*** End of inlined file: juce_BubbleComponent.h ***/
  41786. #endif
  41787. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  41788. /*** Start of inlined file: juce_BubbleMessageComponent.h ***/
  41789. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  41790. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  41791. /**
  41792. A speech-bubble component that displays a short message.
  41793. This can be used to show a message with the tail of the speech bubble
  41794. pointing to a particular component or location on the screen.
  41795. @see BubbleComponent
  41796. */
  41797. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  41798. private Timer
  41799. {
  41800. public:
  41801. /** Creates a bubble component.
  41802. After creating one a BubbleComponent, do the following:
  41803. - add it to an appropriate parent component, or put it on the
  41804. desktop with Component::addToDesktop (0).
  41805. - use the showAt() method to show a message.
  41806. - it will make itself invisible after it times-out (and can optionally
  41807. also delete itself), or you can reuse it somewhere else by calling
  41808. showAt() again.
  41809. */
  41810. BubbleMessageComponent (int fadeOutLengthMs = 150);
  41811. /** Destructor. */
  41812. ~BubbleMessageComponent();
  41813. /** Shows a message bubble at a particular position.
  41814. This shows the bubble with its stem pointing to the given location
  41815. (co-ordinates being relative to its parent component).
  41816. For details about exactly how it decides where to position itself, see
  41817. BubbleComponent::updatePosition().
  41818. @param x the x co-ordinate of end of the bubble's tail
  41819. @param y the y co-ordinate of end of the bubble's tail
  41820. @param message the text to display
  41821. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  41822. from its parent compnent. If this is 0 or less, it
  41823. will stay there until manually removed.
  41824. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  41825. mouse button is pressed (anywhere on the screen)
  41826. @param deleteSelfAfterUse if true, then the component will delete itself after
  41827. it becomes invisible
  41828. */
  41829. void showAt (int x, int y,
  41830. const String& message,
  41831. int numMillisecondsBeforeRemoving,
  41832. bool removeWhenMouseClicked = true,
  41833. bool deleteSelfAfterUse = false);
  41834. /** Shows a message bubble next to a particular component.
  41835. This shows the bubble with its stem pointing at the given component.
  41836. For details about exactly how it decides where to position itself, see
  41837. BubbleComponent::updatePosition().
  41838. @param component the component that you want to point at
  41839. @param message the text to display
  41840. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  41841. from its parent compnent. If this is 0 or less, it
  41842. will stay there until manually removed.
  41843. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  41844. mouse button is pressed (anywhere on the screen)
  41845. @param deleteSelfAfterUse if true, then the component will delete itself after
  41846. it becomes invisible
  41847. */
  41848. void showAt (Component* component,
  41849. const String& message,
  41850. int numMillisecondsBeforeRemoving,
  41851. bool removeWhenMouseClicked = true,
  41852. bool deleteSelfAfterUse = false);
  41853. /** @internal */
  41854. void getContentSize (int& w, int& h);
  41855. /** @internal */
  41856. void paintContent (Graphics& g, int w, int h);
  41857. /** @internal */
  41858. void timerCallback();
  41859. juce_UseDebuggingNewOperator
  41860. private:
  41861. int fadeOutLength, mouseClickCounter;
  41862. TextLayout textLayout;
  41863. int64 expiryTime;
  41864. bool deleteAfterUse;
  41865. void init (int numMillisecondsBeforeRemoving,
  41866. bool removeWhenMouseClicked,
  41867. bool deleteSelfAfterUse);
  41868. BubbleMessageComponent (const BubbleMessageComponent&);
  41869. BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  41870. };
  41871. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  41872. /*** End of inlined file: juce_BubbleMessageComponent.h ***/
  41873. #endif
  41874. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  41875. /*** Start of inlined file: juce_ColourSelector.h ***/
  41876. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  41877. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  41878. /**
  41879. A component that lets the user choose a colour.
  41880. This shows RGB sliders and a colourspace that the user can pick colours from.
  41881. This class is also a ChangeBroadcaster, so listeners can register to be told
  41882. when the colour changes.
  41883. */
  41884. class JUCE_API ColourSelector : public Component,
  41885. public ChangeBroadcaster,
  41886. protected SliderListener
  41887. {
  41888. public:
  41889. /** Options for the type of selector to show. These are passed into the constructor. */
  41890. enum ColourSelectorOptions
  41891. {
  41892. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  41893. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  41894. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  41895. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  41896. };
  41897. /** Creates a ColourSelector object.
  41898. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  41899. which of the selector's features should be visible.
  41900. The edgeGap value specifies the amount of space to leave around the edge.
  41901. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  41902. colourspace and hue selector components.
  41903. */
  41904. ColourSelector (int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  41905. int edgeGap = 4,
  41906. int gapAroundColourSpaceComponent = 7);
  41907. /** Destructor. */
  41908. ~ColourSelector();
  41909. /** Returns the colour that the user has currently selected.
  41910. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  41911. register to be told when the colour changes.
  41912. @see setCurrentColour
  41913. */
  41914. const Colour getCurrentColour() const;
  41915. /** Changes the colour that is currently being shown.
  41916. */
  41917. void setCurrentColour (const Colour& newColour);
  41918. /** Tells the selector how many preset colour swatches you want to have on the component.
  41919. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  41920. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  41921. their values.
  41922. */
  41923. virtual int getNumSwatches() const;
  41924. /** Called by the selector to find out the colour of one of the swatches.
  41925. Your subclass should return the colour of the swatch with the given index.
  41926. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  41927. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  41928. their values.
  41929. */
  41930. virtual const Colour getSwatchColour (int index) const;
  41931. /** Called by the selector when the user puts a new colour into one of the swatches.
  41932. Your subclass should change the colour of the swatch with the given index.
  41933. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  41934. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  41935. their values.
  41936. */
  41937. virtual void setSwatchColour (int index, const Colour& newColour) const;
  41938. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  41939. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41940. methods.
  41941. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41942. */
  41943. enum ColourIds
  41944. {
  41945. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  41946. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  41947. };
  41948. juce_UseDebuggingNewOperator
  41949. private:
  41950. class ColourSpaceView;
  41951. class HueSelectorComp;
  41952. class SwatchComponent;
  41953. friend class ColourSpaceView;
  41954. friend class HueSelectorComp;
  41955. Colour colour;
  41956. float h, s, v;
  41957. Slider* sliders[4];
  41958. ColourSpaceView* colourSpace;
  41959. HueSelectorComp* hueSelector;
  41960. OwnedArray <SwatchComponent> swatchComponents;
  41961. const int flags;
  41962. int topSpace, edgeGap;
  41963. void setHue (float newH);
  41964. void setSV (float newS, float newV);
  41965. void updateHSV();
  41966. void update();
  41967. void sliderValueChanged (Slider*);
  41968. void paint (Graphics& g);
  41969. void resized();
  41970. ColourSelector (const ColourSelector&);
  41971. ColourSelector& operator= (const ColourSelector&);
  41972. // this constructor is here temporarily to prevent old code compiling, because the parameters
  41973. // have changed - if you get an error here, update your code to use the new constructor instead..
  41974. // (xxx - note to self: remember to remove this at some point in the future)
  41975. ColourSelector (bool);
  41976. };
  41977. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  41978. /*** End of inlined file: juce_ColourSelector.h ***/
  41979. #endif
  41980. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  41981. #endif
  41982. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  41983. /*** Start of inlined file: juce_MagnifierComponent.h ***/
  41984. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  41985. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  41986. /**
  41987. A component that contains another component, and can magnify or shrink it.
  41988. This component will continually update its size so that it fits the zoomed
  41989. version of the content component that you put inside it, so don't try to
  41990. change the size of this component directly - instead change that of the
  41991. content component.
  41992. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  41993. to remap mouse events correctly. This means that the content component won't
  41994. appear to be a direct child of this component, and instead will think its
  41995. on the desktop.
  41996. */
  41997. class JUCE_API MagnifierComponent : public Component
  41998. {
  41999. public:
  42000. /** Creates a MagnifierComponent.
  42001. This component will continually update its size so that it fits the zoomed
  42002. version of the content component that you put inside it, so don't try to
  42003. change the size of this component directly - instead change that of the
  42004. content component.
  42005. @param contentComponent the component to add as the magnified one
  42006. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  42007. be deleted when this component is deleted. If false,
  42008. it's the caller's responsibility to delete it later.
  42009. */
  42010. MagnifierComponent (Component* contentComponent,
  42011. bool deleteContentCompWhenNoLongerNeeded);
  42012. /** Destructor. */
  42013. ~MagnifierComponent();
  42014. /** Returns the current content component. */
  42015. Component* getContentComponent() const { return content; }
  42016. /** Changes the zoom level.
  42017. The scale factor must be greater than zero. Values less than 1 will shrink the
  42018. image; values greater than 1 will multiply its size by this amount.
  42019. When this is called, this component will change its size to fit the full extent
  42020. of the newly zoomed content.
  42021. */
  42022. void setScaleFactor (double newScaleFactor);
  42023. /** Returns the current zoom factor. */
  42024. double getScaleFactor() const { return scaleFactor; }
  42025. /** Changes the quality setting used to rescale the graphics.
  42026. */
  42027. void setResamplingQuality (Graphics::ResamplingQuality newQuality);
  42028. juce_UseDebuggingNewOperator
  42029. /** @internal */
  42030. void childBoundsChanged (Component*);
  42031. private:
  42032. Component* content;
  42033. Component* holderComp;
  42034. double scaleFactor;
  42035. ComponentPeer* peer;
  42036. bool deleteContent;
  42037. Graphics::ResamplingQuality quality;
  42038. MouseInputSource mouseSource;
  42039. void paint (Graphics& g);
  42040. void mouseDown (const MouseEvent& e);
  42041. void mouseUp (const MouseEvent& e);
  42042. void mouseDrag (const MouseEvent& e);
  42043. void mouseMove (const MouseEvent& e);
  42044. void mouseEnter (const MouseEvent& e);
  42045. void mouseExit (const MouseEvent& e);
  42046. void mouseWheelMove (const MouseEvent& e, float, float);
  42047. void passOnMouseEventToPeer (const MouseEvent& e);
  42048. int scaleInt (int n) const;
  42049. MagnifierComponent (const MagnifierComponent&);
  42050. MagnifierComponent& operator= (const MagnifierComponent&);
  42051. };
  42052. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  42053. /*** End of inlined file: juce_MagnifierComponent.h ***/
  42054. #endif
  42055. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42056. /*** Start of inlined file: juce_MidiKeyboardComponent.h ***/
  42057. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42058. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42059. /**
  42060. A component that displays a piano keyboard, whose notes can be clicked on.
  42061. This component will mimic a physical midi keyboard, showing the current state of
  42062. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  42063. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  42064. Another feature is that the computer keyboard can also be used to play notes. By
  42065. default it maps the top two rows of a standard querty keyboard to the notes, but
  42066. these can be remapped if needed. It will only respond to keypresses when it has
  42067. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  42068. The component is also a ChangeBroadcaster, so if you want to be informed when the
  42069. keyboard is scrolled, you can register a ChangeListener for callbacks.
  42070. @see MidiKeyboardState
  42071. */
  42072. class JUCE_API MidiKeyboardComponent : public Component,
  42073. public MidiKeyboardStateListener,
  42074. public ChangeBroadcaster,
  42075. private Timer,
  42076. private AsyncUpdater
  42077. {
  42078. public:
  42079. /** The direction of the keyboard.
  42080. @see setOrientation
  42081. */
  42082. enum Orientation
  42083. {
  42084. horizontalKeyboard,
  42085. verticalKeyboardFacingLeft,
  42086. verticalKeyboardFacingRight,
  42087. };
  42088. /** Creates a MidiKeyboardComponent.
  42089. @param state the midi keyboard model that this component will represent
  42090. @param orientation whether the keyboard is horizonal or vertical
  42091. */
  42092. MidiKeyboardComponent (MidiKeyboardState& state,
  42093. Orientation orientation);
  42094. /** Destructor. */
  42095. ~MidiKeyboardComponent();
  42096. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  42097. on the component.
  42098. Values are 0 to 1.0, where 1.0 is the heaviest.
  42099. @see setMidiChannel
  42100. */
  42101. void setVelocity (float velocity, bool useMousePositionForVelocity);
  42102. /** Changes the midi channel number that will be used for events triggered by clicking
  42103. on the component.
  42104. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  42105. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  42106. Although this is the channel used for outgoing events, the component can display
  42107. incoming events from more than one channel - see setMidiChannelsToDisplay()
  42108. @see setVelocity
  42109. */
  42110. void setMidiChannel (int midiChannelNumber);
  42111. /** Returns the midi channel that the keyboard is using for midi messages.
  42112. @see setMidiChannel
  42113. */
  42114. int getMidiChannel() const throw() { return midiChannel; }
  42115. /** Sets a mask to indicate which incoming midi channels should be represented by
  42116. key movements.
  42117. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  42118. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  42119. in this mask, the on-screen keys will also go down.
  42120. By default, this mask is set to 0xffff (all channels displayed).
  42121. @see setMidiChannel
  42122. */
  42123. void setMidiChannelsToDisplay (int midiChannelMask);
  42124. /** Returns the current set of midi channels represented by the component.
  42125. This is the value that was set with setMidiChannelsToDisplay().
  42126. */
  42127. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  42128. /** Changes the width used to draw the white keys. */
  42129. void setKeyWidth (float widthInPixels);
  42130. /** Returns the width that was set by setKeyWidth(). */
  42131. float getKeyWidth() const throw() { return keyWidth; }
  42132. /** Changes the keyboard's current direction. */
  42133. void setOrientation (Orientation newOrientation);
  42134. /** Returns the keyboard's current direction. */
  42135. const Orientation getOrientation() const throw() { return orientation; }
  42136. /** Sets the range of midi notes that the keyboard will be limited to.
  42137. By default the range is 0 to 127 (inclusive), but you can limit this if you
  42138. only want a restricted set of the keys to be shown.
  42139. Note that the values here are inclusive and must be between 0 and 127.
  42140. */
  42141. void setAvailableRange (int lowestNote,
  42142. int highestNote);
  42143. /** Returns the first note in the available range.
  42144. @see setAvailableRange
  42145. */
  42146. int getRangeStart() const throw() { return rangeStart; }
  42147. /** Returns the last note in the available range.
  42148. @see setAvailableRange
  42149. */
  42150. int getRangeEnd() const throw() { return rangeEnd; }
  42151. /** If the keyboard extends beyond the size of the component, this will scroll
  42152. it to show the given key at the start.
  42153. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  42154. base class to send a callback to any ChangeListeners that have been registered.
  42155. */
  42156. void setLowestVisibleKey (int noteNumber);
  42157. /** Returns the number of the first key shown in the component.
  42158. @see setLowestVisibleKey
  42159. */
  42160. int getLowestVisibleKey() const throw() { return firstKey; }
  42161. /** Returns the length of the black notes.
  42162. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  42163. */
  42164. int getBlackNoteLength() const throw() { return blackNoteLength; }
  42165. /** If set to true, then scroll buttons will appear at either end of the keyboard
  42166. if there are too many notes to fit them all in the component at once.
  42167. */
  42168. void setScrollButtonsVisible (bool canScroll);
  42169. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  42170. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42171. methods.
  42172. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42173. */
  42174. enum ColourIds
  42175. {
  42176. whiteNoteColourId = 0x1005000,
  42177. blackNoteColourId = 0x1005001,
  42178. keySeparatorLineColourId = 0x1005002,
  42179. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  42180. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  42181. textLabelColourId = 0x1005005,
  42182. upDownButtonBackgroundColourId = 0x1005006,
  42183. upDownButtonArrowColourId = 0x1005007
  42184. };
  42185. /** Returns the position within the component of the left-hand edge of a key.
  42186. Depending on the keyboard's orientation, this may be a horizontal or vertical
  42187. distance, in either direction.
  42188. */
  42189. int getKeyStartPosition (const int midiNoteNumber) const;
  42190. /** Deletes all key-mappings.
  42191. @see setKeyPressForNote
  42192. */
  42193. void clearKeyMappings();
  42194. /** Maps a key-press to a given note.
  42195. @param key the key that should trigger the note
  42196. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  42197. be. The actual midi note that gets played will be
  42198. this value + (12 * the current base octave). To change
  42199. the base octave, see setKeyPressBaseOctave()
  42200. */
  42201. void setKeyPressForNote (const KeyPress& key,
  42202. int midiNoteOffsetFromC);
  42203. /** Removes any key-mappings for a given note.
  42204. For a description of what the note number means, see setKeyPressForNote().
  42205. */
  42206. void removeKeyPressForNote (int midiNoteOffsetFromC);
  42207. /** Changes the base note above which key-press-triggered notes are played.
  42208. The set of key-mappings that trigger notes can be moved up and down to cover
  42209. the entire scale using this method.
  42210. The value passed in is an octave number between 0 and 10 (inclusive), and
  42211. indicates which C is the base note to which the key-mapped notes are
  42212. relative.
  42213. */
  42214. void setKeyPressBaseOctave (int newOctaveNumber);
  42215. /** This sets the octave number which is shown as the octave number for middle C.
  42216. This affects only the default implementation of getWhiteNoteText(), which
  42217. passes this octave number to MidiMessage::getMidiNoteName() in order to
  42218. get the note text. See MidiMessage::getMidiNoteName() for more info about
  42219. the parameter.
  42220. By default this value is set to 3.
  42221. @see getOctaveForMiddleC
  42222. */
  42223. void setOctaveForMiddleC (int octaveNumForMiddleC);
  42224. /** This returns the value set by setOctaveForMiddleC().
  42225. @see setOctaveForMiddleC
  42226. */
  42227. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  42228. /** @internal */
  42229. void paint (Graphics& g);
  42230. /** @internal */
  42231. void resized();
  42232. /** @internal */
  42233. void mouseMove (const MouseEvent& e);
  42234. /** @internal */
  42235. void mouseDrag (const MouseEvent& e);
  42236. /** @internal */
  42237. void mouseDown (const MouseEvent& e);
  42238. /** @internal */
  42239. void mouseUp (const MouseEvent& e);
  42240. /** @internal */
  42241. void mouseEnter (const MouseEvent& e);
  42242. /** @internal */
  42243. void mouseExit (const MouseEvent& e);
  42244. /** @internal */
  42245. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  42246. /** @internal */
  42247. void timerCallback();
  42248. /** @internal */
  42249. bool keyStateChanged (bool isKeyDown);
  42250. /** @internal */
  42251. void focusLost (FocusChangeType cause);
  42252. /** @internal */
  42253. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  42254. /** @internal */
  42255. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  42256. /** @internal */
  42257. void handleAsyncUpdate();
  42258. /** @internal */
  42259. void colourChanged();
  42260. juce_UseDebuggingNewOperator
  42261. protected:
  42262. friend class MidiKeyboardUpDownButton;
  42263. /** Draws a white note in the given rectangle.
  42264. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  42265. currently pressed down.
  42266. When doing this, be sure to note the keyboard's orientation.
  42267. */
  42268. virtual void drawWhiteNote (int midiNoteNumber,
  42269. Graphics& g,
  42270. int x, int y, int w, int h,
  42271. bool isDown, bool isOver,
  42272. const Colour& lineColour,
  42273. const Colour& textColour);
  42274. /** Draws a black note in the given rectangle.
  42275. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  42276. currently pressed down.
  42277. When doing this, be sure to note the keyboard's orientation.
  42278. */
  42279. virtual void drawBlackNote (int midiNoteNumber,
  42280. Graphics& g,
  42281. int x, int y, int w, int h,
  42282. bool isDown, bool isOver,
  42283. const Colour& noteFillColour);
  42284. /** Allows text to be drawn on the white notes.
  42285. By default this is used to label the C in each octave, but could be used for other things.
  42286. @see setOctaveForMiddleC
  42287. */
  42288. virtual const String getWhiteNoteText (const int midiNoteNumber);
  42289. /** Draws the up and down buttons that change the base note. */
  42290. virtual void drawUpDownButton (Graphics& g, int w, int h,
  42291. const bool isMouseOver,
  42292. const bool isButtonPressed,
  42293. const bool movesOctavesUp);
  42294. /** Callback when the mouse is clicked on a key.
  42295. You could use this to do things like handle right-clicks on keys, etc.
  42296. Return true if you want the click to trigger the note, or false if you
  42297. want to handle it yourself and not have the note played.
  42298. @see mouseDraggedToKey
  42299. */
  42300. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  42301. /** Callback when the mouse is dragged from one key onto another.
  42302. @see mouseDownOnKey
  42303. */
  42304. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  42305. /** Calculates the positon of a given midi-note.
  42306. This can be overridden to create layouts with custom key-widths.
  42307. @param midiNoteNumber the note to find
  42308. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  42309. @param x the x position of the left-hand edge of the key (this method
  42310. always works in terms of a horizontal keyboard)
  42311. @param w the width of the key
  42312. */
  42313. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  42314. int& x, int& w) const;
  42315. private:
  42316. MidiKeyboardState& state;
  42317. int xOffset, blackNoteLength;
  42318. float keyWidth;
  42319. Orientation orientation;
  42320. int midiChannel, midiInChannelMask;
  42321. float velocity;
  42322. int noteUnderMouse, mouseDownNote;
  42323. BigInteger keysPressed, keysCurrentlyDrawnDown;
  42324. int rangeStart, rangeEnd, firstKey;
  42325. bool canScroll, mouseDragging, useMousePositionForVelocity;
  42326. Button* scrollDown;
  42327. Button* scrollUp;
  42328. Array <KeyPress> keyPresses;
  42329. Array <int> keyPressNotes;
  42330. int keyMappingOctave;
  42331. int octaveNumForMiddleC;
  42332. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  42333. int xyToNote (const Point<int>& pos, float& mousePositionVelocity);
  42334. int remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const;
  42335. void resetAnyKeysInUse();
  42336. void updateNoteUnderMouse (const Point<int>& pos);
  42337. void repaintNote (const int midiNoteNumber);
  42338. MidiKeyboardComponent (const MidiKeyboardComponent&);
  42339. MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  42340. };
  42341. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42342. /*** End of inlined file: juce_MidiKeyboardComponent.h ***/
  42343. #endif
  42344. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42345. /*** Start of inlined file: juce_NSViewComponent.h ***/
  42346. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42347. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42348. #if ! DOXYGEN
  42349. class NSViewComponentInternal;
  42350. #endif
  42351. #if JUCE_MAC || DOXYGEN
  42352. /**
  42353. A Mac-specific class that can create and embed an NSView inside itself.
  42354. To use it, create one of these, put it in place and make sure it's visible in a
  42355. window, then use setView() to assign an NSView to it. The view will then be
  42356. moved and resized to follow the movements of this component.
  42357. Of course, since the view is a native object, it'll obliterate any
  42358. juce components that may overlap this component, but that's life.
  42359. */
  42360. class JUCE_API NSViewComponent : public Component
  42361. {
  42362. public:
  42363. /** Create an initially-empty container. */
  42364. NSViewComponent();
  42365. /** Destructor. */
  42366. ~NSViewComponent();
  42367. /** Assigns an NSView to this peer.
  42368. The view will be retained and released by this component for as long as
  42369. it is needed. To remove the current view, just call setView (0).
  42370. Note: a void* is used here to avoid including the cocoa headers as
  42371. part of the juce.h, but the method expects an NSView*.
  42372. */
  42373. void setView (void* nsView);
  42374. /** Returns the current NSView.
  42375. Note: a void* is returned here to avoid including the cocoa headers as
  42376. a requirement of juce.h, so you should just cast the object to an NSView*.
  42377. */
  42378. void* getView() const;
  42379. /** @internal */
  42380. void paint (Graphics& g);
  42381. juce_UseDebuggingNewOperator
  42382. private:
  42383. friend class NSViewComponentInternal;
  42384. ScopedPointer <NSViewComponentInternal> info;
  42385. NSViewComponent (const NSViewComponent&);
  42386. NSViewComponent& operator= (const NSViewComponent&);
  42387. };
  42388. #endif
  42389. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42390. /*** End of inlined file: juce_NSViewComponent.h ***/
  42391. #endif
  42392. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42393. /*** Start of inlined file: juce_OpenGLComponent.h ***/
  42394. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42395. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42396. // this is used to disable OpenGL, and is defined in juce_Config.h
  42397. #if JUCE_OPENGL || DOXYGEN
  42398. /**
  42399. Represents the various properties of an OpenGL bitmap format.
  42400. @see OpenGLComponent::setPixelFormat
  42401. */
  42402. class JUCE_API OpenGLPixelFormat
  42403. {
  42404. public:
  42405. /** Creates an OpenGLPixelFormat.
  42406. The default constructor just initialises the object as a simple 8-bit
  42407. RGBA format.
  42408. */
  42409. OpenGLPixelFormat (int bitsPerRGBComponent = 8,
  42410. int alphaBits = 8,
  42411. int depthBufferBits = 16,
  42412. int stencilBufferBits = 0);
  42413. OpenGLPixelFormat (const OpenGLPixelFormat&);
  42414. OpenGLPixelFormat& operator= (const OpenGLPixelFormat&);
  42415. bool operator== (const OpenGLPixelFormat&) const;
  42416. int redBits; /**< The number of bits per pixel to use for the red channel. */
  42417. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  42418. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  42419. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  42420. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  42421. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  42422. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  42423. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  42424. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  42425. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  42426. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  42427. /** Returns a list of all the pixel formats that can be used in this system.
  42428. A reference component is needed in case there are multiple screens with different
  42429. capabilities - in which case, the one that the component is on will be used.
  42430. */
  42431. static void getAvailablePixelFormats (Component* component,
  42432. OwnedArray <OpenGLPixelFormat>& results);
  42433. juce_UseDebuggingNewOperator
  42434. };
  42435. /**
  42436. A base class for types of OpenGL context.
  42437. An OpenGLComponent will supply its own context for drawing in its window.
  42438. */
  42439. class JUCE_API OpenGLContext
  42440. {
  42441. public:
  42442. /** Destructor. */
  42443. virtual ~OpenGLContext();
  42444. /** Makes this context the currently active one. */
  42445. virtual bool makeActive() const throw() = 0;
  42446. /** If this context is currently active, it is disactivated. */
  42447. virtual bool makeInactive() const throw() = 0;
  42448. /** Returns true if this context is currently active. */
  42449. virtual bool isActive() const throw() = 0;
  42450. /** Swaps the buffers (if the context can do this). */
  42451. virtual void swapBuffers() = 0;
  42452. /** Sets whether the context checks the vertical sync before swapping.
  42453. The value is the number of frames to allow between buffer-swapping. This is
  42454. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  42455. and greater numbers indicate that it should swap less often.
  42456. Returns true if it sets the value successfully.
  42457. */
  42458. virtual bool setSwapInterval (int numFramesPerSwap) = 0;
  42459. /** Returns the current swap-sync interval.
  42460. See setSwapInterval() for info about the value returned.
  42461. */
  42462. virtual int getSwapInterval() const = 0;
  42463. /** Returns the pixel format being used by this context. */
  42464. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  42465. /** For windowed contexts, this moves the context within the bounds of
  42466. its parent window.
  42467. */
  42468. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  42469. /** For windowed contexts, this triggers a repaint of the window.
  42470. (Not relevent on all platforms).
  42471. */
  42472. virtual void repaint() = 0;
  42473. /** Returns an OS-dependent handle to the raw GL context.
  42474. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  42475. a GLXContext.
  42476. */
  42477. virtual void* getRawContext() const throw() = 0;
  42478. /** Returns the context that's currently in active use by the calling thread.
  42479. Returns 0 if there isn't an active context.
  42480. */
  42481. static OpenGLContext* getCurrentContext();
  42482. juce_UseDebuggingNewOperator
  42483. protected:
  42484. OpenGLContext() throw();
  42485. };
  42486. /**
  42487. A component that contains an OpenGL canvas.
  42488. Override this, add it to whatever component you want to, and use the renderOpenGL()
  42489. method to draw its contents.
  42490. */
  42491. class JUCE_API OpenGLComponent : public Component
  42492. {
  42493. public:
  42494. /** Used to select the type of openGL API to use, if more than one choice is available
  42495. on a particular platform.
  42496. */
  42497. enum OpenGLType
  42498. {
  42499. openGLDefault = 0,
  42500. #if JUCE_IPHONE
  42501. openGLES1, /**< On the iPhone, this selects openGL ES 1.0 */
  42502. openGLES2 /**< On the iPhone, this selects openGL ES 2.0 */
  42503. #endif
  42504. };
  42505. /** Creates an OpenGLComponent. */
  42506. OpenGLComponent (OpenGLType type = openGLDefault);
  42507. /** Destructor. */
  42508. ~OpenGLComponent();
  42509. /** Changes the pixel format used by this component.
  42510. @see OpenGLPixelFormat::getAvailablePixelFormats()
  42511. */
  42512. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  42513. /** Returns the pixel format that this component is currently using. */
  42514. const OpenGLPixelFormat getPixelFormat() const;
  42515. /** Specifies an OpenGL context which should be shared with the one that this
  42516. component is using.
  42517. This is an OpenGL feature that lets two contexts share their texture data.
  42518. Note that this pointer is stored by the component, and when the component
  42519. needs to recreate its internal context for some reason, the same context
  42520. will be used again to share lists. So if you pass a context in here,
  42521. don't delete the context while this component is still using it! You can
  42522. call shareWith (0) to stop this component from sharing with it.
  42523. */
  42524. void shareWith (OpenGLContext* contextToShareListsWith);
  42525. /** Returns the context that this component is sharing with.
  42526. @see shareWith
  42527. */
  42528. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  42529. /** Flips the openGL buffers over. */
  42530. void swapBuffers();
  42531. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  42532. When this is called, makeCurrentContextActive() will already have been called
  42533. for you, so you just need to draw.
  42534. */
  42535. virtual void renderOpenGL() = 0;
  42536. /** This method is called when the component creates a new OpenGL context.
  42537. A new context may be created when the component is first used, or when it
  42538. is moved to a different window, or when the window is hidden and re-shown,
  42539. etc.
  42540. You can use this callback as an opportunity to set up things like textures
  42541. that your context needs.
  42542. New contexts are created on-demand by the makeCurrentContextActive() method - so
  42543. if the context is deleted, e.g. by changing the pixel format or window, no context
  42544. will be created until the next call to makeCurrentContextActive(), which will
  42545. synchronously create one and call this method. This means that if you're using
  42546. a non-GUI thread for rendering, you can make sure this method is be called by
  42547. your renderer thread.
  42548. When this callback happens, the context will already have been made current
  42549. using the makeCurrentContextActive() method, so there's no need to call it
  42550. again in your code.
  42551. */
  42552. virtual void newOpenGLContextCreated() = 0;
  42553. /** Returns the context that will draw into this component.
  42554. This may return 0 if the component is currently invisible or hasn't currently
  42555. got a context. The context object can be deleted and a new one created during
  42556. the lifetime of this component, and there may be times when it doesn't have one.
  42557. @see newOpenGLContextCreated()
  42558. */
  42559. OpenGLContext* getCurrentContext() const throw() { return context; }
  42560. /** Makes this component the current openGL context.
  42561. You might want to use this in things like your resize() method, before calling
  42562. GL commands.
  42563. If this returns false, then the context isn't active, so you should avoid
  42564. making any calls.
  42565. This call may actually create a context if one isn't currently initialised. If
  42566. it does this, it will also synchronously call the newOpenGLContextCreated()
  42567. method to let you initialise it as necessary.
  42568. @see OpenGLContext::makeActive
  42569. */
  42570. bool makeCurrentContextActive();
  42571. /** Stops the current component being the active OpenGL context.
  42572. This is the opposite of makeCurrentContextActive()
  42573. @see OpenGLContext::makeInactive
  42574. */
  42575. void makeCurrentContextInactive();
  42576. /** Returns true if this component is the active openGL context for the
  42577. current thread.
  42578. @see OpenGLContext::isActive
  42579. */
  42580. bool isActiveContext() const throw();
  42581. /** Calls the rendering callback, and swaps the buffers afterwards.
  42582. This is called automatically by paint() when the component needs to be rendered.
  42583. It can be overridden if you need to decouple the rendering from the paint callback
  42584. and render with a custom thread.
  42585. Returns true if the operation succeeded.
  42586. */
  42587. virtual bool renderAndSwapBuffers();
  42588. /** This returns a critical section that can be used to lock the current context.
  42589. Because the context that is used by this component can change, e.g. when the
  42590. component is shown or hidden, then if you're rendering to it on a background
  42591. thread, this allows you to lock the context for the duration of your rendering
  42592. routine.
  42593. */
  42594. CriticalSection& getContextLock() throw() { return contextLock; }
  42595. /** @internal */
  42596. void paint (Graphics& g);
  42597. /** Returns the native handle of an embedded heavyweight window, if there is one.
  42598. E.g. On windows, this will return the HWND of the sub-window containing
  42599. the opengl context, on the mac it'll be the NSOpenGLView.
  42600. */
  42601. void* getNativeWindowHandle() const;
  42602. /** Call this to manually delete the current GL context, if there is one.
  42603. This can be useful to cause a clear-out of the context, which will be automatically
  42604. re-created when it's needed.
  42605. */
  42606. void deleteContext();
  42607. juce_UseDebuggingNewOperator
  42608. private:
  42609. const OpenGLType type;
  42610. class OpenGLComponentWatcher;
  42611. friend class OpenGLComponentWatcher;
  42612. friend class ScopedPointer <OpenGLComponentWatcher>;
  42613. ScopedPointer <OpenGLComponentWatcher> componentWatcher;
  42614. ScopedPointer <OpenGLContext> context;
  42615. OpenGLContext* contextToShareListsWith;
  42616. CriticalSection contextLock;
  42617. OpenGLPixelFormat preferredPixelFormat;
  42618. bool needToUpdateViewport;
  42619. OpenGLContext* createContext();
  42620. void updateContextPosition();
  42621. void internalRepaint (int x, int y, int w, int h);
  42622. OpenGLComponent (const OpenGLComponent&);
  42623. OpenGLComponent& operator= (const OpenGLComponent&);
  42624. };
  42625. #endif
  42626. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42627. /*** End of inlined file: juce_OpenGLComponent.h ***/
  42628. #endif
  42629. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  42630. /*** Start of inlined file: juce_PreferencesPanel.h ***/
  42631. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  42632. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  42633. /**
  42634. A component with a set of buttons at the top for changing between pages of
  42635. preferences.
  42636. This is just a handy way of writing a Mac-style preferences panel where you
  42637. have a row of buttons along the top for the different preference categories,
  42638. each button having an icon above its name. Clicking these will show an
  42639. appropriate prefs page below it.
  42640. You can either put one of these inside your own component, or just use the
  42641. showInDialogBox() method to show it in a window and run it modally.
  42642. To use it, just add a set of named pages with the addSettingsPage() method,
  42643. and implement the createComponentForPage() method to create suitable components
  42644. for each of these pages.
  42645. */
  42646. class JUCE_API PreferencesPanel : public Component,
  42647. private ButtonListener
  42648. {
  42649. public:
  42650. /** Creates an empty panel.
  42651. Use addSettingsPage() to add some pages to it in your constructor.
  42652. */
  42653. PreferencesPanel();
  42654. /** Destructor. */
  42655. ~PreferencesPanel();
  42656. /** Creates a page using a set of drawables to define the page's icon.
  42657. Note that the other version of this method is much easier if you're using
  42658. an image instead of a custom drawable.
  42659. @param pageTitle the name of this preferences page - you'll need to
  42660. make sure your createComponentForPage() method creates
  42661. a suitable component when it is passed this name
  42662. @param normalIcon the drawable to display in the page's button normally
  42663. @param overIcon the drawable to display in the page's button when the mouse is over
  42664. @param downIcon the drawable to display in the page's button when the button is down
  42665. @see DrawableButton
  42666. */
  42667. void addSettingsPage (const String& pageTitle,
  42668. const Drawable* normalIcon,
  42669. const Drawable* overIcon,
  42670. const Drawable* downIcon);
  42671. /** Creates a page using a set of drawables to define the page's icon.
  42672. The other version of this method gives you more control over the icon, but this
  42673. one is much easier if you're just loading it from a file.
  42674. @param pageTitle the name of this preferences page - you'll need to
  42675. make sure your createComponentForPage() method creates
  42676. a suitable component when it is passed this name
  42677. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  42678. For this to look good, you'll probably want to use a nice
  42679. transparent png file.
  42680. @param imageDataSize the size of the image data, in bytes
  42681. */
  42682. void addSettingsPage (const String& pageTitle,
  42683. const void* imageData,
  42684. int imageDataSize);
  42685. /** Utility method to display this panel in a DialogWindow.
  42686. Calling this will create a DialogWindow containing this panel with the
  42687. given size and title, and will run it modally, returning when the user
  42688. closes the dialog box.
  42689. */
  42690. void showInDialogBox (const String& dialogtitle,
  42691. int dialogWidth,
  42692. int dialogHeight,
  42693. const Colour& backgroundColour = Colours::white);
  42694. /** Subclasses must override this to return a component for each preferences page.
  42695. The subclass should return a pointer to a new component representing the named
  42696. page, which the panel will then display.
  42697. The panel will delete the component later when the user goes to another page
  42698. or deletes the panel.
  42699. */
  42700. virtual Component* createComponentForPage (const String& pageName) = 0;
  42701. /** Changes the current page being displayed. */
  42702. void setCurrentPage (const String& pageName);
  42703. /** @internal */
  42704. void resized();
  42705. /** @internal */
  42706. void paint (Graphics& g);
  42707. /** @internal */
  42708. void buttonClicked (Button* button);
  42709. juce_UseDebuggingNewOperator
  42710. private:
  42711. String currentPageName;
  42712. ScopedPointer <Component> currentPage;
  42713. int buttonSize;
  42714. PreferencesPanel (const PreferencesPanel&);
  42715. PreferencesPanel& operator= (const PreferencesPanel&);
  42716. };
  42717. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  42718. /*** End of inlined file: juce_PreferencesPanel.h ***/
  42719. #endif
  42720. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  42721. /*** Start of inlined file: juce_QuickTimeMovieComponent.h ***/
  42722. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  42723. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  42724. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  42725. // amalgamated build)
  42726. #if JUCE_WINDOWS
  42727. typedef ActiveXControlComponent QTCompBaseClass;
  42728. #elif JUCE_MAC
  42729. typedef NSViewComponent QTCompBaseClass;
  42730. #endif
  42731. // this is used to disable QuickTime, and is defined in juce_Config.h
  42732. #if JUCE_QUICKTIME || DOXYGEN
  42733. /**
  42734. A window that can play back a QuickTime movie.
  42735. */
  42736. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  42737. {
  42738. public:
  42739. /** Creates a QuickTimeMovieComponent, initially blank.
  42740. Use the loadMovie() method to load a movie once you've added the
  42741. component to a window, (or put it on the desktop as a heavyweight window).
  42742. Loading a movie when the component isn't visible can cause problems, as
  42743. QuickTime needs a window handle to initialise properly.
  42744. */
  42745. QuickTimeMovieComponent();
  42746. /** Destructor. */
  42747. ~QuickTimeMovieComponent();
  42748. /** Returns true if QT is installed and working on this machine.
  42749. */
  42750. static bool isQuickTimeAvailable() throw();
  42751. /** Tries to load a QuickTime movie from a file into the player.
  42752. It's best to call this function once you've added the component to a window,
  42753. (or put it on the desktop as a heavyweight window). Loading a movie when the
  42754. component isn't visible can cause problems, because QuickTime needs a window
  42755. handle to do its stuff.
  42756. @param movieFile the .mov file to open
  42757. @param isControllerVisible whether to show a controller bar at the bottom
  42758. @returns true if the movie opens successfully
  42759. */
  42760. bool loadMovie (const File& movieFile,
  42761. bool isControllerVisible);
  42762. /** Tries to load a QuickTime movie from a URL into the player.
  42763. It's best to call this function once you've added the component to a window,
  42764. (or put it on the desktop as a heavyweight window). Loading a movie when the
  42765. component isn't visible can cause problems, because QuickTime needs a window
  42766. handle to do its stuff.
  42767. @param movieURL the .mov file to open
  42768. @param isControllerVisible whether to show a controller bar at the bottom
  42769. @returns true if the movie opens successfully
  42770. */
  42771. bool loadMovie (const URL& movieURL,
  42772. bool isControllerVisible);
  42773. /** Tries to load a QuickTime movie from a stream into the player.
  42774. It's best to call this function once you've added the component to a window,
  42775. (or put it on the desktop as a heavyweight window). Loading a movie when the
  42776. component isn't visible can cause problems, because QuickTime needs a window
  42777. handle to do its stuff.
  42778. @param movieStream a stream containing a .mov file. The component may try
  42779. to read the whole stream before playing, rather than
  42780. streaming from it.
  42781. @param isControllerVisible whether to show a controller bar at the bottom
  42782. @returns true if the movie opens successfully
  42783. */
  42784. bool loadMovie (InputStream* movieStream,
  42785. bool isControllerVisible);
  42786. /** Closes the movie, if one is open. */
  42787. void closeMovie();
  42788. /** Returns the movie file that is currently open.
  42789. If there isn't one, this returns File::nonexistent
  42790. */
  42791. const File getCurrentMovieFile() const;
  42792. /** Returns true if there's currently a movie open. */
  42793. bool isMovieOpen() const;
  42794. /** Returns the length of the movie, in seconds. */
  42795. double getMovieDuration() const;
  42796. /** Returns the movie's natural size, in pixels.
  42797. You can use this to resize the component to show the movie at its preferred
  42798. scale.
  42799. If no movie is loaded, the size returned will be 0 x 0.
  42800. */
  42801. void getMovieNormalSize (int& width, int& height) const;
  42802. /** This will position the component within a given area, keeping its aspect
  42803. ratio correct according to the movie's normal size.
  42804. The component will be made as large as it can go within the space, and will
  42805. be aligned according to the justification value if this means there are gaps at
  42806. the top or sides.
  42807. */
  42808. void setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  42809. const RectanglePlacement& placement);
  42810. /** Starts the movie playing. */
  42811. void play();
  42812. /** Stops the movie playing. */
  42813. void stop();
  42814. /** Returns true if the movie is currently playing. */
  42815. bool isPlaying() const;
  42816. /** Moves the movie's position back to the start. */
  42817. void goToStart();
  42818. /** Sets the movie's position to a given time. */
  42819. void setPosition (double seconds);
  42820. /** Returns the current play position of the movie. */
  42821. double getPosition() const;
  42822. /** Changes the movie playback rate.
  42823. A value of 1 is normal speed, greater values play it proportionately faster,
  42824. smaller values play it slower.
  42825. */
  42826. void setSpeed (float newSpeed);
  42827. /** Changes the movie's playback volume.
  42828. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  42829. */
  42830. void setMovieVolume (float newVolume);
  42831. /** Returns the movie's playback volume.
  42832. @returns the volume in the range 0 (silent) to 1.0 (full)
  42833. */
  42834. float getMovieVolume() const;
  42835. /** Tells the movie whether it should loop. */
  42836. void setLooping (bool shouldLoop);
  42837. /** Returns true if the movie is currently looping.
  42838. @see setLooping
  42839. */
  42840. bool isLooping() const;
  42841. /** True if the native QuickTime controller bar is shown in the window.
  42842. @see loadMovie
  42843. */
  42844. bool isControllerVisible() const;
  42845. /** @internal */
  42846. void paint (Graphics& g);
  42847. juce_UseDebuggingNewOperator
  42848. private:
  42849. File movieFile;
  42850. bool movieLoaded, controllerVisible, looping;
  42851. #if JUCE_WINDOWS
  42852. void parentHierarchyChanged();
  42853. void visibilityChanged();
  42854. void createControlIfNeeded();
  42855. bool isControlCreated() const;
  42856. class Pimpl;
  42857. friend class ScopedPointer <Pimpl>;
  42858. ScopedPointer <Pimpl> pimpl;
  42859. #else
  42860. void* movie;
  42861. #endif
  42862. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  42863. QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  42864. };
  42865. #endif
  42866. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  42867. /*** End of inlined file: juce_QuickTimeMovieComponent.h ***/
  42868. #endif
  42869. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  42870. /*** Start of inlined file: juce_SystemTrayIconComponent.h ***/
  42871. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  42872. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  42873. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  42874. /**
  42875. On Windows only, this component sits in the taskbar tray as a small icon.
  42876. To use it, just create one of these components, but don't attempt to make it
  42877. visible, add it to a parent, or put it on the desktop.
  42878. You can then call setIconImage() to create an icon for it in the taskbar.
  42879. To change the icon's tooltip, you can use setIconTooltip().
  42880. To respond to mouse-events, you can override the normal mouseDown(),
  42881. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  42882. position will not be valid, you can use this to respond to clicks. Traditionally
  42883. you'd use a left-click to show your application's window, and a right-click
  42884. to show a pop-up menu.
  42885. */
  42886. class JUCE_API SystemTrayIconComponent : public Component
  42887. {
  42888. public:
  42889. SystemTrayIconComponent();
  42890. /** Destructor. */
  42891. ~SystemTrayIconComponent();
  42892. /** Changes the image shown in the taskbar.
  42893. */
  42894. void setIconImage (const Image& newImage);
  42895. /** Changes the tooltip that Windows shows above the icon. */
  42896. void setIconTooltip (const String& tooltip);
  42897. #if JUCE_LINUX
  42898. /** @internal */
  42899. void paint (Graphics& g);
  42900. #endif
  42901. juce_UseDebuggingNewOperator
  42902. private:
  42903. SystemTrayIconComponent (const SystemTrayIconComponent&);
  42904. SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  42905. };
  42906. #endif
  42907. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  42908. /*** End of inlined file: juce_SystemTrayIconComponent.h ***/
  42909. #endif
  42910. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  42911. /*** Start of inlined file: juce_WebBrowserComponent.h ***/
  42912. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  42913. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  42914. #if JUCE_WEB_BROWSER || DOXYGEN
  42915. #if ! DOXYGEN
  42916. class WebBrowserComponentInternal;
  42917. #endif
  42918. /**
  42919. A component that displays an embedded web browser.
  42920. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  42921. Windows, probably IE.
  42922. */
  42923. class JUCE_API WebBrowserComponent : public Component
  42924. {
  42925. public:
  42926. /** Creates a WebBrowserComponent.
  42927. Once it's created and visible, send the browser to a URL using goToURL().
  42928. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  42929. component is taken offscreen, it'll clear the current page
  42930. and replace it with a blank page - this can be handy to stop
  42931. the browser using resources in the background when it's not
  42932. actually being used.
  42933. */
  42934. explicit WebBrowserComponent (bool unloadPageWhenBrowserIsHidden = true);
  42935. /** Destructor. */
  42936. ~WebBrowserComponent();
  42937. /** Sends the browser to a particular URL.
  42938. @param url the URL to go to.
  42939. @param headers an optional set of parameters to put in the HTTP header. If
  42940. you supply this, it should be a set of string in the form
  42941. "HeaderKey: HeaderValue"
  42942. @param postData an optional block of data that will be attached to the HTTP
  42943. POST request
  42944. */
  42945. void goToURL (const String& url,
  42946. const StringArray* headers = 0,
  42947. const MemoryBlock* postData = 0);
  42948. /** Stops the current page loading.
  42949. */
  42950. void stop();
  42951. /** Sends the browser back one page.
  42952. */
  42953. void goBack();
  42954. /** Sends the browser forward one page.
  42955. */
  42956. void goForward();
  42957. /** Refreshes the browser.
  42958. */
  42959. void refresh();
  42960. /** This callback is called when the browser is about to navigate
  42961. to a new location.
  42962. You can override this method to perform some action when the user
  42963. tries to go to a particular URL. To allow the operation to carry on,
  42964. return true, or return false to stop the navigation happening.
  42965. */
  42966. virtual bool pageAboutToLoad (const String& newURL);
  42967. /** @internal */
  42968. void paint (Graphics& g);
  42969. /** @internal */
  42970. void resized();
  42971. /** @internal */
  42972. void parentHierarchyChanged();
  42973. /** @internal */
  42974. void visibilityChanged();
  42975. juce_UseDebuggingNewOperator
  42976. private:
  42977. WebBrowserComponentInternal* browser;
  42978. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  42979. String lastURL;
  42980. StringArray lastHeaders;
  42981. MemoryBlock lastPostData;
  42982. void reloadLastURL();
  42983. void checkWindowAssociation();
  42984. WebBrowserComponent (const WebBrowserComponent&);
  42985. WebBrowserComponent& operator= (const WebBrowserComponent&);
  42986. };
  42987. #endif
  42988. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  42989. /*** End of inlined file: juce_WebBrowserComponent.h ***/
  42990. #endif
  42991. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  42992. #endif
  42993. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  42994. /*** Start of inlined file: juce_CallOutBox.h ***/
  42995. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  42996. #define __JUCE_CALLOUTBOX_JUCEHEADER__
  42997. /**
  42998. A box with a small arrow that can be used as a temporary pop-up window to show
  42999. extra controls when a button or other component is clicked.
  43000. Using one of these is similar to having a popup menu attached to a button or
  43001. other component - but it looks fancier, and has an arrow that can indicate the
  43002. object that it applies to.
  43003. Normally, you'd create one of these on the stack and run it modally, e.g.
  43004. @code
  43005. void mouseUp (const MouseEvent& e)
  43006. {
  43007. MyContentComponent content;
  43008. content.setSize (300, 300);
  43009. CallOutBox callOut (content, *this, 0);
  43010. callOut.runModalLoop();
  43011. }
  43012. @endcode
  43013. The call-out will resize and position itself when the content changes size.
  43014. */
  43015. class JUCE_API CallOutBox : public Component
  43016. {
  43017. public:
  43018. /** Creates a CallOutBox.
  43019. @param contentComponent the component to display inside the call-out. This should
  43020. already have a size set (although the call-out will also
  43021. update itself when the component's size is changed later).
  43022. Obviously this component must not be deleted until the
  43023. call-out box has been deleted.
  43024. @param componentToPointTo the component that the call-out's arrow should point towards
  43025. @param parentComponent if non-zero, this is the component to add the call-out to. If
  43026. this is zero, the call-out will be added to the desktop.
  43027. */
  43028. CallOutBox (Component& contentComponent,
  43029. Component& componentToPointTo,
  43030. Component* parentComponent);
  43031. /** Destructor. */
  43032. ~CallOutBox();
  43033. /** Changes the length of the arrow. */
  43034. void setArrowSize (float newSize);
  43035. /** Updates the position and size of the box.
  43036. You shouldn't normally need to call this, unless you need more precise control over the
  43037. layout.
  43038. @param newAreaToPointTo the rectangle to make the box's arrow point to
  43039. @param newAreaToFitIn the area within which the box's position should be constrained
  43040. */
  43041. void updatePosition (const Rectangle<int>& newAreaToPointTo,
  43042. const Rectangle<int>& newAreaToFitIn);
  43043. /** @internal */
  43044. void paint (Graphics& g);
  43045. /** @internal */
  43046. void resized();
  43047. /** @internal */
  43048. void moved();
  43049. /** @internal */
  43050. void childBoundsChanged (Component*);
  43051. /** @internal */
  43052. bool hitTest (int x, int y);
  43053. /** @internal */
  43054. void inputAttemptWhenModal();
  43055. /** @internal */
  43056. bool keyPressed (const KeyPress& key);
  43057. juce_UseDebuggingNewOperator
  43058. private:
  43059. int borderSpace;
  43060. float arrowSize;
  43061. Component& content;
  43062. Path outline;
  43063. Point<float> targetPoint;
  43064. Rectangle<int> availableArea, targetArea;
  43065. Image background;
  43066. void refreshPath();
  43067. void drawCallOutBoxBackground (Graphics& g, const Path& outline, int width, int height);
  43068. CallOutBox (const CallOutBox&);
  43069. CallOutBox& operator= (const CallOutBox&);
  43070. };
  43071. #endif // __JUCE_CALLOUTBOX_JUCEHEADER__
  43072. /*** End of inlined file: juce_CallOutBox.h ***/
  43073. #endif
  43074. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  43075. /*** Start of inlined file: juce_ComponentPeer.h ***/
  43076. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  43077. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  43078. class ComponentBoundsConstrainer;
  43079. /**
  43080. The base class for window objects that wrap a component as a real operating
  43081. system object.
  43082. This is an abstract base class - the platform specific code contains default
  43083. implementations of it that create and manage windows.
  43084. @see Component::createNewPeer
  43085. */
  43086. class JUCE_API ComponentPeer
  43087. {
  43088. public:
  43089. /** A combination of these flags is passed to the ComponentPeer constructor. */
  43090. enum StyleFlags
  43091. {
  43092. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  43093. entry on the taskbar (ignored on MacOSX) */
  43094. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  43095. tooltip, etc. */
  43096. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  43097. through it (may not be possible on some platforms). */
  43098. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  43099. title bar and frame\. if not specified, the window will be
  43100. borderless. */
  43101. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  43102. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  43103. minimise button on it. */
  43104. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  43105. maximise button on it. */
  43106. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  43107. close button on it. */
  43108. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  43109. not be possible on all platforms). */
  43110. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  43111. do its own repainting, but only to repaint when the
  43112. performAnyPendingRepaintsNow() method is called. */
  43113. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  43114. be used for things like plugin windows, to stop them interfering
  43115. with the host's shortcut keys */
  43116. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  43117. };
  43118. /** Creates a peer.
  43119. The component is the one that we intend to represent, and the style flags are
  43120. a combination of the values in the StyleFlags enum
  43121. */
  43122. ComponentPeer (Component* component, int styleFlags);
  43123. /** Destructor. */
  43124. virtual ~ComponentPeer();
  43125. /** Returns the component being represented by this peer. */
  43126. Component* getComponent() const throw() { return component; }
  43127. /** Returns the set of style flags that were set when the window was created.
  43128. @see Component::addToDesktop
  43129. */
  43130. int getStyleFlags() const throw() { return styleFlags; }
  43131. /** Returns the raw handle to whatever kind of window is being used.
  43132. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  43133. but rememeber there's no guarantees what you'll get back.
  43134. */
  43135. virtual void* getNativeHandle() const = 0;
  43136. /** Shows or hides the window. */
  43137. virtual void setVisible (bool shouldBeVisible) = 0;
  43138. /** Changes the title of the window. */
  43139. virtual void setTitle (const String& title) = 0;
  43140. /** Moves the window without changing its size.
  43141. If the native window is contained in another window, then the co-ordinates are
  43142. relative to the parent window's origin, not the screen origin.
  43143. This should result in a callback to handleMovedOrResized().
  43144. */
  43145. virtual void setPosition (int x, int y) = 0;
  43146. /** Resizes the window without changing its position.
  43147. This should result in a callback to handleMovedOrResized().
  43148. */
  43149. virtual void setSize (int w, int h) = 0;
  43150. /** Moves and resizes the window.
  43151. If the native window is contained in another window, then the co-ordinates are
  43152. relative to the parent window's origin, not the screen origin.
  43153. This should result in a callback to handleMovedOrResized().
  43154. */
  43155. virtual void setBounds (int x, int y, int w, int h, bool isNowFullScreen) = 0;
  43156. /** Returns the current position and size of the window.
  43157. If the native window is contained in another window, then the co-ordinates are
  43158. relative to the parent window's origin, not the screen origin.
  43159. */
  43160. virtual const Rectangle<int> getBounds() const = 0;
  43161. /** Returns the x-position of this window, relative to the screen's origin. */
  43162. virtual const Point<int> getScreenPosition() const = 0;
  43163. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  43164. virtual const Point<int> relativePositionToGlobal (const Point<int>& relativePosition) = 0;
  43165. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  43166. virtual const Point<int> globalPositionToRelative (const Point<int>& screenPosition) = 0;
  43167. /** Minimises the window. */
  43168. virtual void setMinimised (bool shouldBeMinimised) = 0;
  43169. /** True if the window is currently minimised. */
  43170. virtual bool isMinimised() const = 0;
  43171. /** Enable/disable fullscreen mode for the window. */
  43172. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  43173. /** True if the window is currently full-screen. */
  43174. virtual bool isFullScreen() const = 0;
  43175. /** Sets the size to restore to if fullscreen mode is turned off. */
  43176. void setNonFullScreenBounds (const Rectangle<int>& newBounds) throw();
  43177. /** Returns the size to restore to if fullscreen mode is turned off. */
  43178. const Rectangle<int>& getNonFullScreenBounds() const throw();
  43179. /** Attempts to change the icon associated with this window.
  43180. */
  43181. virtual void setIcon (const Image& newIcon) = 0;
  43182. /** Sets a constrainer to use if the peer can resize itself.
  43183. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  43184. */
  43185. void setConstrainer (ComponentBoundsConstrainer* newConstrainer) throw();
  43186. /** Returns the current constrainer, if one has been set. */
  43187. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  43188. /** Checks if a point is in the window.
  43189. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  43190. is false, then this returns false if the point is actually inside a child of this
  43191. window.
  43192. */
  43193. virtual bool contains (const Point<int>& position, bool trueIfInAChildWindow) const = 0;
  43194. /** Returns the size of the window frame that's around this window.
  43195. Whether or not the window has a normal window frame depends on the flags
  43196. that were set when the window was created by Component::addToDesktop()
  43197. */
  43198. virtual const BorderSize getFrameSize() const = 0;
  43199. /** This is called when the window's bounds change.
  43200. A peer implementation must call this when the window is moved and resized, so that
  43201. this method can pass the message on to the component.
  43202. */
  43203. void handleMovedOrResized();
  43204. /** This is called if the screen resolution changes.
  43205. A peer implementation must call this if the monitor arrangement changes or the available
  43206. screen size changes.
  43207. */
  43208. void handleScreenSizeChange();
  43209. /** This is called to repaint the component into the given context. */
  43210. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  43211. /** Sets this window to either be always-on-top or normal.
  43212. Some kinds of window might not be able to do this, so should return false.
  43213. */
  43214. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  43215. /** Brings the window to the top, optionally also giving it focus. */
  43216. virtual void toFront (bool makeActive) = 0;
  43217. /** Moves the window to be just behind another one. */
  43218. virtual void toBehind (ComponentPeer* other) = 0;
  43219. /** Called when the window is brought to the front, either by the OS or by a call
  43220. to toFront().
  43221. */
  43222. void handleBroughtToFront();
  43223. /** True if the window has the keyboard focus. */
  43224. virtual bool isFocused() const = 0;
  43225. /** Tries to give the window keyboard focus. */
  43226. virtual void grabFocus() = 0;
  43227. /** Tells the window that text input may be required at the given position.
  43228. This may cause things like a virtual on-screen keyboard to appear, depending
  43229. on the OS.
  43230. */
  43231. virtual void textInputRequired (const Point<int>& position) = 0;
  43232. /** Called when the window gains keyboard focus. */
  43233. void handleFocusGain();
  43234. /** Called when the window loses keyboard focus. */
  43235. void handleFocusLoss();
  43236. Component* getLastFocusedSubcomponent() const throw();
  43237. /** Called when a key is pressed.
  43238. For keycode info, see the KeyPress class.
  43239. Returns true if the keystroke was used.
  43240. */
  43241. bool handleKeyPress (int keyCode,
  43242. juce_wchar textCharacter);
  43243. /** Called whenever a key is pressed or released.
  43244. Returns true if the keystroke was used.
  43245. */
  43246. bool handleKeyUpOrDown (bool isKeyDown);
  43247. /** Called whenever a modifier key is pressed or released. */
  43248. void handleModifierKeysChange();
  43249. /** Returns the currently focused TextInputTarget, or null if none is found. */
  43250. TextInputTarget* findCurrentTextInputTarget();
  43251. /** Invalidates a region of the window to be repainted asynchronously. */
  43252. virtual void repaint (const Rectangle<int>& area) = 0;
  43253. /** This can be called (from the message thread) to cause the immediate redrawing
  43254. of any areas of this window that need repainting.
  43255. You shouldn't ever really need to use this, it's mainly for special purposes
  43256. like supporting audio plugins where the host's event loop is out of our control.
  43257. */
  43258. virtual void performAnyPendingRepaintsNow() = 0;
  43259. void handleMouseEvent (int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, int64 time);
  43260. void handleMouseWheel (int touchIndex, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  43261. void handleUserClosingWindow();
  43262. void handleFileDragMove (const StringArray& files, const Point<int>& position);
  43263. void handleFileDragExit (const StringArray& files);
  43264. void handleFileDragDrop (const StringArray& files, const Point<int>& position);
  43265. /** Resets the masking region.
  43266. The subclass should call this every time it's about to call the handlePaint
  43267. method.
  43268. @see addMaskedRegion
  43269. */
  43270. void clearMaskedRegion();
  43271. /** Adds a rectangle to the set of areas not to paint over.
  43272. A component can call this on its peer during its paint() method, to signal
  43273. that the painting code should ignore a given region. The reason
  43274. for this is to stop embedded windows (such as OpenGL) getting painted over.
  43275. The masked region is cleared each time before a paint happens, so a component
  43276. will have to make sure it calls this every time it's painted.
  43277. */
  43278. void addMaskedRegion (int x, int y, int w, int h);
  43279. /** Returns the number of currently-active peers.
  43280. @see getPeer
  43281. */
  43282. static int getNumPeers() throw();
  43283. /** Returns one of the currently-active peers.
  43284. @see getNumPeers
  43285. */
  43286. static ComponentPeer* getPeer (int index) throw();
  43287. /** Checks if this peer object is valid.
  43288. @see getNumPeers
  43289. */
  43290. static bool isValidPeer (const ComponentPeer* peer) throw();
  43291. static void bringModalComponentToFront();
  43292. virtual const StringArray getAvailableRenderingEngines() throw();
  43293. virtual int getCurrentRenderingEngine() throw();
  43294. virtual void setCurrentRenderingEngine (int index) throw();
  43295. juce_UseDebuggingNewOperator
  43296. protected:
  43297. Component* const component;
  43298. const int styleFlags;
  43299. RectangleList maskedRegion;
  43300. Rectangle<int> lastNonFullscreenBounds;
  43301. uint32 lastPaintTime;
  43302. ComponentBoundsConstrainer* constrainer;
  43303. static void updateCurrentModifiers() throw();
  43304. private:
  43305. Component::SafePointer<Component> lastFocusedComponent, dragAndDropTargetComponent;
  43306. Component* lastDragAndDropCompUnderMouse;
  43307. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  43308. friend class Component;
  43309. static ComponentPeer* getPeerFor (const Component* component) throw();
  43310. void setLastDragDropTarget (Component* comp);
  43311. ComponentPeer (const ComponentPeer&);
  43312. ComponentPeer& operator= (const ComponentPeer&);
  43313. };
  43314. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  43315. /*** End of inlined file: juce_ComponentPeer.h ***/
  43316. #endif
  43317. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  43318. /*** Start of inlined file: juce_DialogWindow.h ***/
  43319. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  43320. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  43321. /**
  43322. A dialog-box style window.
  43323. This class is a convenient way of creating a DocumentWindow with a close button
  43324. that can be triggered by pressing the escape key.
  43325. Any of the methods available to a DocumentWindow or ResizableWindow are also
  43326. available to this, so it can be made resizable, have a menu bar, etc.
  43327. To add items to the box, see the ResizableWindow::setContentComponent() method.
  43328. Don't add components directly to this class - always put them in a content component!
  43329. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  43330. the user clicking the close button - for more info, see the DocumentWindow
  43331. help.
  43332. @see DocumentWindow, ResizableWindow
  43333. */
  43334. class JUCE_API DialogWindow : public DocumentWindow
  43335. {
  43336. public:
  43337. /** Creates a DialogWindow.
  43338. @param name the name to give the component - this is also
  43339. the title shown at the top of the window. To change
  43340. this later, use setName()
  43341. @param backgroundColour the colour to use for filling the window's background.
  43342. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  43343. close button to be triggered
  43344. @param addToDesktop if true, the window will be automatically added to the
  43345. desktop; if false, you can use it as a child component
  43346. */
  43347. DialogWindow (const String& name,
  43348. const Colour& backgroundColour,
  43349. bool escapeKeyTriggersCloseButton,
  43350. bool addToDesktop = true);
  43351. /** Destructor.
  43352. If a content component has been set with setContentComponent(), it
  43353. will be deleted.
  43354. */
  43355. ~DialogWindow();
  43356. /** Easy way of quickly showing a dialog box containing a given component.
  43357. This will open and display a DialogWindow containing a given component, returning
  43358. when the user clicks its close button.
  43359. It returns the value that was returned by the dialog box's runModalLoop() call.
  43360. To close the dialog programatically, you should call exitModalState (returnValue) on
  43361. the DialogWindow that is created. To find a pointer to this window from your
  43362. contentComponent, you can do something like this:
  43363. @code
  43364. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  43365. if (dw != 0)
  43366. dw->exitModalState (1234);
  43367. @endcode
  43368. @param dialogTitle the dialog box's title
  43369. @param contentComponent the content component for the dialog box. Make sure
  43370. that this has been set to the size you want it to
  43371. be before calling this method. The component won't
  43372. be deleted by this call, so you can re-use it or delete
  43373. it afterwards
  43374. @param componentToCentreAround if this is non-zero, it indicates a component that
  43375. you'd like to show this dialog box in front of. See the
  43376. DocumentWindow::centreAroundComponent() method for more
  43377. info on this parameter
  43378. @param backgroundColour a colour to use for the dialog box's background colour
  43379. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  43380. close button to be triggered
  43381. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  43382. a corner resizer
  43383. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  43384. to use a border or corner resizer component. See ResizableWindow::setResizable()
  43385. */
  43386. static int showModalDialog (const String& dialogTitle,
  43387. Component* contentComponent,
  43388. Component* componentToCentreAround,
  43389. const Colour& backgroundColour,
  43390. bool escapeKeyTriggersCloseButton,
  43391. bool shouldBeResizable = false,
  43392. bool useBottomRightCornerResizer = false);
  43393. juce_UseDebuggingNewOperator
  43394. protected:
  43395. /** @internal */
  43396. void resized();
  43397. private:
  43398. bool escapeKeyTriggersCloseButton;
  43399. DialogWindow (const DialogWindow&);
  43400. DialogWindow& operator= (const DialogWindow&);
  43401. };
  43402. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  43403. /*** End of inlined file: juce_DialogWindow.h ***/
  43404. #endif
  43405. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  43406. #endif
  43407. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  43408. #endif
  43409. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  43410. /*** Start of inlined file: juce_SplashScreen.h ***/
  43411. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  43412. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  43413. /** A component for showing a splash screen while your app starts up.
  43414. This will automatically position itself, and delete itself when the app has
  43415. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  43416. this).
  43417. To use it, just create one of these in your JUCEApplication::initialise() method,
  43418. call its show() method and let the object delete itself later.
  43419. E.g. @code
  43420. void MyApp::initialise (const String& commandLine)
  43421. {
  43422. SplashScreen* splash = new SplashScreen();
  43423. splash->show ("welcome to my app",
  43424. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  43425. 4000, false);
  43426. .. no need to delete the splash screen - it'll do that itself.
  43427. }
  43428. @endcode
  43429. */
  43430. class JUCE_API SplashScreen : public Component,
  43431. public Timer,
  43432. private DeletedAtShutdown
  43433. {
  43434. public:
  43435. /** Creates a SplashScreen object.
  43436. After creating one of these (or your subclass of it), call one of the show()
  43437. methods to display it.
  43438. */
  43439. SplashScreen();
  43440. /** Destructor. */
  43441. ~SplashScreen();
  43442. /** Creates a SplashScreen object that will display an image.
  43443. As soon as this is called, the SplashScreen will be displayed in the centre of the
  43444. screen. This method will also dispatch any pending messages to make sure that when
  43445. it returns, the splash screen has been completely drawn, and your initialisation
  43446. code can carry on.
  43447. @param title the name to give the component
  43448. @param backgroundImage an image to draw on the component. The component's size
  43449. will be set to the size of this image, and if the image is
  43450. semi-transparent, the component will be made semi-transparent
  43451. too. This image will be deleted (or released from the ImageCache
  43452. if that's how it was created) by the splash screen object when
  43453. it is itself deleted.
  43454. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  43455. should stay visible for. If the initialisation takes longer than
  43456. this time, the splash screen will wait for it to finish before
  43457. disappearing, but if initialisation is very quick, this lets
  43458. you make sure that people get a good look at your splash.
  43459. @param useDropShadow if true, the window will have a drop shadow
  43460. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  43461. the mouse (anywhere)
  43462. */
  43463. void show (const String& title,
  43464. const Image& backgroundImage,
  43465. int minimumTimeToDisplayFor,
  43466. bool useDropShadow,
  43467. bool removeOnMouseClick = true);
  43468. /** Creates a SplashScreen object with a specified size.
  43469. For a custom splash screen, you can use this method to display it at a certain size
  43470. and then override the paint() method yourself to do whatever's necessary.
  43471. As soon as this is called, the SplashScreen will be displayed in the centre of the
  43472. screen. This method will also dispatch any pending messages to make sure that when
  43473. it returns, the splash screen has been completely drawn, and your initialisation
  43474. code can carry on.
  43475. @param title the name to give the component
  43476. @param width the width to use
  43477. @param height the height to use
  43478. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  43479. should stay visible for. If the initialisation takes longer than
  43480. this time, the splash screen will wait for it to finish before
  43481. disappearing, but if initialisation is very quick, this lets
  43482. you make sure that people get a good look at your splash.
  43483. @param useDropShadow if true, the window will have a drop shadow
  43484. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  43485. the mouse (anywhere)
  43486. */
  43487. void show (const String& title,
  43488. int width,
  43489. int height,
  43490. int minimumTimeToDisplayFor,
  43491. bool useDropShadow,
  43492. bool removeOnMouseClick = true);
  43493. /** @internal */
  43494. void paint (Graphics& g);
  43495. /** @internal */
  43496. void timerCallback();
  43497. juce_UseDebuggingNewOperator
  43498. private:
  43499. Image backgroundImage;
  43500. Time earliestTimeToDelete;
  43501. int originalClickCounter;
  43502. SplashScreen (const SplashScreen&);
  43503. SplashScreen& operator= (const SplashScreen&);
  43504. };
  43505. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  43506. /*** End of inlined file: juce_SplashScreen.h ***/
  43507. #endif
  43508. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43509. /*** Start of inlined file: juce_ThreadWithProgressWindow.h ***/
  43510. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43511. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43512. /**
  43513. A thread that automatically pops up a modal dialog box with a progress bar
  43514. and cancel button while it's busy running.
  43515. These are handy for performing some sort of task while giving the user feedback
  43516. about how long there is to go, etc.
  43517. E.g. @code
  43518. class MyTask : public ThreadWithProgressWindow
  43519. {
  43520. public:
  43521. MyTask() : ThreadWithProgressWindow ("busy...", true, true)
  43522. {
  43523. }
  43524. ~MyTask()
  43525. {
  43526. }
  43527. void run()
  43528. {
  43529. for (int i = 0; i < thingsToDo; ++i)
  43530. {
  43531. // must check this as often as possible, because this is
  43532. // how we know if the user's pressed 'cancel'
  43533. if (threadShouldExit())
  43534. break;
  43535. // this will update the progress bar on the dialog box
  43536. setProgress (i / (double) thingsToDo);
  43537. // ... do the business here...
  43538. }
  43539. }
  43540. };
  43541. void doTheTask()
  43542. {
  43543. MyTask m;
  43544. if (m.runThread())
  43545. {
  43546. // thread finished normally..
  43547. }
  43548. else
  43549. {
  43550. // user pressed the cancel button..
  43551. }
  43552. }
  43553. @endcode
  43554. @see Thread, AlertWindow
  43555. */
  43556. class JUCE_API ThreadWithProgressWindow : public Thread,
  43557. private Timer
  43558. {
  43559. public:
  43560. /** Creates the thread.
  43561. Initially, the dialog box won't be visible, it'll only appear when the
  43562. runThread() method is called.
  43563. @param windowTitle the title to go at the top of the dialog box
  43564. @param hasProgressBar whether the dialog box should have a progress bar (see
  43565. setProgress() )
  43566. @param hasCancelButton whether the dialog box should have a cancel button
  43567. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  43568. the thread to stop before killing it forcibly (see
  43569. Thread::stopThread() )
  43570. @param cancelButtonText the text that should be shown in the cancel button
  43571. (if it has one)
  43572. */
  43573. ThreadWithProgressWindow (const String& windowTitle,
  43574. bool hasProgressBar,
  43575. bool hasCancelButton,
  43576. int timeOutMsWhenCancelling = 10000,
  43577. const String& cancelButtonText = "Cancel");
  43578. /** Destructor. */
  43579. ~ThreadWithProgressWindow();
  43580. /** Starts the thread and waits for it to finish.
  43581. This will start the thread, make the dialog box appear, and wait until either
  43582. the thread finishes normally, or until the cancel button is pressed.
  43583. Before returning, the dialog box will be hidden.
  43584. @param threadPriority the priority to use when starting the thread - see
  43585. Thread::startThread() for values
  43586. @returns true if the thread finished normally; false if the user pressed cancel
  43587. */
  43588. bool runThread (int threadPriority = 5);
  43589. /** The thread should call this periodically to update the position of the progress bar.
  43590. @param newProgress the progress, from 0.0 to 1.0
  43591. @see setStatusMessage
  43592. */
  43593. void setProgress (double newProgress);
  43594. /** The thread can call this to change the message that's displayed in the dialog box.
  43595. */
  43596. void setStatusMessage (const String& newStatusMessage);
  43597. /** Returns the AlertWindow that is being used.
  43598. */
  43599. AlertWindow* getAlertWindow() const throw() { return alertWindow; }
  43600. juce_UseDebuggingNewOperator
  43601. private:
  43602. void timerCallback();
  43603. double progress;
  43604. ScopedPointer <AlertWindow> alertWindow;
  43605. String message;
  43606. CriticalSection messageLock;
  43607. const int timeOutMsWhenCancelling;
  43608. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  43609. ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  43610. };
  43611. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43612. /*** End of inlined file: juce_ThreadWithProgressWindow.h ***/
  43613. #endif
  43614. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  43615. #endif
  43616. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  43617. #endif
  43618. #ifndef __JUCE_COLOUR_JUCEHEADER__
  43619. #endif
  43620. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  43621. #endif
  43622. #ifndef __JUCE_COLOURS_JUCEHEADER__
  43623. #endif
  43624. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  43625. #endif
  43626. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  43627. /*** Start of inlined file: juce_EdgeTable.h ***/
  43628. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  43629. #define __JUCE_EDGETABLE_JUCEHEADER__
  43630. class Path;
  43631. class Image;
  43632. /**
  43633. A table of horizontal scan-line segments - used for rasterising Paths.
  43634. @see Path, Graphics
  43635. */
  43636. class JUCE_API EdgeTable
  43637. {
  43638. public:
  43639. /** Creates an edge table containing a path.
  43640. A table is created with a fixed vertical range, and only sections of the path
  43641. which lie within this range will be added to the table.
  43642. @param clipLimits only the region of the path that lies within this area will be added
  43643. @param pathToAdd the path to add to the table
  43644. @param transform a transform to apply to the path being added
  43645. */
  43646. EdgeTable (const Rectangle<int>& clipLimits,
  43647. const Path& pathToAdd,
  43648. const AffineTransform& transform);
  43649. /** Creates an edge table containing a rectangle.
  43650. */
  43651. EdgeTable (const Rectangle<int>& rectangleToAdd);
  43652. /** Creates an edge table containing a rectangle list.
  43653. */
  43654. EdgeTable (const RectangleList& rectanglesToAdd);
  43655. /** Creates an edge table containing a rectangle.
  43656. */
  43657. EdgeTable (const Rectangle<float>& rectangleToAdd);
  43658. /** Creates a copy of another edge table. */
  43659. EdgeTable (const EdgeTable& other);
  43660. /** Copies from another edge table. */
  43661. EdgeTable& operator= (const EdgeTable& other);
  43662. /** Destructor. */
  43663. ~EdgeTable();
  43664. void clipToRectangle (const Rectangle<int>& r) throw();
  43665. void excludeRectangle (const Rectangle<int>& r) throw();
  43666. void clipToEdgeTable (const EdgeTable& other);
  43667. void clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw();
  43668. bool isEmpty() throw();
  43669. const Rectangle<int>& getMaximumBounds() const throw() { return bounds; }
  43670. void translate (float dx, int dy) throw();
  43671. /** Reduces the amount of space the table has allocated.
  43672. This will shrink the table down to use as little memory as possible - useful for
  43673. read-only tables that get stored and re-used for rendering.
  43674. */
  43675. void optimiseTable() throw();
  43676. /** Iterates the lines in the table, for rendering.
  43677. This function will iterate each line in the table, and call a user-defined class
  43678. to render each pixel or continuous line of pixels that the table contains.
  43679. @param iterationCallback this templated class must contain the following methods:
  43680. @code
  43681. inline void setEdgeTableYPos (int y);
  43682. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  43683. inline void handleEdgeTablePixelFull (int x) const;
  43684. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  43685. inline void handleEdgeTableLineFull (int x, int width) const;
  43686. @endcode
  43687. (these don't necessarily have to be 'const', but it might help it go faster)
  43688. */
  43689. template <class EdgeTableIterationCallback>
  43690. void iterate (EdgeTableIterationCallback& iterationCallback) const throw()
  43691. {
  43692. const int* lineStart = table;
  43693. for (int y = 0; y < bounds.getHeight(); ++y)
  43694. {
  43695. const int* line = lineStart;
  43696. lineStart += lineStrideElements;
  43697. int numPoints = line[0];
  43698. if (--numPoints > 0)
  43699. {
  43700. int x = *++line;
  43701. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  43702. int levelAccumulator = 0;
  43703. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  43704. while (--numPoints >= 0)
  43705. {
  43706. const int level = *++line;
  43707. jassert (((unsigned int) level) < (unsigned int) 256);
  43708. const int endX = *++line;
  43709. jassert (endX >= x);
  43710. const int endOfRun = (endX >> 8);
  43711. if (endOfRun == (x >> 8))
  43712. {
  43713. // small segment within the same pixel, so just save it for the next
  43714. // time round..
  43715. levelAccumulator += (endX - x) * level;
  43716. }
  43717. else
  43718. {
  43719. // plot the fist pixel of this segment, including any accumulated
  43720. // levels from smaller segments that haven't been drawn yet
  43721. levelAccumulator += (0xff - (x & 0xff)) * level;
  43722. levelAccumulator >>= 8;
  43723. x >>= 8;
  43724. if (levelAccumulator > 0)
  43725. {
  43726. if (levelAccumulator >> 8)
  43727. iterationCallback.handleEdgeTablePixelFull (x);
  43728. else
  43729. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  43730. }
  43731. // if there's a run of similar pixels, do it all in one go..
  43732. if (level > 0)
  43733. {
  43734. jassert (endOfRun <= bounds.getRight());
  43735. const int numPix = endOfRun - ++x;
  43736. if (numPix > 0)
  43737. iterationCallback.handleEdgeTableLine (x, numPix, level);
  43738. }
  43739. // save the bit at the end to be drawn next time round the loop.
  43740. levelAccumulator = (endX & 0xff) * level;
  43741. }
  43742. x = endX;
  43743. }
  43744. levelAccumulator >>= 8;
  43745. if (levelAccumulator > 0)
  43746. {
  43747. x >>= 8;
  43748. jassert (x >= bounds.getX() && x < bounds.getRight());
  43749. if (levelAccumulator >> 8)
  43750. iterationCallback.handleEdgeTablePixelFull (x);
  43751. else
  43752. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  43753. }
  43754. }
  43755. }
  43756. }
  43757. juce_UseDebuggingNewOperator
  43758. private:
  43759. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  43760. HeapBlock<int> table;
  43761. Rectangle<int> bounds;
  43762. int maxEdgesPerLine, lineStrideElements;
  43763. bool needToCheckEmptinesss;
  43764. void addEdgePoint (int x, int y, int winding) throw();
  43765. void remapTableForNumEdges (int newNumEdgesPerLine) throw();
  43766. void intersectWithEdgeTableLine (int y, const int* otherLine) throw();
  43767. void clipEdgeTableLineToRange (int* line, int x1, int x2) throw();
  43768. void sanitiseLevels (bool useNonZeroWinding) throw();
  43769. static void copyEdgeTableData (int* dest, int destLineStride, const int* src, int srcLineStride, int numLines) throw();
  43770. };
  43771. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  43772. /*** End of inlined file: juce_EdgeTable.h ***/
  43773. #endif
  43774. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  43775. /*** Start of inlined file: juce_FillType.h ***/
  43776. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  43777. #define __JUCE_FILLTYPE_JUCEHEADER__
  43778. /**
  43779. Represents a colour or fill pattern to use for rendering paths.
  43780. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  43781. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  43782. @see Graphics::setFillType, DrawablePath::setFill
  43783. */
  43784. class JUCE_API FillType
  43785. {
  43786. public:
  43787. /** Creates a default fill type, of solid black. */
  43788. FillType() throw();
  43789. /** Creates a fill type of a solid colour.
  43790. @see setColour
  43791. */
  43792. FillType (const Colour& colour) throw();
  43793. /** Creates a gradient fill type.
  43794. @see setGradient
  43795. */
  43796. FillType (const ColourGradient& gradient);
  43797. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  43798. and rotation of the pattern.
  43799. @see setTiledImage
  43800. */
  43801. FillType (const Image& image, const AffineTransform& transform) throw();
  43802. /** Creates a copy of another FillType. */
  43803. FillType (const FillType& other);
  43804. /** Makes a copy of another FillType. */
  43805. FillType& operator= (const FillType& other);
  43806. /** Destructor. */
  43807. ~FillType() throw();
  43808. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  43809. bool isColour() const throw() { return gradient == 0 && image.isNull(); }
  43810. /** Returns true if this is a gradient fill. */
  43811. bool isGradient() const throw() { return gradient != 0; }
  43812. /** Returns true if this is a tiled image pattern fill. */
  43813. bool isTiledImage() const throw() { return image.isValid(); }
  43814. /** Turns this object into a solid colour fill.
  43815. If the object was an image or gradient, those fields will no longer be valid. */
  43816. void setColour (const Colour& newColour) throw();
  43817. /** Turns this object into a gradient fill. */
  43818. void setGradient (const ColourGradient& newGradient);
  43819. /** Turns this object into a tiled image fill type. The transform allows you to set
  43820. the scaling, offset and rotation of the pattern.
  43821. */
  43822. void setTiledImage (const Image& image, const AffineTransform& transform) throw();
  43823. /** Changes the opacity that should be used.
  43824. If the fill is a solid colour, this just changes the opacity of that colour. For
  43825. gradients and image tiles, it changes the opacity that will be used for them.
  43826. */
  43827. void setOpacity (float newOpacity) throw();
  43828. /** Returns the current opacity to be applied to the colour, gradient, or image.
  43829. @see setOpacity
  43830. */
  43831. float getOpacity() const throw() { return colour.getFloatAlpha(); }
  43832. /** Returns true if this fill type is completely transparent. */
  43833. bool isInvisible() const throw();
  43834. bool operator== (const FillType& other) const;
  43835. bool operator!= (const FillType& other) const;
  43836. /** The solid colour being used.
  43837. If the fill type is not a solid colour, the alpha channel of this colour indicates
  43838. the opacity that should be used for the fill, and the RGB channels are ignored.
  43839. */
  43840. Colour colour;
  43841. /** Returns the gradient that should be used for filling.
  43842. This will be zero if the object is some other type of fill.
  43843. If a gradient is active, the overall opacity with which it should be applied
  43844. is indicated by the alpha channel of the colour variable.
  43845. */
  43846. ScopedPointer <ColourGradient> gradient;
  43847. /** The image that should be used for tiling.
  43848. If an image fill is active, the overall opacity with which it should be applied
  43849. is indicated by the alpha channel of the colour variable.
  43850. */
  43851. Image image;
  43852. /** The transform that should be applied to the image or gradient that's being drawn.
  43853. */
  43854. AffineTransform transform;
  43855. juce_UseDebuggingNewOperator
  43856. };
  43857. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  43858. /*** End of inlined file: juce_FillType.h ***/
  43859. #endif
  43860. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  43861. #endif
  43862. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  43863. #endif
  43864. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  43865. /*** Start of inlined file: juce_LowLevelGraphicsContext.h ***/
  43866. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  43867. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  43868. /**
  43869. Interface class for graphics context objects, used internally by the Graphics class.
  43870. Users are not supposed to create instances of this class directly - do your drawing
  43871. via the Graphics object instead.
  43872. It's a base class for different types of graphics context, that may perform software-based
  43873. or OS-accelerated rendering.
  43874. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  43875. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  43876. context.
  43877. */
  43878. class JUCE_API LowLevelGraphicsContext
  43879. {
  43880. protected:
  43881. LowLevelGraphicsContext();
  43882. public:
  43883. virtual ~LowLevelGraphicsContext();
  43884. /** Returns true if this device is vector-based, e.g. a printer. */
  43885. virtual bool isVectorDevice() const = 0;
  43886. /** Moves the origin to a new position.
  43887. The co-ords are relative to the current origin, and indicate the new position
  43888. of (0, 0).
  43889. */
  43890. virtual void setOrigin (int x, int y) = 0;
  43891. virtual bool clipToRectangle (const Rectangle<int>& r) = 0;
  43892. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  43893. virtual void excludeClipRectangle (const Rectangle<int>& r) = 0;
  43894. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  43895. virtual void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform) = 0;
  43896. virtual bool clipRegionIntersects (const Rectangle<int>& r) = 0;
  43897. virtual const Rectangle<int> getClipBounds() const = 0;
  43898. virtual bool isClipEmpty() const = 0;
  43899. virtual void saveState() = 0;
  43900. virtual void restoreState() = 0;
  43901. virtual void setFill (const FillType& fillType) = 0;
  43902. virtual void setOpacity (float newOpacity) = 0;
  43903. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  43904. virtual void fillRect (const Rectangle<int>& r, bool replaceExistingContents) = 0;
  43905. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  43906. virtual void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  43907. const AffineTransform& transform, bool fillEntireClipAsTiles) = 0;
  43908. virtual void drawLine (const Line <float>& line) = 0;
  43909. virtual void drawVerticalLine (int x, float top, float bottom) = 0;
  43910. virtual void drawHorizontalLine (int y, float left, float right) = 0;
  43911. virtual void setFont (const Font& newFont) = 0;
  43912. virtual const Font getFont() = 0;
  43913. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  43914. };
  43915. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  43916. /*** End of inlined file: juce_LowLevelGraphicsContext.h ***/
  43917. #endif
  43918. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  43919. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  43920. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  43921. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  43922. /**
  43923. An implementation of LowLevelGraphicsContext that turns the drawing operations
  43924. into a PostScript document.
  43925. */
  43926. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  43927. {
  43928. public:
  43929. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  43930. const String& documentTitle,
  43931. int totalWidth,
  43932. int totalHeight);
  43933. ~LowLevelGraphicsPostScriptRenderer();
  43934. bool isVectorDevice() const;
  43935. void setOrigin (int x, int y);
  43936. bool clipToRectangle (const Rectangle<int>& r);
  43937. bool clipToRectangleList (const RectangleList& clipRegion);
  43938. void excludeClipRectangle (const Rectangle<int>& r);
  43939. void clipToPath (const Path& path, const AffineTransform& transform);
  43940. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform);
  43941. void saveState();
  43942. void restoreState();
  43943. bool clipRegionIntersects (const Rectangle<int>& r);
  43944. const Rectangle<int> getClipBounds() const;
  43945. bool isClipEmpty() const;
  43946. void setFill (const FillType& fillType);
  43947. void setOpacity (float opacity);
  43948. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  43949. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  43950. void fillPath (const Path& path, const AffineTransform& transform);
  43951. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  43952. const AffineTransform& transform, bool fillEntireClipAsTiles);
  43953. void drawLine (const Line <float>& line);
  43954. void drawVerticalLine (int x, float top, float bottom);
  43955. void drawHorizontalLine (int x, float top, float bottom);
  43956. const Font getFont();
  43957. void setFont (const Font& newFont);
  43958. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  43959. juce_UseDebuggingNewOperator
  43960. protected:
  43961. OutputStream& out;
  43962. int totalWidth, totalHeight;
  43963. bool needToClip;
  43964. Colour lastColour;
  43965. struct SavedState
  43966. {
  43967. SavedState();
  43968. ~SavedState();
  43969. RectangleList clip;
  43970. int xOffset, yOffset;
  43971. FillType fillType;
  43972. Font font;
  43973. private:
  43974. SavedState& operator= (const SavedState&);
  43975. };
  43976. OwnedArray <SavedState> stateStack;
  43977. void writeClip();
  43978. void writeColour (const Colour& colour);
  43979. void writePath (const Path& path) const;
  43980. void writeXY (float x, float y) const;
  43981. void writeTransform (const AffineTransform& trans) const;
  43982. void writeImage (const Image& im, int sx, int sy, int maxW, int maxH) const;
  43983. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  43984. LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  43985. };
  43986. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  43987. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  43988. #endif
  43989. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  43990. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  43991. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  43992. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  43993. /**
  43994. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  43995. its rendering in memory.
  43996. User code is not supposed to create instances of this class directly - do all your
  43997. rendering via the Graphics class instead.
  43998. */
  43999. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  44000. {
  44001. public:
  44002. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn);
  44003. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn, int xOffset, int yOffset, const RectangleList& initialClip);
  44004. ~LowLevelGraphicsSoftwareRenderer();
  44005. bool isVectorDevice() const;
  44006. void setOrigin (int x, int y);
  44007. bool clipToRectangle (const Rectangle<int>& r);
  44008. bool clipToRectangleList (const RectangleList& clipRegion);
  44009. void excludeClipRectangle (const Rectangle<int>& r);
  44010. void clipToPath (const Path& path, const AffineTransform& transform);
  44011. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform);
  44012. bool clipRegionIntersects (const Rectangle<int>& r);
  44013. const Rectangle<int> getClipBounds() const;
  44014. bool isClipEmpty() const;
  44015. void saveState();
  44016. void restoreState();
  44017. void setFill (const FillType& fillType);
  44018. void setOpacity (float opacity);
  44019. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  44020. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  44021. void fillPath (const Path& path, const AffineTransform& transform);
  44022. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  44023. const AffineTransform& transform, bool fillEntireClipAsTiles);
  44024. void drawLine (const Line <float>& line);
  44025. void drawVerticalLine (int x, float top, float bottom);
  44026. void drawHorizontalLine (int x, float top, float bottom);
  44027. void setFont (const Font& newFont);
  44028. const Font getFont();
  44029. void drawGlyph (int glyphNumber, float x, float y);
  44030. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  44031. juce_UseDebuggingNewOperator
  44032. protected:
  44033. Image image;
  44034. class GlyphCache;
  44035. class CachedGlyph;
  44036. class SavedState;
  44037. friend class ScopedPointer <SavedState>;
  44038. friend class OwnedArray <SavedState>;
  44039. friend class OwnedArray <CachedGlyph>;
  44040. ScopedPointer <SavedState> currentState;
  44041. OwnedArray <SavedState> stateStack;
  44042. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  44043. LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  44044. };
  44045. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  44046. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  44047. #endif
  44048. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  44049. #endif
  44050. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  44051. #endif
  44052. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  44053. /*** Start of inlined file: juce_DrawableComposite.h ***/
  44054. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  44055. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  44056. /**
  44057. A drawable object which acts as a container for a set of other Drawables.
  44058. @see Drawable
  44059. */
  44060. class JUCE_API DrawableComposite : public Drawable,
  44061. public RelativeCoordinate::NamedCoordinateFinder
  44062. {
  44063. public:
  44064. /** Creates a composite Drawable. */
  44065. DrawableComposite();
  44066. /** Creates a copy of a DrawableComposite. */
  44067. DrawableComposite (const DrawableComposite& other);
  44068. /** Destructor. */
  44069. ~DrawableComposite();
  44070. /** Adds a new sub-drawable to this one.
  44071. This passes in a Drawable pointer for this object to look after. To add a copy
  44072. of a drawable, use the form of this method that takes a Drawable reference instead.
  44073. @param drawable the object to add - this will be deleted automatically
  44074. when no longer needed, so the caller mustn't keep any
  44075. pointers to it.
  44076. @param index where to insert it in the list of drawables. 0 is the back,
  44077. -1 is the front, or any value from 0 and getNumDrawables()
  44078. can be used
  44079. @see removeDrawable
  44080. */
  44081. void insertDrawable (Drawable* drawable, int index = -1);
  44082. /** Adds a new sub-drawable to this one.
  44083. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  44084. for this object to look after, use the form of this method that takes a Drawable
  44085. pointer instead.
  44086. @param drawable the object to add - an internal copy will be made of this object
  44087. @param index where to insert it in the list of drawables. 0 is the back,
  44088. -1 is the front, or any value from 0 and getNumDrawables()
  44089. can be used
  44090. @see removeDrawable
  44091. */
  44092. void insertDrawable (const Drawable& drawable, int index = -1);
  44093. /** Deletes one of the Drawable objects.
  44094. @param index the index of the drawable to delete, between 0
  44095. and (getNumDrawables() - 1).
  44096. @param deleteDrawable if this is true, the drawable that is removed will also
  44097. be deleted. If false, it'll just be removed.
  44098. @see insertDrawable, getNumDrawables
  44099. */
  44100. void removeDrawable (int index, bool deleteDrawable = true);
  44101. /** Returns the number of drawables contained inside this one.
  44102. @see getDrawable
  44103. */
  44104. int getNumDrawables() const throw() { return drawables.size(); }
  44105. /** Returns one of the drawables that are contained in this one.
  44106. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  44107. to find it.
  44108. The pointer returned is managed by this object and will be deleted when no longer
  44109. needed, so be careful what you do with it.
  44110. @see getNumDrawables
  44111. */
  44112. Drawable* getDrawable (int index) const throw() { return drawables [index]; }
  44113. /** Looks for a child drawable with the specified name. */
  44114. Drawable* getDrawableWithName (const String& name) const throw();
  44115. /** Brings one of the Drawables to the front.
  44116. @param index the index of the drawable to move, between 0
  44117. and (getNumDrawables() - 1).
  44118. @see insertDrawable, getNumDrawables
  44119. */
  44120. void bringToFront (int index);
  44121. /** Changes the main content area.
  44122. The content area is actually defined by the markers named "left", "right", "top" and
  44123. "bottom", but this method is a shortcut that sets them all at once.
  44124. @see contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  44125. */
  44126. const RelativeRectangle getContentArea() const;
  44127. /** Returns the main content rectangle.
  44128. The content area is actually defined by the markers named "left", "right", "top" and
  44129. "bottom", but this method is a shortcut that returns them all at once.
  44130. @see setBoundingBox, contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  44131. */
  44132. void setContentArea (const RelativeRectangle& newArea);
  44133. /** Sets the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  44134. @see setContentArea
  44135. */
  44136. void setBoundingBox (const RelativeParallelogram& newBoundingBox);
  44137. /** Returns the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  44138. @see setBoundingBox
  44139. */
  44140. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  44141. /** Changes the bounding box transform to match the content area, so that any sub-items will
  44142. be drawn at their untransformed positions.
  44143. */
  44144. void resetBoundingBoxToContentArea();
  44145. /** Resets the content area and the bounding transform to fit around the area occupied
  44146. by the child components (ignoring any markers).
  44147. */
  44148. void resetContentAreaAndBoundingBoxToFitChildren();
  44149. /** Represents a named marker position.
  44150. @see DrawableComposite::getMarker
  44151. */
  44152. struct Marker
  44153. {
  44154. Marker (const Marker&);
  44155. Marker (const String& name, const RelativeCoordinate& position);
  44156. bool operator!= (const Marker&) const throw();
  44157. String name;
  44158. RelativeCoordinate position;
  44159. };
  44160. int getNumMarkers (bool xAxis) const throw();
  44161. const Marker* getMarker (bool xAxis, int index) const throw();
  44162. void setMarker (const String& name, bool xAxis, const RelativeCoordinate& position);
  44163. void removeMarker (bool xAxis, int index);
  44164. /** The name of the marker that defines the left edge of the content area. */
  44165. static const char* const contentLeftMarkerName;
  44166. /** The name of the marker that defines the right edge of the content area. */
  44167. static const char* const contentRightMarkerName;
  44168. /** The name of the marker that defines the top edge of the content area. */
  44169. static const char* const contentTopMarkerName;
  44170. /** The name of the marker that defines the bottom edge of the content area. */
  44171. static const char* const contentBottomMarkerName;
  44172. /** @internal */
  44173. void render (const Drawable::RenderingContext& context) const;
  44174. /** @internal */
  44175. const Rectangle<float> getBounds() const;
  44176. /** @internal */
  44177. bool hitTest (float x, float y) const;
  44178. /** @internal */
  44179. Drawable* createCopy() const;
  44180. /** @internal */
  44181. void invalidatePoints();
  44182. /** @internal */
  44183. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44184. /** @internal */
  44185. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44186. /** @internal */
  44187. static const Identifier valueTreeType;
  44188. /** @internal */
  44189. const Identifier getValueTreeType() const { return valueTreeType; }
  44190. /** @internal */
  44191. const RelativeCoordinate findNamedCoordinate (const String& objectName, const String& edge) const;
  44192. /** Internally-used class for wrapping a DrawableComposite's state into a ValueTree. */
  44193. class ValueTreeWrapper : public ValueTreeWrapperBase
  44194. {
  44195. public:
  44196. ValueTreeWrapper (const ValueTree& state);
  44197. int getNumDrawables() const;
  44198. ValueTree getDrawableState (int index) const;
  44199. ValueTree getDrawableWithId (const String& objectId, bool recursive) const;
  44200. int indexOfDrawable (const ValueTree& item) const;
  44201. void addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager);
  44202. void moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager);
  44203. void removeDrawable (const ValueTree& child, UndoManager* undoManager);
  44204. const RelativeParallelogram getBoundingBox() const;
  44205. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  44206. void resetBoundingBoxToContentArea (UndoManager* undoManager);
  44207. const RelativeRectangle getContentArea() const;
  44208. void setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager);
  44209. int getNumMarkers (bool xAxis) const;
  44210. const ValueTree getMarkerState (bool xAxis, int index) const;
  44211. const ValueTree getMarkerState (bool xAxis, const String& name) const;
  44212. bool containsMarker (bool xAxis, const ValueTree& state) const;
  44213. const Marker getMarker (bool xAxis, const ValueTree& state) const;
  44214. void setMarker (bool xAxis, const Marker& marker, UndoManager* undoManager);
  44215. void removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager);
  44216. static const Identifier nameProperty, posProperty;
  44217. private:
  44218. static const Identifier topLeft, topRight, bottomLeft, childGroupTag, markerGroupTagX,
  44219. markerGroupTagY, markerTag;
  44220. ValueTree getChildList() const;
  44221. ValueTree getChildListCreating (UndoManager* undoManager);
  44222. ValueTree getMarkerList (bool xAxis) const;
  44223. ValueTree getMarkerListCreating (bool xAxis, UndoManager* undoManager);
  44224. };
  44225. juce_UseDebuggingNewOperator
  44226. private:
  44227. OwnedArray <Drawable> drawables;
  44228. RelativeParallelogram bounds;
  44229. OwnedArray <Marker> markersX, markersY;
  44230. const Rectangle<float> getUntransformedBounds (bool includeMarkers) const;
  44231. const AffineTransform calculateTransform() const;
  44232. DrawableComposite& operator= (const DrawableComposite&);
  44233. };
  44234. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  44235. /*** End of inlined file: juce_DrawableComposite.h ***/
  44236. #endif
  44237. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44238. /*** Start of inlined file: juce_DrawableImage.h ***/
  44239. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44240. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44241. /**
  44242. A drawable object which is a bitmap image.
  44243. @see Drawable
  44244. */
  44245. class JUCE_API DrawableImage : public Drawable
  44246. {
  44247. public:
  44248. DrawableImage();
  44249. DrawableImage (const DrawableImage& other);
  44250. /** Destructor. */
  44251. ~DrawableImage();
  44252. /** Sets the image that this drawable will render. */
  44253. void setImage (const Image& imageToUse);
  44254. /** Returns the current image. */
  44255. const Image getImage() const { return image; }
  44256. /** Sets the opacity to use when drawing the image. */
  44257. void setOpacity (float newOpacity);
  44258. /** Returns the image's opacity. */
  44259. float getOpacity() const throw() { return opacity; }
  44260. /** Sets a colour to draw over the image's alpha channel.
  44261. By default this is transparent so isn't drawn, but if you set a non-transparent
  44262. colour here, then it will be overlaid on the image, using the image's alpha
  44263. channel as a mask.
  44264. This is handy for doing things like darkening or lightening an image by overlaying
  44265. it with semi-transparent black or white.
  44266. */
  44267. void setOverlayColour (const Colour& newOverlayColour);
  44268. /** Returns the overlay colour. */
  44269. const Colour& getOverlayColour() const throw() { return overlayColour; }
  44270. /** Sets the bounding box within which the image should be displayed. */
  44271. void setBoundingBox (const RelativeParallelogram& newBounds);
  44272. /** Returns the position to which the image's top-left corner should be remapped in the target
  44273. coordinate space when rendering this object.
  44274. @see setTransform
  44275. */
  44276. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  44277. /** @internal */
  44278. void render (const Drawable::RenderingContext& context) const;
  44279. /** @internal */
  44280. const Rectangle<float> getBounds() const;
  44281. /** @internal */
  44282. bool hitTest (float x, float y) const;
  44283. /** @internal */
  44284. Drawable* createCopy() const;
  44285. /** @internal */
  44286. void invalidatePoints();
  44287. /** @internal */
  44288. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44289. /** @internal */
  44290. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44291. /** @internal */
  44292. static const Identifier valueTreeType;
  44293. /** @internal */
  44294. const Identifier getValueTreeType() const { return valueTreeType; }
  44295. /** Internally-used class for wrapping a DrawableImage's state into a ValueTree. */
  44296. class ValueTreeWrapper : public ValueTreeWrapperBase
  44297. {
  44298. public:
  44299. ValueTreeWrapper (const ValueTree& state);
  44300. const var getImageIdentifier() const;
  44301. void setImageIdentifier (const var& newIdentifier, UndoManager* undoManager);
  44302. Value getImageIdentifierValue (UndoManager* undoManager);
  44303. float getOpacity() const;
  44304. void setOpacity (float newOpacity, UndoManager* undoManager);
  44305. Value getOpacityValue (UndoManager* undoManager);
  44306. const Colour getOverlayColour() const;
  44307. void setOverlayColour (const Colour& newColour, UndoManager* undoManager);
  44308. Value getOverlayColourValue (UndoManager* undoManager);
  44309. const RelativeParallelogram getBoundingBox() const;
  44310. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  44311. static const Identifier opacity, overlay, image, topLeft, topRight, bottomLeft;
  44312. };
  44313. juce_UseDebuggingNewOperator
  44314. private:
  44315. Image image;
  44316. float opacity;
  44317. Colour overlayColour;
  44318. RelativeParallelogram bounds;
  44319. const AffineTransform calculateTransform() const;
  44320. DrawableImage& operator= (const DrawableImage&);
  44321. };
  44322. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44323. /*** End of inlined file: juce_DrawableImage.h ***/
  44324. #endif
  44325. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  44326. /*** Start of inlined file: juce_DrawablePath.h ***/
  44327. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  44328. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  44329. /**
  44330. A drawable object which renders a filled or outlined shape.
  44331. @see Drawable
  44332. */
  44333. class JUCE_API DrawablePath : public Drawable
  44334. {
  44335. public:
  44336. /** Creates a DrawablePath. */
  44337. DrawablePath();
  44338. DrawablePath (const DrawablePath& other);
  44339. /** Destructor. */
  44340. ~DrawablePath();
  44341. /** Changes the path that will be drawn.
  44342. @see setFillColour, setStrokeType
  44343. */
  44344. void setPath (const Path& newPath);
  44345. /** Sets a fill type for the path.
  44346. This colour is used to fill the path - if you don't want the path to be
  44347. filled (e.g. if you're just drawing an outline), set this to a transparent
  44348. colour.
  44349. @see setPath, setStrokeFill
  44350. */
  44351. void setFill (const FillType& newFill);
  44352. /** Returns the current fill type.
  44353. @see setFill
  44354. */
  44355. const FillType& getFill() const throw() { return mainFill; }
  44356. /** Sets the fill type with which the outline will be drawn.
  44357. @see setFill
  44358. */
  44359. void setStrokeFill (const FillType& newStrokeFill);
  44360. /** Returns the current stroke fill.
  44361. @see setStrokeFill
  44362. */
  44363. const FillType& getStrokeFill() const throw() { return strokeFill; }
  44364. /** Changes the properties of the outline that will be drawn around the path.
  44365. If the stroke has 0 thickness, no stroke will be drawn.
  44366. @see setStrokeThickness, setStrokeColour
  44367. */
  44368. void setStrokeType (const PathStrokeType& newStrokeType);
  44369. /** Changes the stroke thickness.
  44370. This is a shortcut for calling setStrokeType.
  44371. */
  44372. void setStrokeThickness (float newThickness);
  44373. /** Returns the current outline style. */
  44374. const PathStrokeType& getStrokeType() const throw() { return strokeType; }
  44375. /** Returns the current path. */
  44376. const Path& getPath() const;
  44377. /** Returns the current path for the outline. */
  44378. const Path& getStrokePath() const;
  44379. /** @internal */
  44380. void render (const Drawable::RenderingContext& context) const;
  44381. /** @internal */
  44382. const Rectangle<float> getBounds() const;
  44383. /** @internal */
  44384. bool hitTest (float x, float y) const;
  44385. /** @internal */
  44386. Drawable* createCopy() const;
  44387. /** @internal */
  44388. void invalidatePoints();
  44389. /** @internal */
  44390. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44391. /** @internal */
  44392. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44393. /** @internal */
  44394. static const Identifier valueTreeType;
  44395. /** @internal */
  44396. const Identifier getValueTreeType() const { return valueTreeType; }
  44397. /** Internally-used class for wrapping a DrawablePath's state into a ValueTree. */
  44398. class ValueTreeWrapper : public ValueTreeWrapperBase
  44399. {
  44400. public:
  44401. ValueTreeWrapper (const ValueTree& state);
  44402. const FillType getMainFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  44403. ImageProvider* imageProvider) const;
  44404. ValueTree getMainFillState();
  44405. void setMainFill (const FillType& newFill, const RelativePoint* gradientPoint1, const RelativePoint* gradientPoint2,
  44406. ImageProvider* imageProvider, UndoManager* undoManager);
  44407. const FillType getStrokeFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  44408. ImageProvider* imageProvider) const;
  44409. ValueTree getStrokeFillState();
  44410. void setStrokeFill (const FillType& newFill, const RelativePoint* gradientPoint1, const RelativePoint* gradientPoint2,
  44411. ImageProvider* imageProvider, UndoManager* undoManager);
  44412. const PathStrokeType getStrokeType() const;
  44413. void setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager);
  44414. bool usesNonZeroWinding() const;
  44415. void setUsesNonZeroWinding (bool b, UndoManager* undoManager);
  44416. class Element
  44417. {
  44418. public:
  44419. explicit Element (const ValueTree& state);
  44420. ~Element();
  44421. const Identifier getType() const throw() { return state.getType(); }
  44422. int getNumControlPoints() const throw();
  44423. const RelativePoint getControlPoint (int index) const;
  44424. Value getControlPointValue (int index, UndoManager* undoManager) const;
  44425. const RelativePoint getEndPoint() const;
  44426. void setControlPoint (int index, const RelativePoint& point, UndoManager* undoManager);
  44427. ValueTreeWrapper getParent() const;
  44428. static const Identifier startSubPathElement, closeSubPathElement,
  44429. lineToElement, quadraticToElement, cubicToElement;
  44430. ValueTree state;
  44431. };
  44432. ValueTree getPathState();
  44433. static const Identifier fill, stroke, path, jointStyle, capStyle, strokeWidth,
  44434. nonZeroWinding, point1, point2, point3;
  44435. };
  44436. juce_UseDebuggingNewOperator
  44437. private:
  44438. FillType mainFill, strokeFill;
  44439. PathStrokeType strokeType;
  44440. ScopedPointer<RelativePointPath> relativePath;
  44441. mutable Path path, stroke;
  44442. mutable bool pathNeedsUpdating, strokeNeedsUpdating;
  44443. void updatePath() const;
  44444. void updateStroke() const;
  44445. bool isStrokeVisible() const throw();
  44446. DrawablePath& operator= (const DrawablePath&);
  44447. };
  44448. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  44449. /*** End of inlined file: juce_DrawablePath.h ***/
  44450. #endif
  44451. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  44452. /*** Start of inlined file: juce_DrawableText.h ***/
  44453. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  44454. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  44455. /**
  44456. A drawable object which renders a line of text.
  44457. @see Drawable
  44458. */
  44459. class JUCE_API DrawableText : public Drawable
  44460. {
  44461. public:
  44462. /** Creates a DrawableText object. */
  44463. DrawableText();
  44464. DrawableText (const DrawableText& other);
  44465. /** Destructor. */
  44466. ~DrawableText();
  44467. /** Sets the text to display.*/
  44468. void setText (const String& newText);
  44469. /** Sets the colour of the text. */
  44470. void setColour (const Colour& newColour);
  44471. /** Returns the current text colour. */
  44472. const Colour& getColour() const throw() { return colour; }
  44473. /** Sets the font to use.
  44474. Note that the font height and horizontal scale are actually based upon the position
  44475. of the fontSizeAndScaleAnchor parameter to setBounds(). If applySizeAndScale is true, then
  44476. the height and scale control point will be moved to match the dimensions of the font supplied;
  44477. if it is false, then the new font's height and scale are ignored.
  44478. */
  44479. void setFont (const Font& newFont, bool applySizeAndScale);
  44480. /** Changes the justification of the text within the bounding box. */
  44481. void setJustification (const Justification& newJustification);
  44482. /** Returns the parallelogram that defines the text bounding box. */
  44483. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  44484. /** Sets the bounding box that contains the text. */
  44485. void setBoundingBox (const RelativeParallelogram& newBounds);
  44486. /** Returns the point within the bounds that defines the font's size and scale. */
  44487. const RelativePoint& getFontSizeControlPoint() const throw() { return fontSizeControlPoint; }
  44488. /** Sets the control point that defines the font's height and horizontal scale.
  44489. This position is a point within the bounding box parallelogram, whose Y position (relative
  44490. to the parallelogram's origin and possibly distorted shape) specifies the font's height,
  44491. and its X defines the font's horizontal scale.
  44492. */
  44493. void setFontSizeControlPoint (const RelativePoint& newPoint);
  44494. /** @internal */
  44495. void render (const Drawable::RenderingContext& context) const;
  44496. /** @internal */
  44497. const Rectangle<float> getBounds() const;
  44498. /** @internal */
  44499. bool hitTest (float x, float y) const;
  44500. /** @internal */
  44501. Drawable* createCopy() const;
  44502. /** @internal */
  44503. void invalidatePoints();
  44504. /** @internal */
  44505. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44506. /** @internal */
  44507. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44508. /** @internal */
  44509. static const Identifier valueTreeType;
  44510. /** @internal */
  44511. const Identifier getValueTreeType() const { return valueTreeType; }
  44512. /** Internally-used class for wrapping a DrawableText's state into a ValueTree. */
  44513. class ValueTreeWrapper : public ValueTreeWrapperBase
  44514. {
  44515. public:
  44516. ValueTreeWrapper (const ValueTree& state);
  44517. const String getText() const;
  44518. void setText (const String& newText, UndoManager* undoManager);
  44519. Value getTextValue (UndoManager* undoManager);
  44520. const Colour getColour() const;
  44521. void setColour (const Colour& newColour, UndoManager* undoManager);
  44522. const Justification getJustification() const;
  44523. void setJustification (const Justification& newJustification, UndoManager* undoManager);
  44524. const Font getFont() const;
  44525. void setFont (const Font& newFont, UndoManager* undoManager);
  44526. Value getFontValue (UndoManager* undoManager);
  44527. const RelativeParallelogram getBoundingBox() const;
  44528. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  44529. const RelativePoint getFontSizeControlPoint() const;
  44530. void setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager);
  44531. static const Identifier text, colour, font, justification, topLeft, topRight, bottomLeft, fontSizeAnchor;
  44532. };
  44533. juce_UseDebuggingNewOperator
  44534. private:
  44535. RelativeParallelogram bounds;
  44536. RelativePoint fontSizeControlPoint;
  44537. Font font;
  44538. String text;
  44539. Colour colour;
  44540. Justification justification;
  44541. DrawableText& operator= (const DrawableText&);
  44542. };
  44543. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  44544. /*** End of inlined file: juce_DrawableText.h ***/
  44545. #endif
  44546. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  44547. #endif
  44548. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  44549. /*** Start of inlined file: juce_GlowEffect.h ***/
  44550. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  44551. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  44552. /**
  44553. A component effect that adds a coloured blur around the component's contents.
  44554. (This will only work on non-opaque components).
  44555. @see Component::setComponentEffect, DropShadowEffect
  44556. */
  44557. class JUCE_API GlowEffect : public ImageEffectFilter
  44558. {
  44559. public:
  44560. /** Creates a default 'glow' effect.
  44561. To customise its appearance, use the setGlowProperties() method.
  44562. */
  44563. GlowEffect();
  44564. /** Destructor. */
  44565. ~GlowEffect();
  44566. /** Sets the glow's radius and colour.
  44567. The radius is how large the blur should be, and the colour is
  44568. used to render it (for a less intense glow, lower the colour's
  44569. opacity).
  44570. */
  44571. void setGlowProperties (float newRadius,
  44572. const Colour& newColour);
  44573. /** @internal */
  44574. void applyEffect (Image& sourceImage, Graphics& destContext);
  44575. juce_UseDebuggingNewOperator
  44576. private:
  44577. float radius;
  44578. Colour colour;
  44579. };
  44580. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  44581. /*** End of inlined file: juce_GlowEffect.h ***/
  44582. #endif
  44583. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  44584. #endif
  44585. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44586. /*** Start of inlined file: juce_ReduceOpacityEffect.h ***/
  44587. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44588. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44589. /**
  44590. An effect filter that reduces the image's opacity.
  44591. This can be used to make a component (and its child components) more
  44592. transparent.
  44593. @see Component::setComponentEffect
  44594. */
  44595. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  44596. {
  44597. public:
  44598. /** Creates the effect object.
  44599. The opacity of the component to which the effect is applied will be
  44600. scaled by the given factor (in the range 0 to 1.0f).
  44601. */
  44602. ReduceOpacityEffect (float opacity = 1.0f);
  44603. /** Destructor. */
  44604. ~ReduceOpacityEffect();
  44605. /** Sets how much to scale the component's opacity.
  44606. @param newOpacity should be between 0 and 1.0f
  44607. */
  44608. void setOpacity (float newOpacity);
  44609. /** @internal */
  44610. void applyEffect (Image& sourceImage, Graphics& destContext);
  44611. juce_UseDebuggingNewOperator
  44612. private:
  44613. float opacity;
  44614. };
  44615. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44616. /*** End of inlined file: juce_ReduceOpacityEffect.h ***/
  44617. #endif
  44618. #ifndef __JUCE_FONT_JUCEHEADER__
  44619. #endif
  44620. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  44621. #endif
  44622. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  44623. #endif
  44624. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  44625. #endif
  44626. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  44627. #endif
  44628. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  44629. #endif
  44630. #ifndef __JUCE_LINE_JUCEHEADER__
  44631. #endif
  44632. #ifndef __JUCE_PATH_JUCEHEADER__
  44633. #endif
  44634. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  44635. /*** Start of inlined file: juce_PathIterator.h ***/
  44636. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  44637. #define __JUCE_PATHITERATOR_JUCEHEADER__
  44638. /**
  44639. Flattens a Path object into a series of straight-line sections.
  44640. Use one of these to iterate through a Path object, and it will convert
  44641. all the curves into line sections so it's easy to render or perform
  44642. geometric operations on.
  44643. @see Path
  44644. */
  44645. class JUCE_API PathFlatteningIterator
  44646. {
  44647. public:
  44648. /** Creates a PathFlatteningIterator.
  44649. After creation, use the next() method to initialise the fields in the
  44650. object with the first line's position.
  44651. @param path the path to iterate along
  44652. @param transform a transform to apply to each point in the path being iterated
  44653. @param tolerence the amount by which the curves are allowed to deviate from the
  44654. lines into which they are being broken down - a higher tolerence
  44655. is a bit faster, but less smooth.
  44656. */
  44657. PathFlatteningIterator (const Path& path,
  44658. const AffineTransform& transform = AffineTransform::identity,
  44659. float tolerence = 6.0f);
  44660. /** Destructor. */
  44661. ~PathFlatteningIterator();
  44662. /** Fetches the next line segment from the path.
  44663. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  44664. so that they describe the new line segment.
  44665. @returns false when there are no more lines to fetch.
  44666. */
  44667. bool next();
  44668. float x1; /**< The x position of the start of the current line segment. */
  44669. float y1; /**< The y position of the start of the current line segment. */
  44670. float x2; /**< The x position of the end of the current line segment. */
  44671. float y2; /**< The y position of the end of the current line segment. */
  44672. /** Indicates whether the current line segment is closing a sub-path.
  44673. If the current line is the one that connects the end of a sub-path
  44674. back to the start again, this will be true.
  44675. */
  44676. bool closesSubPath;
  44677. /** The index of the current line within the current sub-path.
  44678. E.g. you can use this to see whether the line is the first one in the
  44679. subpath by seeing if it's 0.
  44680. */
  44681. int subPathIndex;
  44682. /** Returns true if the current segment is the last in the current sub-path. */
  44683. bool isLastInSubpath() const throw() { return stackPos == stackBase.getData()
  44684. && (index >= path.numElements || points [index] == Path::moveMarker); }
  44685. juce_UseDebuggingNewOperator
  44686. private:
  44687. const Path& path;
  44688. const AffineTransform transform;
  44689. float* points;
  44690. float tolerence, subPathCloseX, subPathCloseY;
  44691. const bool isIdentityTransform;
  44692. HeapBlock <float> stackBase;
  44693. float* stackPos;
  44694. size_t index, stackSize;
  44695. PathFlatteningIterator (const PathFlatteningIterator&);
  44696. PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  44697. };
  44698. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  44699. /*** End of inlined file: juce_PathIterator.h ***/
  44700. #endif
  44701. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  44702. #endif
  44703. #ifndef __JUCE_POINT_JUCEHEADER__
  44704. #endif
  44705. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  44706. /*** Start of inlined file: juce_PositionedRectangle.h ***/
  44707. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  44708. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  44709. /**
  44710. A rectangle whose co-ordinates can be defined in terms of absolute or
  44711. proportional distances.
  44712. Designed mainly for storing component positions, this gives you a lot of
  44713. control over how each co-ordinate is stored, either as an absolute position,
  44714. or as a proportion of the size of a parent rectangle.
  44715. It also allows you to define the anchor points by which the rectangle is
  44716. positioned, so for example you could specify that the top right of the
  44717. rectangle should be an absolute distance from its parent's bottom-right corner.
  44718. This object can be stored as a string, which takes the form "x y w h", including
  44719. symbols like '%' and letters to indicate the anchor point. See its toString()
  44720. method for more info.
  44721. Example usage:
  44722. @code
  44723. class MyComponent
  44724. {
  44725. void resized()
  44726. {
  44727. // this will set the child component's x to be 20% of our width, its y
  44728. // to be 30, its width to be 150, and its height to be 50% of our
  44729. // height..
  44730. const PositionedRectangle pos1 ("20% 30 150 50%");
  44731. pos1.applyToComponent (*myChildComponent1);
  44732. // this will inset the child component with a gap of 10 pixels
  44733. // around each of its edges..
  44734. const PositionedRectangle pos2 ("10 10 20M 20M");
  44735. pos2.applyToComponent (*myChildComponent2);
  44736. }
  44737. };
  44738. @endcode
  44739. */
  44740. class JUCE_API PositionedRectangle
  44741. {
  44742. public:
  44743. /** Creates an empty rectangle with all co-ordinates set to zero.
  44744. The default anchor point is top-left; the default
  44745. */
  44746. PositionedRectangle() throw();
  44747. /** Initialises a PositionedRectangle from a saved string version.
  44748. The string must be in the format generated by toString().
  44749. */
  44750. PositionedRectangle (const String& stringVersion) throw();
  44751. /** Creates a copy of another PositionedRectangle. */
  44752. PositionedRectangle (const PositionedRectangle& other) throw();
  44753. /** Copies another PositionedRectangle. */
  44754. PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  44755. /** Destructor. */
  44756. ~PositionedRectangle() throw();
  44757. /** Returns a string version of this position, from which it can later be
  44758. re-generated.
  44759. The format is four co-ordinates, "x y w h".
  44760. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  44761. - If a co-ordinate is proportional to its parent's width or height, it is stored
  44762. as a percentage, e.g. "80%".
  44763. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  44764. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  44765. the parent's right-hand edge.
  44766. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  44767. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  44768. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  44769. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  44770. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  44771. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  44772. has "c" appended to it. So "-50Rc" would mean that this component's
  44773. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  44774. this component's centre should be placed 40% across the parent's width.
  44775. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  44776. the number has "M" appended to it.
  44777. To reload a stored string, use the constructor that takes a string parameter.
  44778. */
  44779. const String toString() const throw();
  44780. /** Calculates the absolute position, given the size of the space that
  44781. it should go in.
  44782. This will work out any proportional distances and sizes relative to the
  44783. target rectangle, and will return the absolute position.
  44784. @see applyToComponent
  44785. */
  44786. const Rectangle<int> getRectangle (const Rectangle<int>& targetSpaceToBeRelativeTo) const throw();
  44787. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  44788. */
  44789. void getRectangleDouble (const Rectangle<int>& targetSpaceToBeRelativeTo,
  44790. double& x,
  44791. double& y,
  44792. double& width,
  44793. double& height) const throw();
  44794. /** This sets the bounds of the given component to this position.
  44795. This is equivalent to writing:
  44796. @code
  44797. comp.setBounds (getRectangle (Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  44798. @endcode
  44799. @see getRectangle, updateFromComponent
  44800. */
  44801. void applyToComponent (Component& comp) const throw();
  44802. /** Updates this object's co-ordinates to match the given rectangle.
  44803. This will set all co-ordinates based on the given rectangle, re-calculating
  44804. any proportional distances, and using the current anchor points.
  44805. So for example if the x co-ordinate mode is currently proportional, this will
  44806. re-calculate x based on the rectangle's relative position within the target
  44807. rectangle's width.
  44808. If the target rectangle's width or height are zero then it may not be possible
  44809. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  44810. will not be changed.
  44811. */
  44812. void updateFrom (const Rectangle<int>& newPosition,
  44813. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  44814. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  44815. */
  44816. void updateFromDouble (double x, double y, double width, double height,
  44817. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  44818. /** Updates this object's co-ordinates to match the bounds of this component.
  44819. This is equivalent to calling updateFrom() with the component's bounds and
  44820. it parent size.
  44821. If the component doesn't currently have a parent, then proportional co-ordinates
  44822. might not be updated because it would need to know the parent's size to do the
  44823. maths for this.
  44824. */
  44825. void updateFromComponent (const Component& comp) throw();
  44826. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  44827. enum AnchorPoint
  44828. {
  44829. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  44830. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  44831. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  44832. };
  44833. /** Specifies how an x or y co-ordinate should be interpreted. */
  44834. enum PositionMode
  44835. {
  44836. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  44837. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  44838. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  44839. 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. */
  44840. };
  44841. /** Specifies how the width or height should be interpreted. */
  44842. enum SizeMode
  44843. {
  44844. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  44845. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  44846. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  44847. };
  44848. /** Sets all options for all co-ordinates.
  44849. This requires a reference rectangle to be specified, because if you're changing any
  44850. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  44851. the co-ordinates, and will need to know the parent size so it can calculate this.
  44852. */
  44853. void setModes (const AnchorPoint xAnchorMode,
  44854. const PositionMode xPositionMode,
  44855. const AnchorPoint yAnchorMode,
  44856. const PositionMode yPositionMode,
  44857. const SizeMode widthMode,
  44858. const SizeMode heightMode,
  44859. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  44860. /** Returns the anchoring mode for the x co-ordinate.
  44861. To change any of the modes, use setModes().
  44862. */
  44863. AnchorPoint getAnchorPointX() const throw();
  44864. /** Returns the positioning mode for the x co-ordinate.
  44865. To change any of the modes, use setModes().
  44866. */
  44867. PositionMode getPositionModeX() const throw();
  44868. /** Returns the raw x co-ordinate.
  44869. If the x position mode is absolute, then this will be the absolute value. If it's
  44870. proportional, then this will be a fractional proportion, where 1.0 means the full
  44871. width of the parent space.
  44872. */
  44873. double getX() const throw() { return x; }
  44874. /** Sets the raw value of the x co-ordinate.
  44875. See getX() for the meaning of this value.
  44876. */
  44877. void setX (const double newX) throw() { x = newX; }
  44878. /** Returns the anchoring mode for the y co-ordinate.
  44879. To change any of the modes, use setModes().
  44880. */
  44881. AnchorPoint getAnchorPointY() const throw();
  44882. /** Returns the positioning mode for the y co-ordinate.
  44883. To change any of the modes, use setModes().
  44884. */
  44885. PositionMode getPositionModeY() const throw();
  44886. /** Returns the raw y co-ordinate.
  44887. If the y position mode is absolute, then this will be the absolute value. If it's
  44888. proportional, then this will be a fractional proportion, where 1.0 means the full
  44889. height of the parent space.
  44890. */
  44891. double getY() const throw() { return y; }
  44892. /** Sets the raw value of the y co-ordinate.
  44893. See getY() for the meaning of this value.
  44894. */
  44895. void setY (const double newY) throw() { y = newY; }
  44896. /** Returns the mode used to calculate the width.
  44897. To change any of the modes, use setModes().
  44898. */
  44899. SizeMode getWidthMode() const throw();
  44900. /** Returns the raw width value.
  44901. If the width mode is absolute, then this will be the absolute value. If the mode is
  44902. proportional, then this will be a fractional proportion, where 1.0 means the full
  44903. width of the parent space.
  44904. */
  44905. double getWidth() const throw() { return w; }
  44906. /** Sets the raw width value.
  44907. See getWidth() for the details about what this value means.
  44908. */
  44909. void setWidth (const double newWidth) throw() { w = newWidth; }
  44910. /** Returns the mode used to calculate the height.
  44911. To change any of the modes, use setModes().
  44912. */
  44913. SizeMode getHeightMode() const throw();
  44914. /** Returns the raw height value.
  44915. If the height mode is absolute, then this will be the absolute value. If the mode is
  44916. proportional, then this will be a fractional proportion, where 1.0 means the full
  44917. height of the parent space.
  44918. */
  44919. double getHeight() const throw() { return h; }
  44920. /** Sets the raw height value.
  44921. See getHeight() for the details about what this value means.
  44922. */
  44923. void setHeight (const double newHeight) throw() { h = newHeight; }
  44924. /** If the size and position are constance, and wouldn't be affected by changes
  44925. in the parent's size, then this will return true.
  44926. */
  44927. bool isPositionAbsolute() const throw();
  44928. /** Compares two objects. */
  44929. bool operator== (const PositionedRectangle& other) const throw();
  44930. /** Compares two objects. */
  44931. bool operator!= (const PositionedRectangle& other) const throw();
  44932. juce_UseDebuggingNewOperator
  44933. private:
  44934. double x, y, w, h;
  44935. uint8 xMode, yMode, wMode, hMode;
  44936. void addPosDescription (String& result, uint8 mode, double value) const throw();
  44937. void addSizeDescription (String& result, uint8 mode, double value) const throw();
  44938. void decodePosString (const String& s, uint8& mode, double& value) throw();
  44939. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  44940. void applyPosAndSize (double& xOut, double& wOut, double x, double w,
  44941. uint8 xMode, uint8 wMode,
  44942. int parentPos, int parentSize) const throw();
  44943. void updatePosAndSize (double& xOut, double& wOut, double x, double w,
  44944. uint8 xMode, uint8 wMode,
  44945. int parentPos, int parentSize) const throw();
  44946. };
  44947. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  44948. /*** End of inlined file: juce_PositionedRectangle.h ***/
  44949. #endif
  44950. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  44951. #endif
  44952. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  44953. #endif
  44954. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  44955. #endif
  44956. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  44957. /*** Start of inlined file: juce_CameraDevice.h ***/
  44958. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  44959. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  44960. #if JUCE_USE_CAMERA || DOXYGEN
  44961. /**
  44962. Receives callbacks with images from a CameraDevice.
  44963. @see CameraDevice::addListener
  44964. */
  44965. class CameraImageListener
  44966. {
  44967. public:
  44968. CameraImageListener() {}
  44969. virtual ~CameraImageListener() {}
  44970. /** This method is called when a new image arrives.
  44971. This may be called by any thread, so be careful about thread-safety,
  44972. and make sure that you process the data as quickly as possible to
  44973. avoid glitching!
  44974. */
  44975. virtual void imageReceived (const Image& image) = 0;
  44976. };
  44977. /**
  44978. Controls any camera capture devices that might be available.
  44979. Use getAvailableDevices() to list the devices that are attached to the
  44980. system, then call openDevice to open one for use. Once you have a CameraDevice
  44981. object, you can get a viewer component from it, and use its methods to
  44982. stream to a file or capture still-frames.
  44983. */
  44984. class JUCE_API CameraDevice
  44985. {
  44986. public:
  44987. /** Destructor. */
  44988. virtual ~CameraDevice();
  44989. /** Returns a list of the available cameras on this machine.
  44990. You can open one of these devices by calling openDevice().
  44991. */
  44992. static const StringArray getAvailableDevices();
  44993. /** Opens a camera device.
  44994. The index parameter indicates which of the items returned by getAvailableDevices()
  44995. to open.
  44996. The size constraints allow the method to choose between different resolutions if
  44997. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  44998. then these will be ignored.
  44999. */
  45000. static CameraDevice* openDevice (int deviceIndex,
  45001. int minWidth = 128, int minHeight = 64,
  45002. int maxWidth = 1024, int maxHeight = 768);
  45003. /** Returns the name of this device */
  45004. const String getName() const { return name; }
  45005. /** Creates a component that can be used to display a preview of the
  45006. video from this camera.
  45007. */
  45008. Component* createViewerComponent();
  45009. /** Starts recording video to the specified file.
  45010. You should use getFileExtension() to find out the correct extension to
  45011. use for your filename.
  45012. If the file exists, it will be deleted before the recording starts.
  45013. This method may not start recording instantly, so if you need to know the
  45014. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  45015. after the recording has finished.
  45016. The quality parameter can be 0, 1, or 2, to indicate low, medium, or high. It may
  45017. or may not be used, depending on the driver.
  45018. */
  45019. void startRecordingToFile (const File& file, int quality = 2);
  45020. /** Stops recording, after a call to startRecordingToFile().
  45021. */
  45022. void stopRecording();
  45023. /** Returns the file extension that should be used for the files
  45024. that you pass to startRecordingToFile().
  45025. This may be platform-specific, e.g. ".mov" or ".avi".
  45026. */
  45027. static const String getFileExtension();
  45028. /** After calling stopRecording(), this method can be called to return the timestamp
  45029. of the first frame that was written to the file.
  45030. */
  45031. const Time getTimeOfFirstRecordedFrame() const;
  45032. /** Adds a listener to receive images from the camera.
  45033. Be very careful not to delete the listener without first removing it by calling
  45034. removeListener().
  45035. */
  45036. void addListener (CameraImageListener* listenerToAdd);
  45037. /** Removes a listener that was previously added with addListener().
  45038. */
  45039. void removeListener (CameraImageListener* listenerToRemove);
  45040. juce_UseDebuggingNewOperator
  45041. protected:
  45042. /** @internal */
  45043. CameraDevice (const String& name, int index);
  45044. private:
  45045. void* internal;
  45046. bool isRecording;
  45047. String name;
  45048. CameraDevice (const CameraDevice&);
  45049. CameraDevice& operator= (const CameraDevice&);
  45050. };
  45051. #endif
  45052. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  45053. /*** End of inlined file: juce_CameraDevice.h ***/
  45054. #endif
  45055. #ifndef __JUCE_IMAGE_JUCEHEADER__
  45056. #endif
  45057. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  45058. /*** Start of inlined file: juce_ImageCache.h ***/
  45059. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  45060. #define __JUCE_IMAGECACHE_JUCEHEADER__
  45061. /**
  45062. A global cache of images that have been loaded from files or memory.
  45063. If you're loading an image and may need to use the image in more than one
  45064. place, this is used to allow the same image to be shared rather than loading
  45065. multiple copies into memory.
  45066. Another advantage is that after images are released, they will be kept in
  45067. memory for a few seconds before it is actually deleted, so if you're repeatedly
  45068. loading/deleting the same image, it'll reduce the chances of having to reload it
  45069. each time.
  45070. @see Image, ImageFileFormat
  45071. */
  45072. class JUCE_API ImageCache
  45073. {
  45074. public:
  45075. /** Loads an image from a file, (or just returns the image if it's already cached).
  45076. If the cache already contains an image that was loaded from this file,
  45077. that image will be returned. Otherwise, this method will try to load the
  45078. file, add it to the cache, and return it.
  45079. Remember that the image returned is shared, so drawing into it might
  45080. affect other things that are using it! If you want to draw on it, first
  45081. call Image::duplicateIfShared()
  45082. @param file the file to try to load
  45083. @returns the image, or null if it there was an error loading it
  45084. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  45085. */
  45086. static const Image getFromFile (const File& file);
  45087. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  45088. If the cache already contains an image that was loaded from this block of memory,
  45089. that image will be returned. Otherwise, this method will try to load the
  45090. file, add it to the cache, and return it.
  45091. Remember that the image returned is shared, so drawing into it might
  45092. affect other things that are using it! If you want to draw on it, first
  45093. call Image::duplicateIfShared()
  45094. @param imageData the block of memory containing the image data
  45095. @param dataSize the data size in bytes
  45096. @returns the image, or an invalid image if it there was an error loading it
  45097. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  45098. */
  45099. static const Image getFromMemory (const void* imageData, int dataSize);
  45100. /** Checks the cache for an image with a particular hashcode.
  45101. If there's an image in the cache with this hashcode, it will be returned,
  45102. otherwise it will return an invalid image.
  45103. @param hashCode the hash code that was associated with the image by addImageToCache()
  45104. @see addImageToCache
  45105. */
  45106. static const Image getFromHashCode (int64 hashCode);
  45107. /** Adds an image to the cache with a user-defined hash-code.
  45108. The image passed-in will be referenced (not copied) by the cache, so it's probably
  45109. a good idea not to draw into it after adding it, otherwise this will affect all
  45110. instances of it that may be in use.
  45111. @param image the image to add
  45112. @param hashCode the hash-code to associate with it
  45113. @see getFromHashCode
  45114. */
  45115. static void addImageToCache (const Image& image, int64 hashCode);
  45116. /** Changes the amount of time before an unused image will be removed from the cache.
  45117. By default this is about 5 seconds.
  45118. */
  45119. static void setCacheTimeout (int millisecs);
  45120. juce_UseDebuggingNewOperator
  45121. private:
  45122. class Pimpl;
  45123. ImageCache();
  45124. ImageCache (const ImageCache&);
  45125. ImageCache& operator= (const ImageCache&);
  45126. ~ImageCache();
  45127. };
  45128. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  45129. /*** End of inlined file: juce_ImageCache.h ***/
  45130. #endif
  45131. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45132. /*** Start of inlined file: juce_ImageConvolutionKernel.h ***/
  45133. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45134. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45135. /**
  45136. Represents a filter kernel to use in convoluting an image.
  45137. @see Image::applyConvolution
  45138. */
  45139. class JUCE_API ImageConvolutionKernel
  45140. {
  45141. public:
  45142. /** Creates an empty convulution kernel.
  45143. @param size the length of each dimension of the kernel, so e.g. if the size
  45144. is 5, it will create a 5x5 kernel
  45145. */
  45146. ImageConvolutionKernel (int size);
  45147. /** Destructor. */
  45148. ~ImageConvolutionKernel();
  45149. /** Resets all values in the kernel to zero. */
  45150. void clear();
  45151. /** Returns one of the kernel values. */
  45152. float getKernelValue (int x, int y) const throw();
  45153. /** Sets the value of a specific cell in the kernel.
  45154. The x and y parameters must be in the range 0 < x < getKernelSize().
  45155. @see setOverallSum
  45156. */
  45157. void setKernelValue (int x, int y, float value) throw();
  45158. /** Rescales all values in the kernel to make the total add up to a fixed value.
  45159. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  45160. */
  45161. void setOverallSum (float desiredTotalSum);
  45162. /** Multiplies all values in the kernel by a value. */
  45163. void rescaleAllValues (float multiplier);
  45164. /** Intialises the kernel for a gaussian blur.
  45165. @param blurRadius this may be larger or smaller than the kernel's actual
  45166. size but this will obviously be wasteful or clip at the
  45167. edges. Ideally the kernel should be just larger than
  45168. (blurRadius * 2).
  45169. */
  45170. void createGaussianBlur (float blurRadius);
  45171. /** Returns the size of the kernel.
  45172. E.g. if it's a 3x3 kernel, this returns 3.
  45173. */
  45174. int getKernelSize() const { return size; }
  45175. /** Applies the kernel to an image.
  45176. @param destImage the image that will receive the resultant convoluted pixels.
  45177. @param sourceImage the source image to read from - this can be the same image as
  45178. the destination, but if different, it must be exactly the same
  45179. size and format.
  45180. @param destinationArea the region of the image to apply the filter to
  45181. */
  45182. void applyToImage (Image& destImage,
  45183. const Image& sourceImage,
  45184. const Rectangle<int>& destinationArea) const;
  45185. juce_UseDebuggingNewOperator
  45186. private:
  45187. HeapBlock <float> values;
  45188. const int size;
  45189. // no reason not to implement these one day..
  45190. ImageConvolutionKernel (const ImageConvolutionKernel&);
  45191. ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  45192. };
  45193. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45194. /*** End of inlined file: juce_ImageConvolutionKernel.h ***/
  45195. #endif
  45196. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45197. /*** Start of inlined file: juce_ImageFileFormat.h ***/
  45198. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45199. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45200. /**
  45201. Base-class for codecs that can read and write image file formats such
  45202. as PNG, JPEG, etc.
  45203. This class also contains static methods to make it easy to load images
  45204. from files, streams or from memory.
  45205. @see Image, ImageCache
  45206. */
  45207. class JUCE_API ImageFileFormat
  45208. {
  45209. protected:
  45210. /** Creates an ImageFormat. */
  45211. ImageFileFormat() {}
  45212. public:
  45213. /** Destructor. */
  45214. virtual ~ImageFileFormat() {}
  45215. /** Returns a description of this file format.
  45216. E.g. "JPEG", "PNG"
  45217. */
  45218. virtual const String getFormatName() = 0;
  45219. /** Returns true if the given stream seems to contain data that this format
  45220. understands.
  45221. The format class should only read the first few bytes of the stream and sniff
  45222. for header bytes that it understands.
  45223. @see decodeImage
  45224. */
  45225. virtual bool canUnderstand (InputStream& input) = 0;
  45226. /** Tries to decode and return an image from the given stream.
  45227. This will be called for an image format after calling its canUnderStand() method
  45228. to see if it can handle the stream.
  45229. @param input the stream to read the data from. The stream will be positioned
  45230. at the start of the image data (but this may not necessarily
  45231. be position 0)
  45232. @returns the image that was decoded, or an invalid image if it fails.
  45233. @see loadFrom
  45234. */
  45235. virtual const Image decodeImage (InputStream& input) = 0;
  45236. /** Attempts to write an image to a stream.
  45237. To specify extra information like encoding quality, there will be appropriate parameters
  45238. in the subclasses of the specific file types.
  45239. @returns true if it nothing went wrong.
  45240. */
  45241. virtual bool writeImageToStream (const Image& sourceImage,
  45242. OutputStream& destStream) = 0;
  45243. /** Tries the built-in decoders to see if it can find one to read this stream.
  45244. There are currently built-in decoders for PNG, JPEG and GIF formats.
  45245. The object that is returned should not be deleted by the caller.
  45246. @see canUnderstand, decodeImage, loadFrom
  45247. */
  45248. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  45249. /** Tries to load an image from a stream.
  45250. This will use the findImageFormatForStream() method to locate a suitable
  45251. codec, and use that to load the image.
  45252. @returns the image that was decoded, or an invalid image if it fails.
  45253. */
  45254. static const Image loadFrom (InputStream& input);
  45255. /** Tries to load an image from a file.
  45256. This will use the findImageFormatForStream() method to locate a suitable
  45257. codec, and use that to load the image.
  45258. @returns the image that was decoded, or an invalid image if it fails.
  45259. */
  45260. static const Image loadFrom (const File& file);
  45261. /** Tries to load an image from a block of raw image data.
  45262. This will use the findImageFormatForStream() method to locate a suitable
  45263. codec, and use that to load the image.
  45264. @returns the image that was decoded, or an invalid image if it fails.
  45265. */
  45266. static const Image loadFrom (const void* rawData,
  45267. const int numBytesOfData);
  45268. };
  45269. /**
  45270. A type of ImageFileFormat for reading and writing PNG files.
  45271. @see ImageFileFormat, JPEGImageFormat
  45272. */
  45273. class JUCE_API PNGImageFormat : public ImageFileFormat
  45274. {
  45275. public:
  45276. PNGImageFormat();
  45277. ~PNGImageFormat();
  45278. const String getFormatName();
  45279. bool canUnderstand (InputStream& input);
  45280. const Image decodeImage (InputStream& input);
  45281. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  45282. };
  45283. /**
  45284. A type of ImageFileFormat for reading and writing JPEG files.
  45285. @see ImageFileFormat, PNGImageFormat
  45286. */
  45287. class JUCE_API JPEGImageFormat : public ImageFileFormat
  45288. {
  45289. public:
  45290. JPEGImageFormat();
  45291. ~JPEGImageFormat();
  45292. /** Specifies the quality to be used when writing a JPEG file.
  45293. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  45294. any negative value is "default" quality
  45295. */
  45296. void setQuality (const float newQuality);
  45297. const String getFormatName();
  45298. bool canUnderstand (InputStream& input);
  45299. const Image decodeImage (InputStream& input);
  45300. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  45301. private:
  45302. float quality;
  45303. };
  45304. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45305. /*** End of inlined file: juce_ImageFileFormat.h ***/
  45306. #endif
  45307. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  45308. #endif
  45309. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45310. /*** Start of inlined file: juce_FileBasedDocument.h ***/
  45311. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45312. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45313. /**
  45314. A class to take care of the logic involved with the loading/saving of some kind
  45315. of document.
  45316. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  45317. functions you need for documents that get saved to a file, so this class attempts
  45318. to abstract most of the boring stuff.
  45319. Your subclass should just implement all the pure virtual methods, and you can
  45320. then use the higher-level public methods to do the load/save dialogs, to warn the user
  45321. about overwriting files, etc.
  45322. The document object keeps track of whether it has changed since it was last saved or
  45323. loaded, so when you change something, call its changed() method. This will set a
  45324. flag so it knows it needs saving, and will also broadcast a change message using the
  45325. ChangeBroadcaster base class.
  45326. @see ChangeBroadcaster
  45327. */
  45328. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  45329. {
  45330. public:
  45331. /** Creates a FileBasedDocument.
  45332. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  45333. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  45334. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  45335. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  45336. */
  45337. FileBasedDocument (const String& fileExtension,
  45338. const String& fileWildCard,
  45339. const String& openFileDialogTitle,
  45340. const String& saveFileDialogTitle);
  45341. /** Destructor. */
  45342. virtual ~FileBasedDocument();
  45343. /** Returns true if the changed() method has been called since the file was
  45344. last saved or loaded.
  45345. @see resetChangedFlag, changed
  45346. */
  45347. bool hasChangedSinceSaved() const { return changedSinceSave; }
  45348. /** Called to indicate that the document has changed and needs saving.
  45349. This method will also trigger a change message to be sent out using the
  45350. ChangeBroadcaster base class.
  45351. After calling the method, the hasChangedSinceSaved() method will return true, until
  45352. it is reset either by saving to a file or using the resetChangedFlag() method.
  45353. @see hasChangedSinceSaved, resetChangedFlag
  45354. */
  45355. virtual void changed();
  45356. /** Sets the state of the 'changed' flag.
  45357. The 'changed' flag is set to true when the changed() method is called - use this method
  45358. to reset it or to set it without also broadcasting a change message.
  45359. @see changed, hasChangedSinceSaved
  45360. */
  45361. void setChangedFlag (bool hasChanged);
  45362. /** Tries to open a file.
  45363. If the file opens correctly, the document's file (see the getFile() method) is set
  45364. to this new one; if it fails, the document's file is left unchanged, and optionally
  45365. a message box is shown telling the user there was an error.
  45366. @returns true if the new file loaded successfully
  45367. @see loadDocument, loadFromUserSpecifiedFile
  45368. */
  45369. bool loadFrom (const File& fileToLoadFrom,
  45370. bool showMessageOnFailure);
  45371. /** Asks the user for a file and tries to load it.
  45372. This will pop up a dialog box using the title, file extension and
  45373. wildcard specified in the document's constructor, and asks the user
  45374. for a file. If they pick one, the loadFrom() method is used to
  45375. try to load it, optionally showing a message if it fails.
  45376. @returns true if a file was loaded; false if the user cancelled or if they
  45377. picked a file which failed to load correctly
  45378. @see loadFrom
  45379. */
  45380. bool loadFromUserSpecifiedFile (bool showMessageOnFailure);
  45381. /** A set of possible outcomes of one of the save() methods
  45382. */
  45383. enum SaveResult
  45384. {
  45385. savedOk = 0, /**< indicates that a file was saved successfully. */
  45386. userCancelledSave, /**< indicates that the user aborted the save operation. */
  45387. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  45388. };
  45389. /** Tries to save the document to the last file it was saved or loaded from.
  45390. This will always try to write to the file, even if the document isn't flagged as
  45391. having changed.
  45392. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  45393. true, it will prompt the user to pick a file, as if
  45394. saveAsInteractive() was called.
  45395. @param showMessageOnFailure if true it will show a warning message when if the
  45396. save operation fails
  45397. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  45398. */
  45399. SaveResult save (bool askUserForFileIfNotSpecified,
  45400. bool showMessageOnFailure);
  45401. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  45402. it if they say yes.
  45403. If you've got a document open and want to close it (e.g. to quit the app), this is the
  45404. method to call.
  45405. If the document doesn't need saving it'll return the value savedOk so
  45406. you can go ahead and delete the document.
  45407. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  45408. return savedOk, so again, you can safely delete the document.
  45409. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  45410. close-document operation.
  45411. And if they click "save changes", it'll try to save and either return savedOk, or
  45412. failedToWriteToFile if there was a problem.
  45413. @see save, saveAs, saveAsInteractive
  45414. */
  45415. SaveResult saveIfNeededAndUserAgrees();
  45416. /** Tries to save the document to a specified file.
  45417. If this succeeds, it'll also change the document's internal file (as returned by
  45418. the getFile() method). If it fails, the file will be left unchanged.
  45419. @param newFile the file to try to write to
  45420. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  45421. the user first if they want to overwrite it
  45422. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  45423. use the saveAsInteractive() method to ask the user for a
  45424. filename
  45425. @param showMessageOnFailure if true and the write operation fails, it'll show
  45426. a message box to warn the user
  45427. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  45428. */
  45429. SaveResult saveAs (const File& newFile,
  45430. bool warnAboutOverwritingExistingFiles,
  45431. bool askUserForFileIfNotSpecified,
  45432. bool showMessageOnFailure);
  45433. /** Prompts the user for a filename and tries to save to it.
  45434. This will pop up a dialog box using the title, file extension and
  45435. wildcard specified in the document's constructor, and asks the user
  45436. for a file. If they pick one, the saveAs() method is used to try to save
  45437. to this file.
  45438. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  45439. the user first if they want to overwrite it
  45440. @see saveIfNeededAndUserAgrees, save, saveAs
  45441. */
  45442. SaveResult saveAsInteractive (bool warnAboutOverwritingExistingFiles);
  45443. /** Returns the file that this document was last successfully saved or loaded from.
  45444. When the document object is created, this will be set to File::nonexistent.
  45445. It is changed when one of the load or save methods is used, or when setFile()
  45446. is used to explicitly set it.
  45447. */
  45448. const File getFile() const { return documentFile; }
  45449. /** Sets the file that this document thinks it was loaded from.
  45450. This won't actually load anything - it just changes the file stored internally.
  45451. @see getFile
  45452. */
  45453. void setFile (const File& newFile);
  45454. protected:
  45455. /** Overload this to return the title of the document.
  45456. This is used in message boxes, filenames and file choosers, so it should be
  45457. something sensible.
  45458. */
  45459. virtual const String getDocumentTitle() = 0;
  45460. /** This method should try to load your document from the given file.
  45461. If it fails, it should return an error message. If it succeeds, it should return
  45462. an empty string.
  45463. */
  45464. virtual const String loadDocument (const File& file) = 0;
  45465. /** This method should try to write your document to the given file.
  45466. If it fails, it should return an error message. If it succeeds, it should return
  45467. an empty string.
  45468. */
  45469. virtual const String saveDocument (const File& file) = 0;
  45470. /** This is used for dialog boxes to make them open at the last folder you
  45471. were using.
  45472. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  45473. the last document that was used - you might want to store this value
  45474. in a static variable, or even in your application's properties. It should
  45475. be a global setting rather than a property of this object.
  45476. This method works very well in conjunction with a RecentlyOpenedFilesList
  45477. object to manage your recent-files list.
  45478. As a default value, it's ok to return File::nonexistent, and the document
  45479. object will use a sensible one instead.
  45480. @see RecentlyOpenedFilesList
  45481. */
  45482. virtual const File getLastDocumentOpened() = 0;
  45483. /** This is used for dialog boxes to make them open at the last folder you
  45484. were using.
  45485. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  45486. the last document that was used - you might want to store this value
  45487. in a static variable, or even in your application's properties. It should
  45488. be a global setting rather than a property of this object.
  45489. This method works very well in conjunction with a RecentlyOpenedFilesList
  45490. object to manage your recent-files list.
  45491. @see RecentlyOpenedFilesList
  45492. */
  45493. virtual void setLastDocumentOpened (const File& file) = 0;
  45494. public:
  45495. juce_UseDebuggingNewOperator
  45496. private:
  45497. File documentFile;
  45498. bool changedSinceSave;
  45499. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  45500. FileBasedDocument (const FileBasedDocument&);
  45501. FileBasedDocument& operator= (const FileBasedDocument&);
  45502. };
  45503. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45504. /*** End of inlined file: juce_FileBasedDocument.h ***/
  45505. #endif
  45506. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  45507. #endif
  45508. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45509. /*** Start of inlined file: juce_RecentlyOpenedFilesList.h ***/
  45510. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45511. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45512. /**
  45513. Manages a set of files for use as a list of recently-opened documents.
  45514. This is a handy class for holding your list of recently-opened documents, with
  45515. helpful methods for things like purging any non-existent files, automatically
  45516. adding them to a menu, and making persistence easy.
  45517. @see File, FileBasedDocument
  45518. */
  45519. class JUCE_API RecentlyOpenedFilesList
  45520. {
  45521. public:
  45522. /** Creates an empty list.
  45523. */
  45524. RecentlyOpenedFilesList();
  45525. /** Destructor. */
  45526. ~RecentlyOpenedFilesList();
  45527. /** Sets a limit for the number of files that will be stored in the list.
  45528. When addFile() is called, then if there is no more space in the list, the
  45529. least-recently added file will be dropped.
  45530. @see getMaxNumberOfItems
  45531. */
  45532. void setMaxNumberOfItems (int newMaxNumber);
  45533. /** Returns the number of items that this list will store.
  45534. @see setMaxNumberOfItems
  45535. */
  45536. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  45537. /** Returns the number of files in the list.
  45538. The most recently added file is always at index 0.
  45539. */
  45540. int getNumFiles() const;
  45541. /** Returns one of the files in the list.
  45542. The most recently added file is always at index 0.
  45543. */
  45544. const File getFile (int index) const;
  45545. /** Returns an array of all the absolute pathnames in the list.
  45546. */
  45547. const StringArray& getAllFilenames() const throw() { return files; }
  45548. /** Clears all the files from the list. */
  45549. void clear();
  45550. /** Adds a file to the list.
  45551. The file will be added at index 0. If this file is already in the list, it will
  45552. be moved up to index 0, but a file can only appear once in the list.
  45553. If the list already contains the maximum number of items that is permitted, the
  45554. least-recently added file will be dropped from the end.
  45555. */
  45556. void addFile (const File& file);
  45557. /** Checks each of the files in the list, removing any that don't exist.
  45558. You might want to call this after reloading a list of files, or before putting them
  45559. on a menu.
  45560. */
  45561. void removeNonExistentFiles();
  45562. /** Adds entries to a menu, representing each of the files in the list.
  45563. This is handy for creating an "open recent file..." menu in your app. The
  45564. menu items are numbered consecutively starting with the baseItemId value,
  45565. and can either be added as complete pathnames, or just the last part of the
  45566. filename.
  45567. If dontAddNonExistentFiles is true, then each file will be checked and only those
  45568. that exist will be added.
  45569. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  45570. pointers to file objects. Any files that appear in this list will not be added to the
  45571. menu - the reason for this is that you might have a number of files already open, so
  45572. might not want these to be shown in the menu.
  45573. It returns the number of items that were added.
  45574. */
  45575. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  45576. int baseItemId,
  45577. bool showFullPaths,
  45578. bool dontAddNonExistentFiles,
  45579. const File** filesToAvoid = 0);
  45580. /** Returns a string that encapsulates all the files in the list.
  45581. The string that is returned can later be passed into restoreFromString() in
  45582. order to recreate the list. This is handy for persisting your list, e.g. in
  45583. a PropertiesFile object.
  45584. @see restoreFromString
  45585. */
  45586. const String toString() const;
  45587. /** Restores the list from a previously stringified version of the list.
  45588. Pass in a stringified version created with toString() in order to persist/restore
  45589. your list.
  45590. @see toString
  45591. */
  45592. void restoreFromString (const String& stringifiedVersion);
  45593. juce_UseDebuggingNewOperator
  45594. private:
  45595. StringArray files;
  45596. int maxNumberOfItems;
  45597. };
  45598. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45599. /*** End of inlined file: juce_RecentlyOpenedFilesList.h ***/
  45600. #endif
  45601. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  45602. #endif
  45603. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45604. /*** Start of inlined file: juce_SystemClipboard.h ***/
  45605. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45606. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45607. /**
  45608. Handles reading/writing to the system's clipboard.
  45609. */
  45610. class JUCE_API SystemClipboard
  45611. {
  45612. public:
  45613. /** Copies a string of text onto the clipboard */
  45614. static void copyTextToClipboard (const String& text);
  45615. /** Gets the current clipboard's contents.
  45616. Obviously this might have come from another app, so could contain
  45617. anything..
  45618. */
  45619. static const String getTextFromClipboard();
  45620. };
  45621. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45622. /*** End of inlined file: juce_SystemClipboard.h ***/
  45623. #endif
  45624. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  45625. #endif
  45626. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  45627. #endif
  45628. #endif
  45629. /*** End of inlined file: juce_app_includes.h ***/
  45630. #endif
  45631. #if JUCE_MSVC
  45632. #pragma warning (pop)
  45633. #pragma pack (pop)
  45634. #endif
  45635. END_JUCE_NAMESPACE
  45636. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  45637. #ifdef JUCE_NAMESPACE
  45638. // this will obviously save a lot of typing, but can be disabled by
  45639. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  45640. using namespace JUCE_NAMESPACE;
  45641. /* On the Mac, these symbols are defined in the Mac libraries, so
  45642. these macros make it easier to reference them without writing out
  45643. the namespace every time.
  45644. If you run into difficulties where these macros interfere with the contents
  45645. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  45646. the comments in that file for more information.
  45647. */
  45648. #if (JUCE_MAC || JUCE_IPHONE) && ! JUCE_DONT_DEFINE_MACROS
  45649. #define Component JUCE_NAMESPACE::Component
  45650. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  45651. #define Point JUCE_NAMESPACE::Point
  45652. #define Button JUCE_NAMESPACE::Button
  45653. #endif
  45654. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  45655. it easier to use the juce version explicitly.
  45656. If you run into difficulties where this macro interferes with other 3rd party header
  45657. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  45658. file for more information.
  45659. */
  45660. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  45661. #define Rectangle JUCE_NAMESPACE::Rectangle
  45662. #endif
  45663. #endif
  45664. #endif
  45665. /* Easy autolinking to the right JUCE libraries under win32.
  45666. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  45667. including this header file.
  45668. */
  45669. #if JUCE_MSVC
  45670. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  45671. /** If you want your application to link to Juce as a DLL instead of
  45672. a static library (on win32), just define the JUCE_DLL macro before
  45673. including juce.h
  45674. */
  45675. #ifdef JUCE_DLL
  45676. #if JUCE_DEBUG
  45677. #define AUTOLINKEDLIB "JUCE_debug.lib"
  45678. #else
  45679. #define AUTOLINKEDLIB "JUCE.lib"
  45680. #endif
  45681. #else
  45682. #if JUCE_DEBUG
  45683. #ifdef _WIN64
  45684. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  45685. #else
  45686. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  45687. #endif
  45688. #else
  45689. #ifdef _WIN64
  45690. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  45691. #else
  45692. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  45693. #endif
  45694. #endif
  45695. #endif
  45696. #pragma comment(lib, AUTOLINKEDLIB)
  45697. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  45698. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  45699. #endif
  45700. // Auto-link the other win32 libs that are needed by library calls..
  45701. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  45702. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  45703. // Auto-links to various win32 libs that are needed by library calls..
  45704. #pragma comment(lib, "kernel32.lib")
  45705. #pragma comment(lib, "user32.lib")
  45706. #pragma comment(lib, "shell32.lib")
  45707. #pragma comment(lib, "gdi32.lib")
  45708. #pragma comment(lib, "vfw32.lib")
  45709. #pragma comment(lib, "comdlg32.lib")
  45710. #pragma comment(lib, "winmm.lib")
  45711. #pragma comment(lib, "wininet.lib")
  45712. #pragma comment(lib, "ole32.lib")
  45713. #pragma comment(lib, "oleaut32.lib")
  45714. #pragma comment(lib, "advapi32.lib")
  45715. #pragma comment(lib, "ws2_32.lib")
  45716. #pragma comment(lib, "comsupp.lib")
  45717. #pragma comment(lib, "version.lib")
  45718. #if JUCE_OPENGL
  45719. #pragma comment(lib, "OpenGL32.Lib")
  45720. #pragma comment(lib, "GlU32.Lib")
  45721. #endif
  45722. #if JUCE_QUICKTIME
  45723. #pragma comment (lib, "QTMLClient.lib")
  45724. #endif
  45725. #if JUCE_USE_CAMERA
  45726. #pragma comment (lib, "Strmiids.lib")
  45727. #pragma comment (lib, "wmvcore.lib")
  45728. #endif
  45729. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  45730. #endif
  45731. #endif
  45732. #endif
  45733. /*
  45734. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  45735. AppSubClass is the name of a class derived from JUCEApplication.
  45736. See the JUCEApplication class documentation (juce_Application.h) for more details.
  45737. */
  45738. #if defined (JUCE_GCC) || defined (__MWERKS__)
  45739. #define START_JUCE_APPLICATION(AppClass) \
  45740. int main (int argc, char* argv[]) \
  45741. { \
  45742. return JUCE_NAMESPACE::JUCEApplication::main (argc, (const char**) argv, new AppClass()); \
  45743. }
  45744. #elif JUCE_WINDOWS
  45745. #ifdef _CONSOLE
  45746. #define START_JUCE_APPLICATION(AppClass) \
  45747. int main (int, char* argv[]) \
  45748. { \
  45749. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  45750. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  45751. }
  45752. #elif ! defined (_AFXDLL)
  45753. #ifdef _WINDOWS_
  45754. #define START_JUCE_APPLICATION(AppClass) \
  45755. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  45756. { \
  45757. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  45758. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  45759. }
  45760. #else
  45761. #define START_JUCE_APPLICATION(AppClass) \
  45762. int __stdcall WinMain (int, int, const char*, int) \
  45763. { \
  45764. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  45765. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  45766. }
  45767. #endif
  45768. #endif
  45769. #endif
  45770. #endif // __JUCE_JUCEHEADER__
  45771. /*** End of inlined file: juce.h ***/
  45772. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__