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.

60715 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 12
  46. /** Current Juce version number.
  47. Bits 16 to 32 = major version.
  48. Bits 8 to 16 = minor version.
  49. Bits 0 to 8 = point release (not currently used).
  50. See also SystemStats::getJUCEVersion() for a string version.
  51. */
  52. #define JUCE_VERSION ((JUCE_MAJOR_VERSION << 16) + (JUCE_MINOR_VERSION << 8) + JUCE_BUILDNUMBER)
  53. /*** Start of inlined file: juce_TargetPlatform.h ***/
  54. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  55. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  56. /* This file figures out which platform is being built, and defines some macros
  57. that the rest of the code can use for OS-specific compilation.
  58. Macros that will be set here are:
  59. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  60. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  61. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  62. - Either JUCE_INTEL or JUCE_PPC
  63. - Either JUCE_GCC or JUCE_MSVC
  64. */
  65. #if (defined (_WIN32) || defined (_WIN64))
  66. #define JUCE_WIN32 1
  67. #define JUCE_WINDOWS 1
  68. #elif defined (LINUX) || defined (__linux__)
  69. #define JUCE_LINUX 1
  70. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  71. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  72. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  73. #define JUCE_IPHONE 1
  74. #else
  75. #define JUCE_MAC 1
  76. #endif
  77. #else
  78. #error "Unknown platform!"
  79. #endif
  80. #if JUCE_WINDOWS
  81. #ifdef _MSC_VER
  82. #ifdef _WIN64
  83. #define JUCE_64BIT 1
  84. #else
  85. #define JUCE_32BIT 1
  86. #endif
  87. #endif
  88. #ifdef _DEBUG
  89. #define JUCE_DEBUG 1
  90. #endif
  91. #ifdef __MINGW32__
  92. #define JUCE_MINGW 1
  93. #endif
  94. /** If defined, this indicates that the processor is little-endian. */
  95. #define JUCE_LITTLE_ENDIAN 1
  96. #define JUCE_INTEL 1
  97. #endif
  98. #if JUCE_MAC
  99. #ifndef NDEBUG
  100. #define JUCE_DEBUG 1
  101. #endif
  102. #ifdef __LITTLE_ENDIAN__
  103. #define JUCE_LITTLE_ENDIAN 1
  104. #else
  105. #define JUCE_BIG_ENDIAN 1
  106. #endif
  107. #if defined (__ppc__) || defined (__ppc64__)
  108. #define JUCE_PPC 1
  109. #else
  110. #define JUCE_INTEL 1
  111. #endif
  112. #ifdef __LP64__
  113. #define JUCE_64BIT 1
  114. #else
  115. #define JUCE_32BIT 1
  116. #endif
  117. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  118. #error "Building for OSX 10.3 is no longer supported!"
  119. #endif
  120. #ifndef MAC_OS_X_VERSION_10_5
  121. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  122. #endif
  123. #endif
  124. #if JUCE_IPHONE
  125. #ifndef NDEBUG
  126. #define JUCE_DEBUG 1
  127. #endif
  128. #ifdef __LITTLE_ENDIAN__
  129. #define JUCE_LITTLE_ENDIAN 1
  130. #else
  131. #define JUCE_BIG_ENDIAN 1
  132. #endif
  133. #endif
  134. #if JUCE_LINUX
  135. #ifdef _DEBUG
  136. #define JUCE_DEBUG 1
  137. #endif
  138. // Allow override for big-endian Linux platforms
  139. #ifndef JUCE_BIG_ENDIAN
  140. #define JUCE_LITTLE_ENDIAN 1
  141. #endif
  142. #if defined (__LP64__) || defined (_LP64)
  143. #define JUCE_64BIT 1
  144. #else
  145. #define JUCE_32BIT 1
  146. #endif
  147. #define JUCE_INTEL 1
  148. #endif
  149. // Compiler type macros.
  150. #ifdef __GNUC__
  151. #define JUCE_GCC 1
  152. #elif defined (_MSC_VER)
  153. #define JUCE_MSVC 1
  154. #if _MSC_VER >= 1400
  155. #define JUCE_USE_INTRINSICS 1
  156. #endif
  157. #else
  158. #error unknown compiler
  159. #endif
  160. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  161. /*** End of inlined file: juce_TargetPlatform.h ***/
  162. // (sets up the various JUCE_WINDOWS, JUCE_MAC, etc flags)
  163. /*** Start of inlined file: juce_Config.h ***/
  164. #ifndef __JUCE_CONFIG_JUCEHEADER__
  165. #define __JUCE_CONFIG_JUCEHEADER__
  166. /*
  167. This file contains macros that enable/disable various JUCE features.
  168. */
  169. /** The name of the namespace that all Juce classes and functions will be
  170. put inside. If this is not defined, no namespace will be used.
  171. */
  172. #ifndef JUCE_NAMESPACE
  173. #define JUCE_NAMESPACE juce
  174. #endif
  175. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  176. project settings, but if you define this value, you can override this to force
  177. it to be true or false.
  178. */
  179. #ifndef JUCE_FORCE_DEBUG
  180. //#define JUCE_FORCE_DEBUG 0
  181. #endif
  182. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  183. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  184. Enabling it will also leave this turned on in release builds. When it's disabled,
  185. however, the jassert and jassertfalse macros will not be compiled in a
  186. release build.
  187. @see jassert, jassertfalse, Logger
  188. */
  189. #ifndef JUCE_LOG_ASSERTIONS
  190. #define JUCE_LOG_ASSERTIONS 0
  191. #endif
  192. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  193. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  194. on your Windows build machine.
  195. See the comments in the ASIOAudioIODevice class's header file for more
  196. info about this.
  197. */
  198. #ifndef JUCE_ASIO
  199. #define JUCE_ASIO 0
  200. #endif
  201. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  202. */
  203. #ifndef JUCE_WASAPI
  204. #define JUCE_WASAPI 0
  205. #endif
  206. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  207. */
  208. #ifndef JUCE_DIRECTSOUND
  209. #define JUCE_DIRECTSOUND 1
  210. #endif
  211. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  212. #ifndef JUCE_ALSA
  213. #define JUCE_ALSA 1
  214. #endif
  215. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  216. #ifndef JUCE_JACK
  217. #define JUCE_JACK 0
  218. #endif
  219. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  220. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  221. installed, and its header files will need to be on your include path.
  222. */
  223. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IPHONE || (JUCE_WINDOWS && ! JUCE_MSVC))
  224. #define JUCE_QUICKTIME 0
  225. #endif
  226. #if (JUCE_IPHONE || JUCE_LINUX) && JUCE_QUICKTIME
  227. #undef JUCE_QUICKTIME
  228. #endif
  229. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  230. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  231. */
  232. #ifndef JUCE_OPENGL
  233. #define JUCE_OPENGL 1
  234. #endif
  235. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  236. If your app doesn't need to read FLAC files, you might want to disable this to
  237. reduce the size of your codebase and build time.
  238. */
  239. #ifndef JUCE_USE_FLAC
  240. #define JUCE_USE_FLAC 1
  241. #endif
  242. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  243. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  244. reduce the size of your codebase and build time.
  245. */
  246. #ifndef JUCE_USE_OGGVORBIS
  247. #define JUCE_USE_OGGVORBIS 1
  248. #endif
  249. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  250. Unless you're using CD-burning, you should probably turn this flag off to
  251. reduce code size.
  252. */
  253. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  254. #define JUCE_USE_CDBURNER 0
  255. #endif
  256. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  257. Unless you're using CD-reading, you should probably turn this flag off to
  258. reduce code size.
  259. */
  260. #ifndef JUCE_USE_CDREADER
  261. #define JUCE_USE_CDREADER 0
  262. #endif
  263. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  264. */
  265. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  266. #define JUCE_USE_CAMERA 0
  267. #endif
  268. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  269. gets repainted will flash in a random colour, so that you can check exactly how much and how
  270. often your components are being drawn.
  271. */
  272. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  273. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  274. #endif
  275. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  276. Unless you specifically want to disable this, it's best to leave this option turned on.
  277. */
  278. #ifndef JUCE_USE_XINERAMA
  279. #define JUCE_USE_XINERAMA 1
  280. #endif
  281. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  282. turned on unless you have a good reason to disable it.
  283. */
  284. #ifndef JUCE_USE_XSHM
  285. #define JUCE_USE_XSHM 1
  286. #endif
  287. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  288. */
  289. #ifndef JUCE_USE_XRENDER
  290. #define JUCE_USE_XRENDER 0
  291. #endif
  292. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  293. unless you have a good reason to disable it.
  294. */
  295. #ifndef JUCE_USE_XCURSOR
  296. #define JUCE_USE_XCURSOR 1
  297. #endif
  298. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  299. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  300. you're building a plugin hosting app.
  301. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  302. */
  303. #ifndef JUCE_PLUGINHOST_VST
  304. #define JUCE_PLUGINHOST_VST 0
  305. #endif
  306. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  307. of course, and should only be enabled if you're building a plugin hosting app.
  308. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  309. */
  310. #ifndef JUCE_PLUGINHOST_AU
  311. #define JUCE_PLUGINHOST_AU 0
  312. #endif
  313. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  314. This should be enabled if you're writing a console application.
  315. */
  316. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  317. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  318. #endif
  319. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  320. If you're not using any embedded web-pages, turning this off may reduce your code size.
  321. */
  322. #ifndef JUCE_WEB_BROWSER
  323. #define JUCE_WEB_BROWSER 1
  324. #endif
  325. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  326. Carbon isn't required for a normal app, but may be needed by specialised classes like
  327. plugin-hosts, which support older APIs.
  328. */
  329. #ifndef JUCE_SUPPORT_CARBON
  330. #define JUCE_SUPPORT_CARBON 1
  331. #endif
  332. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  333. You might need to tweak this if you're linking to an external zlib library in your app,
  334. but for normal apps, this option should be left alone.
  335. */
  336. #ifndef JUCE_INCLUDE_ZLIB_CODE
  337. #define JUCE_INCLUDE_ZLIB_CODE 1
  338. #endif
  339. #ifndef JUCE_INCLUDE_FLAC_CODE
  340. #define JUCE_INCLUDE_FLAC_CODE 1
  341. #endif
  342. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  343. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  344. #endif
  345. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  346. #define JUCE_INCLUDE_PNGLIB_CODE 1
  347. #endif
  348. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  349. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  350. #endif
  351. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  352. (Currently, this only affects Windows builds in debug mode).
  353. */
  354. #ifndef JUCE_CHECK_MEMORY_LEAKS
  355. #define JUCE_CHECK_MEMORY_LEAKS 1
  356. #endif
  357. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  358. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  359. are passed to the JUCEApplication::unhandledException() callback for logging.
  360. */
  361. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  362. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  363. #endif
  364. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  365. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  366. #undef JUCE_QUICKTIME
  367. #define JUCE_QUICKTIME 0
  368. #undef JUCE_OPENGL
  369. #define JUCE_OPENGL 0
  370. #undef JUCE_USE_CDBURNER
  371. #define JUCE_USE_CDBURNER 0
  372. #undef JUCE_USE_CDREADER
  373. #define JUCE_USE_CDREADER 0
  374. #undef JUCE_WEB_BROWSER
  375. #define JUCE_WEB_BROWSER 0
  376. #undef JUCE_PLUGINHOST_AU
  377. #define JUCE_PLUGINHOST_AU 0
  378. #undef JUCE_PLUGINHOST_VST
  379. #define JUCE_PLUGINHOST_VST 0
  380. #endif
  381. #endif
  382. /*** End of inlined file: juce_Config.h ***/
  383. #ifdef JUCE_NAMESPACE
  384. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  385. #define END_JUCE_NAMESPACE }
  386. #else
  387. #define BEGIN_JUCE_NAMESPACE
  388. #define END_JUCE_NAMESPACE
  389. #endif
  390. /*** Start of inlined file: juce_PlatformDefs.h ***/
  391. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  392. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  393. /* This file defines miscellaneous macros for debugging, assertions, etc.
  394. */
  395. #ifdef JUCE_FORCE_DEBUG
  396. #undef JUCE_DEBUG
  397. #if JUCE_FORCE_DEBUG
  398. #define JUCE_DEBUG 1
  399. #endif
  400. #endif
  401. /** This macro defines the C calling convention used as the standard for Juce calls. */
  402. #if JUCE_MSVC
  403. #define JUCE_CALLTYPE __stdcall
  404. #else
  405. #define JUCE_CALLTYPE
  406. #endif
  407. // Debugging and assertion macros
  408. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  409. #if JUCE_LOG_ASSERTIONS
  410. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  411. #elif JUCE_DEBUG
  412. #define juce_LogCurrentAssertion std::cerr << "JUCE Assertion failure in " << __FILE__ << ", line " << __LINE__ << std::endl;
  413. #else
  414. #define juce_LogCurrentAssertion
  415. #endif
  416. #if JUCE_DEBUG
  417. // If debugging is enabled..
  418. /** Writes a string to the standard error stream.
  419. This is only compiled in a debug build.
  420. @see Logger::outputDebugString
  421. */
  422. #define DBG(dbgtext) Logger::outputDebugString (dbgtext);
  423. // Assertions..
  424. #if JUCE_WINDOWS || DOXYGEN
  425. #if JUCE_USE_INTRINSICS
  426. #pragma intrinsic (__debugbreak)
  427. /** This will try to break the debugger if one is currently hosting this app.
  428. @see jassert()
  429. */
  430. #define juce_breakDebugger __debugbreak();
  431. #elif JUCE_GCC
  432. /** This will try to break the debugger if one is currently hosting this app.
  433. @see jassert()
  434. */
  435. #define juce_breakDebugger asm("int $3");
  436. #else
  437. /** This will try to break the debugger if one is currently hosting this app.
  438. @see jassert()
  439. */
  440. #define juce_breakDebugger { __asm int 3 }
  441. #endif
  442. #elif JUCE_MAC
  443. #define juce_breakDebugger Debugger();
  444. #elif JUCE_IPHONE
  445. #define juce_breakDebugger kill (0, SIGTRAP);
  446. #elif JUCE_LINUX
  447. #define juce_breakDebugger kill (0, SIGTRAP);
  448. #endif
  449. /** This will always cause an assertion failure.
  450. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled
  451. in juce_Config.h).
  452. @see jassert()
  453. */
  454. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  455. /** Platform-independent assertion macro.
  456. This gets optimised out when not being built with debugging turned on.
  457. Be careful not to call any functions within its arguments that are vital to
  458. the behaviour of the program, because these won't get called in the release
  459. build.
  460. @see jassertfalse
  461. */
  462. #define jassert(expression) { if (! (expression)) jassertfalse; }
  463. #else
  464. // If debugging is disabled, these dummy debug and assertion macros are used..
  465. #define DBG(dbgtext)
  466. #define jassertfalse { juce_LogCurrentAssertion }
  467. #if JUCE_LOG_ASSERTIONS
  468. #define jassert(expression) { if (! (expression)) jassertfalse; }
  469. #else
  470. #define jassert(a) { }
  471. #endif
  472. #endif
  473. #ifndef DOXYGEN
  474. template <bool b> struct JuceStaticAssert;
  475. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  476. #endif
  477. /** A compile-time assertion macro.
  478. If the expression parameter is false, the macro will cause a compile error.
  479. */
  480. #define static_jassert(expression) JuceStaticAssert<expression>::dummy();
  481. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  482. #define JUCE_TRY try
  483. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  484. object so they can be logged by the application if it wants to.
  485. */
  486. #define JUCE_CATCH_EXCEPTION \
  487. catch (const std::exception& e) \
  488. { \
  489. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  490. } \
  491. catch (...) \
  492. { \
  493. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  494. }
  495. #define JUCE_CATCH_ALL catch (...) {}
  496. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse; }
  497. #else
  498. #define JUCE_TRY
  499. #define JUCE_CATCH_EXCEPTION
  500. #define JUCE_CATCH_ALL
  501. #define JUCE_CATCH_ALL_ASSERT
  502. #endif
  503. // Macros for inlining.
  504. #if JUCE_MSVC
  505. /** A platform-independent way of forcing an inline function.
  506. Use the syntax: @code
  507. forcedinline void myfunction (int x)
  508. @endcode
  509. */
  510. #ifndef JUCE_DEBUG
  511. #define forcedinline __forceinline
  512. #else
  513. #define forcedinline inline
  514. #endif
  515. #define JUCE_ALIGN(bytes) __declspec (align (bytes))
  516. #else
  517. /** A platform-independent way of forcing an inline function.
  518. Use the syntax: @code
  519. forcedinline void myfunction (int x)
  520. @endcode
  521. */
  522. #ifndef JUCE_DEBUG
  523. #define forcedinline inline __attribute__((always_inline))
  524. #else
  525. #define forcedinline inline
  526. #endif
  527. #define JUCE_ALIGN(bytes) __attribute__ ((aligned (bytes)))
  528. #endif
  529. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  530. /*** End of inlined file: juce_PlatformDefs.h ***/
  531. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  532. #if JUCE_MSVC
  533. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  534. #pragma warning (disable: 4284 4786) // (spurious VC6 warnings)
  535. #endif
  536. #pragma warning (push)
  537. #pragma warning (disable: 4514 4245 4100)
  538. #endif
  539. #include <cstdlib>
  540. #include <cstdarg>
  541. #include <climits>
  542. #include <limits>
  543. #include <cmath>
  544. #include <cwchar>
  545. #include <stdexcept>
  546. #include <typeinfo>
  547. #include <cstring>
  548. #include <cstdio>
  549. #include <iostream>
  550. #if JUCE_USE_INTRINSICS
  551. #include <intrin.h>
  552. #endif
  553. #if JUCE_MAC || JUCE_IPHONE
  554. #include <libkern/OSAtomic.h>
  555. #endif
  556. #if JUCE_LINUX
  557. #include <signal.h>
  558. #if __INTEL_COMPILER
  559. #if __ia64__
  560. #include <ia64intrin.h>
  561. #else
  562. #include <ia32intrin.h>
  563. #endif
  564. #endif
  565. #endif
  566. #if JUCE_MSVC && JUCE_DEBUG
  567. #include <crtdbg.h>
  568. #endif
  569. #if JUCE_MSVC
  570. #include <malloc.h>
  571. #pragma warning (pop)
  572. #if ! JUCE_PUBLIC_INCLUDES
  573. #pragma warning (4: 4511 4512 4100) // (enable some warnings that are turned off in VC8)
  574. #endif
  575. #endif
  576. // DLL building settings on Win32
  577. #if JUCE_MSVC
  578. #ifdef JUCE_DLL_BUILD
  579. #define JUCE_API __declspec (dllexport)
  580. #pragma warning (disable: 4251)
  581. #elif defined (JUCE_DLL)
  582. #define JUCE_API __declspec (dllimport)
  583. #pragma warning (disable: 4251)
  584. #endif
  585. #elif defined (__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
  586. #ifdef JUCE_DLL_BUILD
  587. #define JUCE_API __attribute__ ((visibility("default")))
  588. #endif
  589. #endif
  590. #ifndef JUCE_API
  591. /** This macro is added to all juce public class declarations. */
  592. #define JUCE_API
  593. #endif
  594. /** This macro is added to all juce public function declarations. */
  595. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  596. // Now include some basics that are needed by most of the Juce classes...
  597. BEGIN_JUCE_NAMESPACE
  598. extern bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger();
  599. #if JUCE_LOG_ASSERTIONS
  600. extern void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw();
  601. #endif
  602. /*** Start of inlined file: juce_Memory.h ***/
  603. #ifndef __JUCE_MEMORY_JUCEHEADER__
  604. #define __JUCE_MEMORY_JUCEHEADER__
  605. /*
  606. This file defines the various juce_malloc(), juce_free() macros that should be used in
  607. preference to the standard calls.
  608. */
  609. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  610. #ifndef JUCE_DLL
  611. // Win32 debug non-DLL versions..
  612. /** This should be used instead of calling malloc directly.
  613. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  614. */
  615. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  616. /** This should be used instead of calling calloc directly.
  617. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  618. */
  619. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  620. /** This should be used instead of calling realloc directly.
  621. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  622. */
  623. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  624. /** This should be used instead of calling free directly.
  625. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  626. */
  627. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  628. #else
  629. // Win32 debug DLL versions..
  630. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  631. // way all juce calls in the DLL and in the host API will all use the same allocator.
  632. extern JUCE_API void* juce_DebugMalloc (const int size, const char* file, const int line);
  633. extern JUCE_API void* juce_DebugCalloc (const int size, const char* file, const int line);
  634. extern JUCE_API void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line);
  635. extern JUCE_API void juce_DebugFree (void* const block);
  636. /** This should be used instead of calling malloc directly.
  637. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  638. */
  639. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  640. /** This should be used instead of calling calloc directly.
  641. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  642. */
  643. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  644. /** This should be used instead of calling realloc directly.
  645. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  646. */
  647. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  648. /** This should be used instead of calling free directly.
  649. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  650. */
  651. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  652. #endif
  653. #if ! defined (_AFXDLL)
  654. /** This macro can be added to classes to add extra debugging information to the memory
  655. allocated for them, so you can see the type of objects involved when there's a dump
  656. of leaked objects at program shutdown. (Only works on win32 at the moment).
  657. */
  658. #define juce_UseDebuggingNewOperator \
  659. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  660. static void* operator new (size_t, void* p) { return p; } \
  661. static void operator delete (void* p) { juce_free (p); } \
  662. static void operator delete (void*, void*) { }
  663. #endif
  664. #elif defined (JUCE_DLL)
  665. // Win32 DLL (release) versions..
  666. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  667. // way all juce calls in the DLL and in the host API will all use the same allocator.
  668. extern JUCE_API void* juce_Malloc (const int size);
  669. extern JUCE_API void* juce_Calloc (const int size);
  670. extern JUCE_API void* juce_Realloc (void* const block, const int size);
  671. extern JUCE_API void juce_Free (void* const block);
  672. /** This should be used instead of calling malloc directly.
  673. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  674. */
  675. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  676. /** This should be used instead of calling calloc directly.
  677. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  678. */
  679. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  680. /** This should be used instead of calling realloc directly.
  681. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  682. */
  683. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  684. /** This should be used instead of calling free directly.
  685. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  686. */
  687. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  688. #define juce_UseDebuggingNewOperator \
  689. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  690. static void* operator new (size_t, void* p) { return p; } \
  691. static void operator delete (void* p) { juce_free (p); } \
  692. static void operator delete (void*, void*) { }
  693. #else
  694. // Mac, Linux and Win32 (release) versions..
  695. /** This should be used instead of calling malloc directly.
  696. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  697. */
  698. #define juce_malloc(numBytes) malloc (numBytes)
  699. /** This should be used instead of calling calloc directly.
  700. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  701. */
  702. #define juce_calloc(numBytes) calloc (1, numBytes)
  703. /** This should be used instead of calling realloc directly.
  704. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  705. */
  706. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  707. /** This should be used instead of calling free directly.
  708. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  709. */
  710. #define juce_free(location) free (location)
  711. #endif
  712. /** This macro can be added to classes to add extra debugging information to the memory
  713. allocated for them, so you can see the type of objects involved when there's a dump
  714. of leaked objects at program shutdown. (Only works on win32 at the moment).
  715. Note that if you create a class that inherits from a class that uses this macro,
  716. your class must also use the macro, otherwise you'll probably get compile errors
  717. because of ambiguous new operators.
  718. Most of the JUCE classes use it, so see these for examples of where it should go.
  719. */
  720. #ifndef juce_UseDebuggingNewOperator
  721. #define juce_UseDebuggingNewOperator
  722. #endif
  723. #if JUCE_MSVC
  724. /** This is a compiler-independent way of declaring a variable as being thread-local.
  725. E.g.
  726. @code
  727. juce_ThreadLocal int myVariable;
  728. @endcode
  729. */
  730. #define juce_ThreadLocal __declspec(thread)
  731. #else
  732. #define juce_ThreadLocal __thread
  733. #endif
  734. #if JUCE_MINGW
  735. /** This allocator is not defined in mingw gcc. */
  736. #define alloca __builtin_alloca
  737. #endif
  738. /** Clears a block of memory. */
  739. inline void zeromem (void* memory, size_t numBytes) { memset (memory, 0, numBytes); }
  740. /** Clears a reference to a local structure. */
  741. template <typename Type>
  742. inline void zerostruct (Type& structure) { memset (&structure, 0, sizeof (structure)); }
  743. /** A handy function that calls delete on a pointer if it's non-zero, and then sets
  744. the pointer to null.
  745. */
  746. template <typename Type>
  747. inline void deleteAndZero (Type& pointer) { delete pointer; pointer = 0; }
  748. #endif // __JUCE_MEMORY_JUCEHEADER__
  749. /*** End of inlined file: juce_Memory.h ***/
  750. /*** Start of inlined file: juce_MathsFunctions.h ***/
  751. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  752. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  753. /*
  754. This file sets up some handy mathematical typdefs and functions.
  755. */
  756. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  757. /** A platform-independent 8-bit signed integer type. */
  758. typedef signed char int8;
  759. /** A platform-independent 8-bit unsigned integer type. */
  760. typedef unsigned char uint8;
  761. /** A platform-independent 16-bit signed integer type. */
  762. typedef signed short int16;
  763. /** A platform-independent 16-bit unsigned integer type. */
  764. typedef unsigned short uint16;
  765. /** A platform-independent 32-bit signed integer type. */
  766. typedef signed int int32;
  767. /** A platform-independent 32-bit unsigned integer type. */
  768. typedef unsigned int uint32;
  769. #if JUCE_MSVC
  770. /** A platform-independent 64-bit integer type. */
  771. typedef __int64 int64;
  772. /** A platform-independent 64-bit unsigned integer type. */
  773. typedef unsigned __int64 uint64;
  774. /** A platform-independent macro for writing 64-bit literals, needed because
  775. different compilers have different syntaxes for this.
  776. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  777. GCC, or 0x1000000000 for MSVC.
  778. */
  779. #define literal64bit(longLiteral) ((__int64) longLiteral)
  780. #else
  781. /** A platform-independent 64-bit integer type. */
  782. typedef long long int64;
  783. /** A platform-independent 64-bit unsigned integer type. */
  784. typedef unsigned long long uint64;
  785. /** A platform-independent macro for writing 64-bit literals, needed because
  786. different compilers have different syntaxes for this.
  787. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  788. GCC, or 0x1000000000 for MSVC.
  789. */
  790. #define literal64bit(longLiteral) (longLiteral##LL)
  791. #endif
  792. #if JUCE_64BIT
  793. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  794. typedef int64 pointer_sized_int;
  795. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  796. typedef uint64 pointer_sized_uint;
  797. #elif _MSC_VER >= 1300
  798. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  799. typedef _W64 int pointer_sized_int;
  800. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  801. typedef _W64 unsigned int pointer_sized_uint;
  802. #else
  803. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  804. typedef int pointer_sized_int;
  805. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  806. typedef unsigned int pointer_sized_uint;
  807. #endif
  808. /** A platform-independent unicode character type. */
  809. typedef wchar_t juce_wchar;
  810. // Some indispensible min/max functions
  811. /** Returns the larger of two values. */
  812. template <typename Type>
  813. inline Type jmax (const Type a, const Type b) { return (a < b) ? b : a; }
  814. /** Returns the larger of three values. */
  815. template <typename Type>
  816. inline Type jmax (const Type a, const Type b, const Type c) { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  817. /** Returns the larger of four values. */
  818. template <typename Type>
  819. inline Type jmax (const Type a, const Type b, const Type c, const Type d) { return jmax (a, jmax (b, c, d)); }
  820. /** Returns the smaller of two values. */
  821. template <typename Type>
  822. inline Type jmin (const Type a, const Type b) { return (b < a) ? b : a; }
  823. /** Returns the smaller of three values. */
  824. template <typename Type>
  825. inline Type jmin (const Type a, const Type b, const Type c) { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
  826. /** Returns the smaller of four values. */
  827. template <typename Type>
  828. inline Type jmin (const Type a, const Type b, const Type c, const Type d) { return jmin (a, jmin (b, c, d)); }
  829. /** Constrains a value to keep it within a given range.
  830. This will check that the specified value lies between the lower and upper bounds
  831. specified, and if not, will return the nearest value that would be in-range. Effectively,
  832. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  833. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  834. the results will be unpredictable.
  835. @param lowerLimit the minimum value to return
  836. @param upperLimit the maximum value to return
  837. @param valueToConstrain the value to try to return
  838. @returns the closest value to valueToConstrain which lies between lowerLimit
  839. and upperLimit (inclusive)
  840. @see jlimit0To, jmin, jmax
  841. */
  842. template <typename Type>
  843. inline Type jlimit (const Type lowerLimit,
  844. const Type upperLimit,
  845. const Type valueToConstrain) throw()
  846. {
  847. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  848. return (valueToConstrain < lowerLimit) ? lowerLimit
  849. : ((upperLimit < valueToConstrain) ? upperLimit
  850. : valueToConstrain);
  851. }
  852. /** Handy function to swap two values over.
  853. */
  854. template <typename Type>
  855. inline void swapVariables (Type& variable1, Type& variable2)
  856. {
  857. const Type tempVal = variable1;
  858. variable1 = variable2;
  859. variable2 = tempVal;
  860. }
  861. /** Handy function for getting the number of elements in a simple const C array.
  862. E.g.
  863. @code
  864. static int myArray[] = { 1, 2, 3 };
  865. int numElements = numElementsInArray (myArray) // returns 3
  866. @endcode
  867. */
  868. template <typename Type>
  869. inline int numElementsInArray (Type& array) { return static_cast<int> (sizeof (array) / sizeof (array[0])); }
  870. // Some useful maths functions that aren't always present with all compilers and build settings.
  871. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  872. versions of these functions of various platforms and compilers. */
  873. inline double juce_hypot (double a, double b)
  874. {
  875. #if JUCE_WINDOWS
  876. return _hypot (a, b);
  877. #else
  878. return hypot (a, b);
  879. #endif
  880. }
  881. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  882. versions of these functions of various platforms and compilers. */
  883. inline float juce_hypotf (float a, float b) throw()
  884. {
  885. #if JUCE_WINDOWS
  886. return (float) _hypot (a, b);
  887. #else
  888. return hypotf (a, b);
  889. #endif
  890. }
  891. /** 64-bit abs function. */
  892. inline int64 abs64 (const int64 n) throw()
  893. {
  894. return (n >= 0) ? n : -n;
  895. }
  896. /** This templated negate function will negate pointers as well as integers */
  897. template <typename Type>
  898. inline Type juce_negate (Type n) throw()
  899. {
  900. return sizeof (Type) == 1 ? (Type) -(char) n
  901. : (sizeof (Type) == 2 ? (Type) -(short) n
  902. : (sizeof (Type) == 4 ? (Type) -(int) n
  903. : ((Type) -(int64) n)));
  904. }
  905. /** This templated negate function will negate pointers as well as integers */
  906. template <typename Type>
  907. inline Type* juce_negate (Type* n) throw()
  908. {
  909. return (Type*) -(pointer_sized_int) n;
  910. }
  911. /** A predefined value for Pi, at double-precision.
  912. @see float_Pi
  913. */
  914. const double double_Pi = 3.1415926535897932384626433832795;
  915. /** A predefined value for Pi, at sngle-precision.
  916. @see double_Pi
  917. */
  918. const float float_Pi = 3.14159265358979323846f;
  919. /** The isfinite() method seems to vary between platforms, so this is a
  920. platform-independent function for it.
  921. */
  922. template <typename FloatingPointType>
  923. inline bool juce_isfinite (FloatingPointType value)
  924. {
  925. #if JUCE_WINDOWS
  926. return _finite (value);
  927. #else
  928. return std::isfinite (value);
  929. #endif
  930. }
  931. /** Fast floating-point-to-integer conversion.
  932. This is faster than using the normal c++ cast to convert a float to an int, and
  933. it will round the value to the nearest integer, rather than rounding it down
  934. like the normal cast does.
  935. Note that this routine gets its speed at the expense of some accuracy, and when
  936. rounding values whose floating point component is exactly 0.5, odd numbers and
  937. even numbers will be rounded up or down differently.
  938. */
  939. template <typename FloatType>
  940. inline int roundToInt (const FloatType value) throw()
  941. {
  942. union { int asInt[2]; double asDouble; } n;
  943. n.asDouble = ((double) value) + 6755399441055744.0;
  944. #if JUCE_BIG_ENDIAN
  945. return n.asInt [1];
  946. #else
  947. return n.asInt [0];
  948. #endif
  949. }
  950. /** Fast floating-point-to-integer conversion.
  951. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  952. fine for values above zero, but negative numbers are rounded the wrong way.
  953. */
  954. inline int roundToIntAccurate (const double value) throw()
  955. {
  956. return roundToInt (value + 1.5e-8);
  957. }
  958. /** Fast floating-point-to-integer conversion.
  959. This is faster than using the normal c++ cast to convert a double to an int, and
  960. it will round the value to the nearest integer, rather than rounding it down
  961. like the normal cast does.
  962. Note that this routine gets its speed at the expense of some accuracy, and when
  963. rounding values whose floating point component is exactly 0.5, odd numbers and
  964. even numbers will be rounded up or down differently. For a more accurate conversion,
  965. see roundDoubleToIntAccurate().
  966. */
  967. inline int roundDoubleToInt (const double value) throw()
  968. {
  969. return roundToInt (value);
  970. }
  971. /** Fast floating-point-to-integer conversion.
  972. This is faster than using the normal c++ cast to convert a float to an int, and
  973. it will round the value to the nearest integer, rather than rounding it down
  974. like the normal cast does.
  975. Note that this routine gets its speed at the expense of some accuracy, and when
  976. rounding values whose floating point component is exactly 0.5, odd numbers and
  977. even numbers will be rounded up or down differently.
  978. */
  979. inline int roundFloatToInt (const float value) throw()
  980. {
  981. return roundToInt (value);
  982. }
  983. /** This namespace contains a few template classes for helping work out class type variations.
  984. */
  985. namespace TypeHelpers
  986. {
  987. /** The ParameterType struct is used to find the best type to use when passing some kind
  988. of object as a parameter.
  989. Of course, this is only likely to be useful in certain esoteric template situations.
  990. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  991. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  992. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  993. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  994. pass-by-value, but passing objects as a const reference, to avoid copying.
  995. */
  996. #if defined (_MSC_VER) && _MSC_VER <= 1400
  997. #define PARAMETER_TYPE(a) a
  998. #else
  999. template <typename Type> struct ParameterType { typedef const Type& type; };
  1000. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  1001. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  1002. template <> struct ParameterType <char> { typedef char type; };
  1003. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  1004. template <> struct ParameterType <short> { typedef short type; };
  1005. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  1006. template <> struct ParameterType <int> { typedef int type; };
  1007. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  1008. template <> struct ParameterType <long> { typedef long type; };
  1009. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  1010. template <> struct ParameterType <int64> { typedef int64 type; };
  1011. template <> struct ParameterType <uint64> { typedef uint64 type; };
  1012. template <> struct ParameterType <bool> { typedef bool type; };
  1013. template <> struct ParameterType <float> { typedef float type; };
  1014. template <> struct ParameterType <double> { typedef double type; };
  1015. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  1016. #endif
  1017. }
  1018. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  1019. /*** End of inlined file: juce_MathsFunctions.h ***/
  1020. /*** Start of inlined file: juce_ByteOrder.h ***/
  1021. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  1022. #define __JUCE_BYTEORDER_JUCEHEADER__
  1023. /** Contains static methods for converting the byte order between different
  1024. endiannesses.
  1025. */
  1026. class JUCE_API ByteOrder
  1027. {
  1028. public:
  1029. /** Swaps the upper and lower bytes of a 16-bit integer. */
  1030. static uint16 swap (uint16 value);
  1031. /** Reverses the order of the 4 bytes in a 32-bit integer. */
  1032. static uint32 swap (uint32 value);
  1033. /** Reverses the order of the 8 bytes in a 64-bit integer. */
  1034. static uint64 swap (uint64 value);
  1035. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  1036. static uint16 swapIfBigEndian (uint16 value);
  1037. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  1038. static uint32 swapIfBigEndian (uint32 value);
  1039. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  1040. static uint64 swapIfBigEndian (uint64 value);
  1041. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  1042. static uint16 swapIfLittleEndian (uint16 value);
  1043. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  1044. static uint32 swapIfLittleEndian (uint32 value);
  1045. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  1046. static uint64 swapIfLittleEndian (uint64 value);
  1047. /** Turns 4 bytes into a little-endian integer. */
  1048. static uint32 littleEndianInt (const void* bytes);
  1049. /** Turns 2 bytes into a little-endian integer. */
  1050. static uint16 littleEndianShort (const void* bytes);
  1051. /** Turns 4 bytes into a big-endian integer. */
  1052. static uint32 bigEndianInt (const void* bytes);
  1053. /** Turns 2 bytes into a big-endian integer. */
  1054. static uint16 bigEndianShort (const void* bytes);
  1055. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1056. static int littleEndian24Bit (const char* bytes);
  1057. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1058. static int bigEndian24Bit (const char* bytes);
  1059. /** Copies a 24-bit number to 3 little-endian bytes. */
  1060. static void littleEndian24BitToChars (int value, char* destBytes);
  1061. /** Copies a 24-bit number to 3 big-endian bytes. */
  1062. static void bigEndian24BitToChars (int value, char* destBytes);
  1063. /** Returns true if the current CPU is big-endian. */
  1064. static bool isBigEndian();
  1065. private:
  1066. ByteOrder();
  1067. ByteOrder (const ByteOrder&);
  1068. ByteOrder& operator= (const ByteOrder&);
  1069. };
  1070. #if JUCE_USE_INTRINSICS
  1071. #pragma intrinsic (_byteswap_ulong)
  1072. #endif
  1073. inline uint16 ByteOrder::swap (uint16 n)
  1074. {
  1075. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  1076. return static_cast <uint16> (_byteswap_ushort (n));
  1077. #else
  1078. return static_cast <uint16> ((n << 8) | (n >> 8));
  1079. #endif
  1080. }
  1081. inline uint32 ByteOrder::swap (uint32 n)
  1082. {
  1083. #if JUCE_MAC || JUCE_IPHONE
  1084. return OSSwapInt32 (n);
  1085. #elif JUCE_GCC
  1086. asm("bswap %%eax" : "=a"(n) : "a"(n));
  1087. return n;
  1088. #elif JUCE_USE_INTRINSICS
  1089. return _byteswap_ulong (n);
  1090. #else
  1091. __asm {
  1092. mov eax, n
  1093. bswap eax
  1094. mov n, eax
  1095. }
  1096. return n;
  1097. #endif
  1098. }
  1099. inline uint64 ByteOrder::swap (uint64 value)
  1100. {
  1101. #if JUCE_MAC || JUCE_IPHONE
  1102. return OSSwapInt64 (value);
  1103. #elif JUCE_USE_INTRINSICS
  1104. return _byteswap_uint64 (value);
  1105. #else
  1106. return (((int64) swap ((uint32) value)) << 32) | swap ((uint32) (value >> 32));
  1107. #endif
  1108. }
  1109. #if JUCE_LITTLE_ENDIAN
  1110. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return v; }
  1111. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return v; }
  1112. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return v; }
  1113. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return swap (v); }
  1114. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return swap (v); }
  1115. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return swap (v); }
  1116. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1117. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1118. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1119. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1120. inline bool ByteOrder::isBigEndian() { return false; }
  1121. #else
  1122. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return swap (v); }
  1123. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return swap (v); }
  1124. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return swap (v); }
  1125. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return v; }
  1126. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return v; }
  1127. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return v; }
  1128. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1129. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1130. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1131. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1132. inline bool ByteOrder::isBigEndian() { return true; }
  1133. #endif
  1134. inline int ByteOrder::littleEndian24Bit (const char* const bytes) { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  1135. inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  1136. inline void ByteOrder::littleEndian24BitToChars (const int value, char* const destBytes) { destBytes[0] = (char)(value & 0xff); destBytes[1] = (char)((value >> 8) & 0xff); destBytes[2] = (char)((value >> 16) & 0xff); }
  1137. inline void ByteOrder::bigEndian24BitToChars (const int value, char* const destBytes) { destBytes[0] = (char)((value >> 16) & 0xff); destBytes[1] = (char)((value >> 8) & 0xff); destBytes[2] = (char)(value & 0xff); }
  1138. #endif // __JUCE_BYTEORDER_JUCEHEADER__
  1139. /*** End of inlined file: juce_ByteOrder.h ***/
  1140. /*** Start of inlined file: juce_Logger.h ***/
  1141. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1142. #define __JUCE_LOGGER_JUCEHEADER__
  1143. /*** Start of inlined file: juce_String.h ***/
  1144. #ifndef __JUCE_STRING_JUCEHEADER__
  1145. #define __JUCE_STRING_JUCEHEADER__
  1146. /*** Start of inlined file: juce_CharacterFunctions.h ***/
  1147. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1148. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1149. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1150. typedef juce_wchar tchar;
  1151. #if ! JUCE_DONT_DEFINE_MACROS
  1152. /** The 'T' macro allows a literal string to be compiled as unicode.
  1153. If you write your string literals in the form T("xyz"), it will be compiled as L"xyz"
  1154. or "xyz", depending on which representation is best for the String class to work with.
  1155. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1156. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1157. the juce/src directory) to avoid defining this macro. See the comments in
  1158. juce_withoutMacros.h for more info.
  1159. */
  1160. #define T(stringLiteral) JUCE_T(stringLiteral)
  1161. #endif
  1162. /**
  1163. A set of methods for manipulating characters and character strings, with
  1164. duplicate methods to handle 8-bit and unicode characters.
  1165. These are defined as wrappers around the basic C string handlers, to provide
  1166. a clean, cross-platform layer, (because various platforms differ in the
  1167. range of C library calls that they provide).
  1168. @see String
  1169. */
  1170. class JUCE_API CharacterFunctions
  1171. {
  1172. public:
  1173. static int length (const char* const s) throw();
  1174. static int length (const juce_wchar* const s) throw();
  1175. static void copy (char* dest, const char* src, const int maxBytes) throw();
  1176. static void copy (juce_wchar* dest, const juce_wchar* src, const int maxChars) throw();
  1177. static void copy (juce_wchar* dest, const char* src, const int maxChars) throw();
  1178. static void copy (char* dest, const juce_wchar* src, const int maxBytes) throw();
  1179. static int bytesRequiredForCopy (const juce_wchar* src) throw();
  1180. static void append (char* dest, const char* src) throw();
  1181. static void append (juce_wchar* dest, const juce_wchar* src) throw();
  1182. static int compare (const char* const s1, const char* const s2) throw();
  1183. static int compare (const juce_wchar* s1, const juce_wchar* s2) throw();
  1184. static int compare (const juce_wchar* s1, const char* s2) throw();
  1185. static int compare (const char* s1, const juce_wchar* s2) throw();
  1186. static int compare (const char* const s1, const char* const s2, const int maxChars) throw();
  1187. static int compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1188. static int compareIgnoreCase (const char* const s1, const char* const s2) throw();
  1189. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw();
  1190. static int compareIgnoreCase (const juce_wchar* s1, const char* s2) throw();
  1191. static int compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw();
  1192. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1193. static const char* find (const char* const haystack, const char* const needle) throw();
  1194. static const juce_wchar* find (const juce_wchar* haystack, const juce_wchar* const needle) throw();
  1195. static int indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw();
  1196. static int indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw();
  1197. static int indexOfCharFast (const char* const haystack, const char needle) throw();
  1198. static int indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw();
  1199. static int getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw();
  1200. static int getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw();
  1201. static int ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw();
  1202. static int ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw();
  1203. static int getIntValue (const char* const s) throw();
  1204. static int getIntValue (const juce_wchar* s) throw();
  1205. static int64 getInt64Value (const char* s) throw();
  1206. static int64 getInt64Value (const juce_wchar* s) throw();
  1207. static double getDoubleValue (const char* const s) throw();
  1208. static double getDoubleValue (const juce_wchar* const s) throw();
  1209. static char toUpperCase (const char character) throw();
  1210. static juce_wchar toUpperCase (const juce_wchar character) throw();
  1211. static void toUpperCase (char* s) throw();
  1212. static void toUpperCase (juce_wchar* s) throw();
  1213. static bool isUpperCase (const char character) throw();
  1214. static bool isUpperCase (const juce_wchar character) throw();
  1215. static char toLowerCase (const char character) throw();
  1216. static juce_wchar toLowerCase (const juce_wchar character) throw();
  1217. static void toLowerCase (char* s) throw();
  1218. static void toLowerCase (juce_wchar* s) throw();
  1219. static bool isLowerCase (const char character) throw();
  1220. static bool isLowerCase (const juce_wchar character) throw();
  1221. static bool isWhitespace (const char character) throw();
  1222. static bool isWhitespace (const juce_wchar character) throw();
  1223. static bool isDigit (const char character) throw();
  1224. static bool isDigit (const juce_wchar character) throw();
  1225. static bool isLetter (const char character) throw();
  1226. static bool isLetter (const juce_wchar character) throw();
  1227. static bool isLetterOrDigit (const char character) throw();
  1228. static bool isLetterOrDigit (const juce_wchar character) throw();
  1229. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legel
  1230. hex digit.
  1231. */
  1232. static int getHexDigitValue (const juce_wchar digit) throw();
  1233. };
  1234. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1235. /*** End of inlined file: juce_CharacterFunctions.h ***/
  1236. class OutputStream;
  1237. /**
  1238. The JUCE String class!
  1239. Using a reference-counted internal representation, these strings are fast
  1240. and efficient, and there are methods to do just about any operation you'll ever
  1241. dream of.
  1242. @see StringArray, StringPairArray
  1243. */
  1244. class JUCE_API String
  1245. {
  1246. public:
  1247. /** Creates an empty string.
  1248. @see empty
  1249. */
  1250. String() throw();
  1251. /** Creates a copy of another string. */
  1252. String (const String& other) throw();
  1253. /** Creates a string from a zero-terminated text string.
  1254. The string is assumed to be stored in the default system encoding.
  1255. */
  1256. String (const char* text);
  1257. /** Creates a string from an string of characters.
  1258. This will use up the the first maxChars characters of the string (or
  1259. less if the string is actually shorter)
  1260. */
  1261. String (const char* text, size_t maxChars);
  1262. /** Creates a string from a zero-terminated unicode text string. */
  1263. String (const juce_wchar* unicodeText);
  1264. /** Creates a string from a unicode text string.
  1265. This will use up the the first maxChars characters of the string (or
  1266. less if the string is actually shorter)
  1267. */
  1268. String (const juce_wchar* unicodeText, size_t maxChars);
  1269. /** Creates a string from a single character. */
  1270. static const String charToString (juce_wchar character);
  1271. /** Destructor. */
  1272. ~String() throw();
  1273. /** This is an empty string that can be used whenever one is needed.
  1274. It's better to use this than String() because it explains what's going on
  1275. and is more efficient.
  1276. */
  1277. static const String empty;
  1278. /** Generates a probably-unique 32-bit hashcode from this string. */
  1279. int hashCode() const throw();
  1280. /** Generates a probably-unique 64-bit hashcode from this string. */
  1281. int64 hashCode64() const throw();
  1282. /** Returns the number of characters in the string. */
  1283. int length() const throw();
  1284. // Assignment and concatenation operators..
  1285. /** Replaces this string's contents with another string. */
  1286. String& operator= (const String& other) throw();
  1287. /** Appends another string at the end of this one. */
  1288. String& operator+= (const juce_wchar* textToAppend);
  1289. /** Appends another string at the end of this one. */
  1290. String& operator+= (const String& stringToAppend);
  1291. /** Appends a character at the end of this string. */
  1292. String& operator+= (char characterToAppend);
  1293. /** Appends a character at the end of this string. */
  1294. String& operator+= (juce_wchar characterToAppend);
  1295. /** Appends a decimal number at the end of this string. */
  1296. String& operator+= (int numberToAppend);
  1297. /** Appends a decimal number at the end of this string. */
  1298. String& operator+= (unsigned int numberToAppend);
  1299. /** Appends a string at the end of this one.
  1300. @param textToAppend the string to add
  1301. @param maxCharsToTake the maximum number of characters to take from the string passed in
  1302. */
  1303. void append (const juce_wchar* textToAppend, int maxCharsToTake);
  1304. // Comparison methods..
  1305. /** Returns true if the string contains no characters.
  1306. Note that there's also an isNotEmpty() method to help write readable code.
  1307. @see containsNonWhitespaceChars()
  1308. */
  1309. inline bool isEmpty() const throw() { return text[0] == 0; }
  1310. /** Returns true if the string contains at least one character.
  1311. Note that there's also an isEmpty() method to help write readable code.
  1312. @see containsNonWhitespaceChars()
  1313. */
  1314. inline bool isNotEmpty() const throw() { return text[0] != 0; }
  1315. /** Case-insensitive comparison with another string. */
  1316. bool equalsIgnoreCase (const String& other) const throw();
  1317. /** Case-insensitive comparison with another string. */
  1318. bool equalsIgnoreCase (const juce_wchar* other) const throw();
  1319. /** Case-insensitive comparison with another string. */
  1320. bool equalsIgnoreCase (const char* other) const throw();
  1321. /** Case-sensitive comparison with another string.
  1322. @returns 0 if the two strings are identical; negative if this string
  1323. comes before the other one alphabetically, or positive if it
  1324. comes after it.
  1325. */
  1326. int compare (const String& other) const throw();
  1327. /** Case-sensitive comparison with another string.
  1328. @returns 0 if the two strings are identical; negative if this string
  1329. comes before the other one alphabetically, or positive if it
  1330. comes after it.
  1331. */
  1332. int compare (const char* other) const throw();
  1333. /** Case-sensitive comparison with another string.
  1334. @returns 0 if the two strings are identical; negative if this string
  1335. comes before the other one alphabetically, or positive if it
  1336. comes after it.
  1337. */
  1338. int compare (const juce_wchar* other) const throw();
  1339. /** Case-insensitive comparison with another string.
  1340. @returns 0 if the two strings are identical; negative if this string
  1341. comes before the other one alphabetically, or positive if it
  1342. comes after it.
  1343. */
  1344. int compareIgnoreCase (const String& other) const throw();
  1345. /** Lexicographic comparison with another string.
  1346. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  1347. characters, making it good for sorting human-readable strings.
  1348. @returns 0 if the two strings are identical; negative if this string
  1349. comes before the other one alphabetically, or positive if it
  1350. comes after it.
  1351. */
  1352. int compareLexicographically (const String& other) const throw();
  1353. /** Tests whether the string begins with another string.
  1354. Uses a case-sensitive comparison.
  1355. */
  1356. bool startsWith (const String& text) const throw();
  1357. /** Tests whether the string begins with a particular character.
  1358. Uses a case-sensitive comparison.
  1359. */
  1360. bool startsWithChar (juce_wchar character) const throw();
  1361. /** Tests whether the string begins with another string.
  1362. Uses a case-insensitive comparison.
  1363. */
  1364. bool startsWithIgnoreCase (const String& text) const throw();
  1365. /** Tests whether the string ends with another string.
  1366. Uses a case-sensitive comparison.
  1367. */
  1368. bool endsWith (const String& text) const throw();
  1369. /** Tests whether the string ends with a particular character.
  1370. Uses a case-sensitive comparison.
  1371. */
  1372. bool endsWithChar (juce_wchar character) const throw();
  1373. /** Tests whether the string ends with another string.
  1374. Uses a case-insensitive comparison.
  1375. */
  1376. bool endsWithIgnoreCase (const String& text) const throw();
  1377. /** Tests whether the string contains another substring.
  1378. Uses a case-sensitive comparison.
  1379. */
  1380. bool contains (const String& text) const throw();
  1381. /** Tests whether the string contains a particular character.
  1382. Uses a case-sensitive comparison.
  1383. */
  1384. bool containsChar (juce_wchar character) const throw();
  1385. /** Tests whether the string contains another substring.
  1386. Uses a case-insensitive comparison.
  1387. */
  1388. bool containsIgnoreCase (const String& text) const throw();
  1389. /** Tests whether the string contains another substring as a distict word.
  1390. @returns true if the string contains this word, surrounded by
  1391. non-alphanumeric characters
  1392. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1393. */
  1394. bool containsWholeWord (const String& wordToLookFor) const throw();
  1395. /** Tests whether the string contains another substring as a distict word.
  1396. @returns true if the string contains this word, surrounded by
  1397. non-alphanumeric characters
  1398. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1399. */
  1400. bool containsWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  1401. /** Finds an instance of another substring if it exists as a distict word.
  1402. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1403. then this will return the index of the start of the substring. If it isn't
  1404. found, then it will return -1
  1405. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1406. */
  1407. int indexOfWholeWord (const String& wordToLookFor) const throw();
  1408. /** Finds an instance of another substring if it exists as a distict word.
  1409. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1410. then this will return the index of the start of the substring. If it isn't
  1411. found, then it will return -1
  1412. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1413. */
  1414. int indexOfWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  1415. /** Looks for any of a set of characters in the string.
  1416. Uses a case-sensitive comparison.
  1417. @returns true if the string contains any of the characters from
  1418. the string that is passed in.
  1419. */
  1420. bool containsAnyOf (const String& charactersItMightContain) const throw();
  1421. /** Looks for a set of characters in the string.
  1422. Uses a case-sensitive comparison.
  1423. @returns true if the all the characters in the string are also found in the
  1424. string that is passed in.
  1425. */
  1426. bool containsOnly (const String& charactersItMightContain) const throw();
  1427. /** Returns true if this string contains any non-whitespace characters.
  1428. This will return false if the string contains only whitespace characters, or
  1429. if it's empty.
  1430. It is equivalent to calling "myString.trim().isNotEmpty()".
  1431. */
  1432. bool containsNonWhitespaceChars() const throw();
  1433. /** Returns true if the string matches this simple wildcard expression.
  1434. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  1435. This isn't a full-blown regex though! The only wildcard characters supported
  1436. are "*" and "?". It's mainly intended for filename pattern matching.
  1437. */
  1438. bool matchesWildcard (const String& wildcard, bool ignoreCase) const throw();
  1439. // Substring location methods..
  1440. /** Searches for a character inside this string.
  1441. Uses a case-sensitive comparison.
  1442. @returns the index of the first occurrence of the character in this
  1443. string, or -1 if it's not found.
  1444. */
  1445. int indexOfChar (juce_wchar characterToLookFor) const throw();
  1446. /** Searches for a character inside this string.
  1447. Uses a case-sensitive comparison.
  1448. @param startIndex the index from which the search should proceed
  1449. @param characterToLookFor the character to look for
  1450. @returns the index of the first occurrence of the character in this
  1451. string, or -1 if it's not found.
  1452. */
  1453. int indexOfChar (int startIndex, juce_wchar characterToLookFor) const throw();
  1454. /** Returns the index of the first character that matches one of the characters
  1455. passed-in to this method.
  1456. This scans the string, beginning from the startIndex supplied, and if it finds
  1457. a character that appears in the string charactersToLookFor, it returns its index.
  1458. If none of these characters are found, it returns -1.
  1459. If ignoreCase is true, the comparison will be case-insensitive.
  1460. @see indexOfChar, lastIndexOfAnyOf
  1461. */
  1462. int indexOfAnyOf (const String& charactersToLookFor,
  1463. int startIndex = 0,
  1464. bool ignoreCase = false) const throw();
  1465. /** Searches for a substring within this string.
  1466. Uses a case-sensitive comparison.
  1467. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1468. */
  1469. int indexOf (const String& text) const throw();
  1470. /** Searches for a substring within this string.
  1471. Uses a case-sensitive comparison.
  1472. @param startIndex the index from which the search should proceed
  1473. @param textToLookFor the string to search for
  1474. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1475. */
  1476. int indexOf (int startIndex,
  1477. const String& textToLookFor) const throw();
  1478. /** Searches for a substring within this string.
  1479. Uses a case-insensitive comparison.
  1480. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1481. */
  1482. int indexOfIgnoreCase (const String& textToLookFor) const throw();
  1483. /** Searches for a substring within this string.
  1484. Uses a case-insensitive comparison.
  1485. @param startIndex the index from which the search should proceed
  1486. @param textToLookFor the string to search for
  1487. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1488. */
  1489. int indexOfIgnoreCase (int startIndex,
  1490. const String& textToLookFor) const throw();
  1491. /** Searches for a character inside this string (working backwards from the end of the string).
  1492. Uses a case-sensitive comparison.
  1493. @returns the index of the last occurrence of the character in this
  1494. string, or -1 if it's not found.
  1495. */
  1496. int lastIndexOfChar (juce_wchar character) const throw();
  1497. /** Searches for a substring inside this string (working backwards from the end of the string).
  1498. Uses a case-sensitive comparison.
  1499. @returns the index of the start of the last occurrence of the
  1500. substring within this string, or -1 if it's not found.
  1501. */
  1502. int lastIndexOf (const String& textToLookFor) const throw();
  1503. /** Searches for a substring inside this string (working backwards from the end of the string).
  1504. Uses a case-insensitive comparison.
  1505. @returns the index of the start of the last occurrence of the
  1506. substring within this string, or -1 if it's not found.
  1507. */
  1508. int lastIndexOfIgnoreCase (const String& textToLookFor) const throw();
  1509. /** Returns the index of the last character in this string that matches one of the
  1510. characters passed-in to this method.
  1511. This scans the string backwards, starting from its end, and if it finds
  1512. a character that appears in the string charactersToLookFor, it returns its index.
  1513. If none of these characters are found, it returns -1.
  1514. If ignoreCase is true, the comparison will be case-insensitive.
  1515. @see lastIndexOf, indexOfAnyOf
  1516. */
  1517. int lastIndexOfAnyOf (const String& charactersToLookFor,
  1518. bool ignoreCase = false) const throw();
  1519. // Substring extraction and manipulation methods..
  1520. /** Returns the character at this index in the string.
  1521. No checks are made to see if the index is within a valid range, so be careful!
  1522. */
  1523. inline const juce_wchar& operator[] (int index) const throw() { jassert (((unsigned int) index) <= (unsigned int) length()); return text [index]; }
  1524. /** Returns a character from the string such that it can also be altered.
  1525. This can be used as a way of easily changing characters in the string.
  1526. Note that the index passed-in is not checked to see whether it's in-range, so
  1527. be careful when using this.
  1528. */
  1529. juce_wchar& operator[] (int index);
  1530. /** Returns the final character of the string.
  1531. If the string is empty this will return 0.
  1532. */
  1533. juce_wchar getLastCharacter() const throw();
  1534. /** Returns a subsection of the string.
  1535. If the range specified is beyond the limits of the string, as much as
  1536. possible is returned.
  1537. @param startIndex the index of the start of the substring needed
  1538. @param endIndex all characters from startIndex up to (but not including)
  1539. this index are returned
  1540. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  1541. */
  1542. const String substring (int startIndex, int endIndex) const;
  1543. /** Returns a section of the string, starting from a given position.
  1544. @param startIndex the first character to include. If this is beyond the end
  1545. of the string, an empty string is returned. If it is zero or
  1546. less, the whole string is returned.
  1547. @returns the substring from startIndex up to the end of the string
  1548. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  1549. */
  1550. const String substring (int startIndex) const;
  1551. /** Returns a version of this string with a number of characters removed
  1552. from the end.
  1553. @param numberToDrop the number of characters to drop from the end of the
  1554. string. If this is greater than the length of the string,
  1555. an empty string will be returned. If zero or less, the
  1556. original string will be returned.
  1557. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  1558. */
  1559. const String dropLastCharacters (int numberToDrop) const;
  1560. /** Returns a number of characters from the end of the string.
  1561. This returns the last numCharacters characters from the end of the string. If the
  1562. string is shorter than numCharacters, the whole string is returned.
  1563. @see substring, dropLastCharacters, getLastCharacter
  1564. */
  1565. const String getLastCharacters (int numCharacters) const;
  1566. /** Returns a section of the string starting from a given substring.
  1567. This will search for the first occurrence of the given substring, and
  1568. return the section of the string starting from the point where this is
  1569. found (optionally not including the substring itself).
  1570. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  1571. fromFirstOccurrenceOf ("34", false) would return "56".
  1572. If the substring isn't found, the method will return an empty string.
  1573. If ignoreCase is true, the comparison will be case-insensitive.
  1574. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  1575. */
  1576. const String fromFirstOccurrenceOf (const String& substringToStartFrom,
  1577. bool includeSubStringInResult,
  1578. bool ignoreCase) const;
  1579. /** Returns a section of the string starting from the last occurrence of a given substring.
  1580. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  1581. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  1582. return the whole of the original string.
  1583. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  1584. */
  1585. const String fromLastOccurrenceOf (const String& substringToFind,
  1586. bool includeSubStringInResult,
  1587. bool ignoreCase) const;
  1588. /** Returns the start of this string, up to the first occurrence of a substring.
  1589. This will search for the first occurrence of a given substring, and then
  1590. return a copy of the string, up to the position of this substring,
  1591. optionally including or excluding the substring itself in the result.
  1592. e.g. for the string "123456", upTo ("34", false) would return "12", and
  1593. upTo ("34", true) would return "1234".
  1594. If the substring isn't found, this will return the whole of the original string.
  1595. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  1596. */
  1597. const String upToFirstOccurrenceOf (const String& substringToEndWith,
  1598. bool includeSubStringInResult,
  1599. bool ignoreCase) const;
  1600. /** Returns the start of this string, up to the last occurrence of a substring.
  1601. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  1602. If the substring isn't found, this will return an empty string.
  1603. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  1604. */
  1605. const String upToLastOccurrenceOf (const String& substringToFind,
  1606. bool includeSubStringInResult,
  1607. bool ignoreCase) const;
  1608. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  1609. const String trim() const;
  1610. /** Returns a copy of this string with any whitespace characters removed from the start. */
  1611. const String trimStart() const;
  1612. /** Returns a copy of this string with any whitespace characters removed from the end. */
  1613. const String trimEnd() const;
  1614. /** Returns a copy of this string, having removed a specified set of characters from its start.
  1615. Characters are removed from the start of the string until it finds one that is not in the
  1616. specified set, and then it stops.
  1617. @param charactersToTrim the set of characters to remove.
  1618. @see trim, trimStart, trimCharactersAtEnd
  1619. */
  1620. const String trimCharactersAtStart (const String& charactersToTrim) const;
  1621. /** Returns a copy of this string, having removed a specified set of characters from its end.
  1622. Characters are removed from the end of the string until it finds one that is not in the
  1623. specified set, and then it stops.
  1624. @param charactersToTrim the set of characters to remove.
  1625. @see trim, trimEnd, trimCharactersAtStart
  1626. */
  1627. const String trimCharactersAtEnd (const String& charactersToTrim) const;
  1628. /** Returns an upper-case version of this string. */
  1629. const String toUpperCase() const;
  1630. /** Returns an lower-case version of this string. */
  1631. const String toLowerCase() const;
  1632. /** Replaces a sub-section of the string with another string.
  1633. This will return a copy of this string, with a set of characters
  1634. from startIndex to startIndex + numCharsToReplace removed, and with
  1635. a new string inserted in their place.
  1636. Note that this is a const method, and won't alter the string itself.
  1637. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  1638. it will be constrained to a valid range.
  1639. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  1640. characters will be taken out.
  1641. @param stringToInsert the new string to insert at startIndex after the characters have been
  1642. removed.
  1643. */
  1644. const String replaceSection (int startIndex,
  1645. int numCharactersToReplace,
  1646. const String& stringToInsert) const;
  1647. /** Replaces all occurrences of a substring with another string.
  1648. Returns a copy of this string, with any occurrences of stringToReplace
  1649. swapped for stringToInsertInstead.
  1650. Note that this is a const method, and won't alter the string itself.
  1651. */
  1652. const String replace (const String& stringToReplace,
  1653. const String& stringToInsertInstead,
  1654. bool ignoreCase = false) const;
  1655. /** Returns a string with all occurrences of a character replaced with a different one. */
  1656. const String replaceCharacter (juce_wchar characterToReplace,
  1657. juce_wchar characterToInsertInstead) const;
  1658. /** Replaces a set of characters with another set.
  1659. Returns a string in which each character from charactersToReplace has been replaced
  1660. by the character at the equivalent position in newCharacters (so the two strings
  1661. passed in must be the same length).
  1662. e.g. replaceCharacters ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  1663. Note that this is a const method, and won't affect the string itself.
  1664. */
  1665. const String replaceCharacters (const String& charactersToReplace,
  1666. const String& charactersToInsertInstead) const;
  1667. /** Returns a version of this string that only retains a fixed set of characters.
  1668. This will return a copy of this string, omitting any characters which are not
  1669. found in the string passed-in.
  1670. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  1671. Note that this is a const method, and won't alter the string itself.
  1672. */
  1673. const String retainCharacters (const String& charactersToRetain) const;
  1674. /** Returns a version of this string with a set of characters removed.
  1675. This will return a copy of this string, omitting any characters which are
  1676. found in the string passed-in.
  1677. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  1678. Note that this is a const method, and won't alter the string itself.
  1679. */
  1680. const String removeCharacters (const String& charactersToRemove) const;
  1681. /** Returns a section from the start of the string that only contains a certain set of characters.
  1682. This returns the leftmost section of the string, up to (and not including) the
  1683. first character that doesn't appear in the string passed in.
  1684. */
  1685. const String initialSectionContainingOnly (const String& permittedCharacters) const;
  1686. /** Returns a section from the start of the string that only contains a certain set of characters.
  1687. This returns the leftmost section of the string, up to (and not including) the
  1688. first character that occurs in the string passed in.
  1689. */
  1690. const String initialSectionNotContaining (const String& charactersToStopAt) const;
  1691. /** Checks whether the string might be in quotation marks.
  1692. @returns true if the string begins with a quote character (either a double or single quote).
  1693. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  1694. @see unquoted, quoted
  1695. */
  1696. bool isQuotedString() const;
  1697. /** Removes quotation marks from around the string, (if there are any).
  1698. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  1699. at the ends of the string are not affected. If there aren't any quotes, the original string
  1700. is returned.
  1701. Note that this is a const method, and won't alter the string itself.
  1702. @see isQuotedString, quoted
  1703. */
  1704. const String unquoted() const;
  1705. /** Adds quotation marks around a string.
  1706. This will return a copy of the string with a quote at the start and end, (but won't
  1707. add the quote if there's already one there, so it's safe to call this on strings that
  1708. may already have quotes around them).
  1709. Note that this is a const method, and won't alter the string itself.
  1710. @param quoteCharacter the character to add at the start and end
  1711. @see isQuotedString, unquoted
  1712. */
  1713. const String quoted (juce_wchar quoteCharacter = '"') const;
  1714. /** Creates a string which is a version of a string repeated and joined together.
  1715. @param stringToRepeat the string to repeat
  1716. @param numberOfTimesToRepeat how many times to repeat it
  1717. */
  1718. static const String repeatedString (const String& stringToRepeat,
  1719. int numberOfTimesToRepeat);
  1720. /** Returns a copy of this string with the specified character repeatedly added to its
  1721. beginning until the total length is at least the minimum length specified.
  1722. */
  1723. const String paddedLeft (juce_wchar padCharacter, int minimumLength) const;
  1724. /** Returns a copy of this string with the specified character repeatedly added to its
  1725. end until the total length is at least the minimum length specified.
  1726. */
  1727. const String paddedRight (juce_wchar padCharacter, int minimumLength) const;
  1728. /** Creates a string from data in an unknown format.
  1729. This looks at some binary data and tries to guess whether it's Unicode
  1730. or 8-bit characters, then returns a string that represents it correctly.
  1731. Should be able to handle Unicode endianness correctly, by looking at
  1732. the first two bytes.
  1733. */
  1734. static const String createStringFromData (const void* data, int size);
  1735. /** Creates a String from a printf-style parameter list.
  1736. I don't like this method. I don't use it myself, and I recommend avoiding it and
  1737. using the operator<< methods or pretty much anything else instead. It's only provided
  1738. here because of the popular unrest that was stirred-up when I tried to remove it...
  1739. If you're really determined to use it, at least make sure that you never, ever,
  1740. pass any String objects to it as parameters.
  1741. */
  1742. static const String formatted (const juce_wchar* formatString, ... );
  1743. // Numeric conversions..
  1744. /** Creates a string containing this signed 32-bit integer as a decimal number.
  1745. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1746. */
  1747. explicit String (int decimalInteger);
  1748. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  1749. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1750. */
  1751. explicit String (unsigned int decimalInteger);
  1752. /** Creates a string containing this signed 16-bit integer as a decimal number.
  1753. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1754. */
  1755. explicit String (short decimalInteger);
  1756. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  1757. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1758. */
  1759. explicit String (unsigned short decimalInteger);
  1760. /** Creates a string containing this signed 64-bit integer as a decimal number.
  1761. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1762. */
  1763. explicit String (int64 largeIntegerValue);
  1764. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  1765. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1766. */
  1767. explicit String (uint64 largeIntegerValue);
  1768. /** Creates a string representing this floating-point number.
  1769. @param floatValue the value to convert to a string
  1770. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1771. decimal places, and will not use exponent notation. If 0 or
  1772. less, it will use exponent notation if necessary.
  1773. @see getDoubleValue, getIntValue
  1774. */
  1775. explicit String (float floatValue,
  1776. int numberOfDecimalPlaces = 0);
  1777. /** Creates a string representing this floating-point number.
  1778. @param doubleValue the value to convert to a string
  1779. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1780. decimal places, and will not use exponent notation. If 0 or
  1781. less, it will use exponent notation if necessary.
  1782. @see getFloatValue, getIntValue
  1783. */
  1784. explicit String (double doubleValue,
  1785. int numberOfDecimalPlaces = 0);
  1786. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  1787. @returns the value of the string as a 32 bit signed base-10 integer.
  1788. @see getTrailingIntValue, getHexValue32, getHexValue64
  1789. */
  1790. int getIntValue() const throw();
  1791. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  1792. @returns the value of the string as a 64 bit signed base-10 integer.
  1793. */
  1794. int64 getLargeIntValue() const throw();
  1795. /** Parses a decimal number from the end of the string.
  1796. This will look for a value at the end of the string.
  1797. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  1798. Negative numbers are not handled, so "xyz-5" returns 5.
  1799. @see getIntValue
  1800. */
  1801. int getTrailingIntValue() const throw();
  1802. /** Parses this string as a floating point number.
  1803. @returns the value of the string as a 32-bit floating point value.
  1804. @see getDoubleValue
  1805. */
  1806. float getFloatValue() const throw();
  1807. /** Parses this string as a floating point number.
  1808. @returns the value of the string as a 64-bit floating point value.
  1809. @see getFloatValue
  1810. */
  1811. double getDoubleValue() const throw();
  1812. /** Parses the string as a hexadecimal number.
  1813. Non-hexadecimal characters in the string are ignored.
  1814. If the string contains too many characters, then the lowest significant
  1815. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  1816. @returns a 32-bit number which is the value of the string in hex.
  1817. */
  1818. int getHexValue32() const throw();
  1819. /** Parses the string as a hexadecimal number.
  1820. Non-hexadecimal characters in the string are ignored.
  1821. If the string contains too many characters, then the lowest significant
  1822. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  1823. @returns a 64-bit number which is the value of the string in hex.
  1824. */
  1825. int64 getHexValue64() const throw();
  1826. /** Creates a string representing this 32-bit value in hexadecimal. */
  1827. static const String toHexString (int number);
  1828. /** Creates a string representing this 64-bit value in hexadecimal. */
  1829. static const String toHexString (int64 number);
  1830. /** Creates a string representing this 16-bit value in hexadecimal. */
  1831. static const String toHexString (short number);
  1832. /** Creates a string containing a hex dump of a block of binary data.
  1833. @param data the binary data to use as input
  1834. @param size how many bytes of data to use
  1835. @param groupSize how many bytes are grouped together before inserting a
  1836. space into the output. e.g. group size 0 has no spaces,
  1837. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  1838. like "bea1 c2ff".
  1839. */
  1840. static const String toHexString (const unsigned char* data,
  1841. int size,
  1842. int groupSize = 1);
  1843. /** Returns a unicode version of this string.
  1844. Because it returns a reference to the string's internal data, the pointer
  1845. that is returned must not be stored anywhere, as it can become invalid whenever
  1846. any string methods (even some const ones!) are called.
  1847. */
  1848. inline operator const juce_wchar*() const throw() { return text; }
  1849. /** Returns a unicode version of this string.
  1850. Because it returns a reference to the string's internal data, the pointer
  1851. that is returned must not be stored anywhere, as it can become invalid whenever
  1852. any string methods (even some const ones!) are called.
  1853. */
  1854. inline operator juce_wchar*() throw() { return text; }
  1855. /** Returns a pointer to a UTF-8 version of this string.
  1856. Because it returns a reference to the string's internal data, the pointer
  1857. that is returned must not be stored anywhere, as it can be deleted whenever the
  1858. string changes.
  1859. @see getNumBytesAsUTF8, fromUTF8, copyToUTF8, toCString
  1860. */
  1861. const char* toUTF8() const;
  1862. /** Creates a String from a UTF-8 encoded buffer.
  1863. If the size is < 0, it'll keep reading until it hits a zero.
  1864. */
  1865. static const String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1);
  1866. /** Returns the number of bytes required to represent this string as UTF8.
  1867. The number returned does NOT include the trailing zero.
  1868. @see toUTF8, copyToUTF8
  1869. */
  1870. int getNumBytesAsUTF8() const throw();
  1871. /** Copies the string to a buffer as UTF-8 characters.
  1872. Returns the number of bytes copied to the buffer, including the terminating null
  1873. character.
  1874. @param destBuffer the place to copy it to; if this is a null pointer,
  1875. the method just returns the number of bytes required
  1876. (including the terminating null character).
  1877. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  1878. string won't fit, it'll put in as many as it can while
  1879. still allowing for a terminating null char at the end, and
  1880. will return the number of bytes that were actually used.
  1881. */
  1882. int copyToUTF8 (char* destBuffer, int maxBufferSizeBytes) const throw();
  1883. /** Returns a version of this string using the default 8-bit multi-byte system encoding.
  1884. Because it returns a reference to the string's internal data, the pointer
  1885. that is returned must not be stored anywhere, as it can be deleted whenever the
  1886. string changes.
  1887. @see getNumBytesAsCString, copyToCString, toUTF8
  1888. */
  1889. const char* toCString() const;
  1890. /** Returns the number of bytes
  1891. */
  1892. int getNumBytesAsCString() const throw();
  1893. /** Copies the string to a buffer.
  1894. @param destBuffer the place to copy it to; if this is a null pointer,
  1895. the method just returns the number of bytes required
  1896. (including the terminating null character).
  1897. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  1898. string won't fit, it'll put in as many as it can while
  1899. still allowing for a terminating null char at the end, and
  1900. will return the number of bytes that were actually used.
  1901. */
  1902. int copyToCString (char* destBuffer, int maxBufferSizeBytes) const throw();
  1903. /** Copies the string to a unicode buffer.
  1904. @param destBuffer the place to copy it to
  1905. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1906. not including the tailing zero, so this shouldn't be
  1907. larger than the size of your destination buffer - 1
  1908. */
  1909. void copyToUnicode (juce_wchar* destBuffer, int maxCharsToCopy) const throw();
  1910. /** Increases the string's internally allocated storage.
  1911. Although the string's contents won't be affected by this call, it will
  1912. increase the amount of memory allocated internally for the string to grow into.
  1913. If you're about to make a large number of calls to methods such
  1914. as += or <<, it's more efficient to preallocate enough extra space
  1915. beforehand, so that these methods won't have to keep resizing the string
  1916. to append the extra characters.
  1917. @param numCharsNeeded the number of characters to allocate storage for. If this
  1918. value is less than the currently allocated size, it will
  1919. have no effect.
  1920. */
  1921. void preallocateStorage (size_t numCharsNeeded);
  1922. /** Swaps the contents of this string with another one.
  1923. This is a very fast operation, as no allocation or copying needs to be done.
  1924. */
  1925. void swapWith (String& other) throw();
  1926. /** A helper class to improve performance when concatenating many large strings
  1927. together.
  1928. Because appending one string to another involves measuring the length of
  1929. both strings, repeatedly doing this for many long strings will become
  1930. an exponentially slow operation. This class uses some internal state to
  1931. avoid that, so that each append operation only needs to measure the length
  1932. of the appended string.
  1933. */
  1934. class JUCE_API Concatenator
  1935. {
  1936. public:
  1937. Concatenator (String& stringToAppendTo);
  1938. ~Concatenator();
  1939. void append (const String& s);
  1940. private:
  1941. String& result;
  1942. int nextIndex;
  1943. Concatenator (const Concatenator&);
  1944. Concatenator& operator= (const Concatenator&);
  1945. };
  1946. juce_UseDebuggingNewOperator // (adds debugging info to find leaked objects)
  1947. private:
  1948. juce_wchar* text;
  1949. // internal constructor that preallocates a certain amount of memory
  1950. String (size_t numChars, int dummyVariable);
  1951. String (const String& stringToCopy, size_t charsToAllocate);
  1952. void createInternal (const juce_wchar* text, size_t numChars);
  1953. void appendInternal (const juce_wchar* text, int numExtraChars);
  1954. };
  1955. /** Concatenates two strings. */
  1956. const String JUCE_CALLTYPE operator+ (const char* string1, const String& string2);
  1957. /** Concatenates two strings. */
  1958. const String JUCE_CALLTYPE operator+ (const juce_wchar* string1, const String& string2);
  1959. /** Concatenates two strings. */
  1960. const String JUCE_CALLTYPE operator+ (char string1, const String& string2);
  1961. /** Concatenates two strings. */
  1962. const String JUCE_CALLTYPE operator+ (juce_wchar string1, const String& string2);
  1963. /** Concatenates two strings. */
  1964. const String JUCE_CALLTYPE operator+ (String string1, const String& string2);
  1965. /** Concatenates two strings. */
  1966. const String JUCE_CALLTYPE operator+ (String string1, const char* string2);
  1967. /** Concatenates two strings. */
  1968. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* string2);
  1969. /** Concatenates two strings. */
  1970. const String JUCE_CALLTYPE operator+ (String string1, char characterToAppend);
  1971. /** Concatenates two strings. */
  1972. const String JUCE_CALLTYPE operator+ (String string1, juce_wchar characterToAppend);
  1973. /** Appends a character at the end of a string. */
  1974. String& JUCE_CALLTYPE operator<< (String& string1, char characterToAppend);
  1975. /** Appends a character at the end of a string. */
  1976. String& JUCE_CALLTYPE operator<< (String& string1, juce_wchar characterToAppend);
  1977. /** Appends a string to the end of the first one. */
  1978. String& JUCE_CALLTYPE operator<< (String& string1, const char* string2);
  1979. /** Appends a string to the end of the first one. */
  1980. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* string2);
  1981. /** Appends a string to the end of the first one. */
  1982. String& JUCE_CALLTYPE operator<< (String& string1, const String& string2);
  1983. /** Appends a decimal number at the end of a string. */
  1984. String& JUCE_CALLTYPE operator<< (String& string1, short number);
  1985. /** Appends a decimal number at the end of a string. */
  1986. String& JUCE_CALLTYPE operator<< (String& string1, int number);
  1987. /** Appends a decimal number at the end of a string. */
  1988. String& JUCE_CALLTYPE operator<< (String& string1, unsigned int number);
  1989. /** Appends a decimal number at the end of a string. */
  1990. String& JUCE_CALLTYPE operator<< (String& string1, long number);
  1991. /** Appends a decimal number at the end of a string. */
  1992. String& JUCE_CALLTYPE operator<< (String& string1, unsigned long number);
  1993. /** Appends a decimal number at the end of a string. */
  1994. String& JUCE_CALLTYPE operator<< (String& string1, float number);
  1995. /** Appends a decimal number at the end of a string. */
  1996. String& JUCE_CALLTYPE operator<< (String& string1, double number);
  1997. /** Case-sensitive comparison of two strings. */
  1998. bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw();
  1999. /** Case-sensitive comparison of two strings. */
  2000. bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw();
  2001. /** Case-sensitive comparison of two strings. */
  2002. bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw();
  2003. /** Case-sensitive comparison of two strings. */
  2004. bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw();
  2005. /** Case-sensitive comparison of two strings. */
  2006. bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw();
  2007. /** Case-sensitive comparison of two strings. */
  2008. bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw();
  2009. /** Case-sensitive comparison of two strings. */
  2010. bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw();
  2011. /** Case-sensitive comparison of two strings. */
  2012. bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw();
  2013. /** Case-sensitive comparison of two strings. */
  2014. bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw();
  2015. /** Case-sensitive comparison of two strings. */
  2016. bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw();
  2017. /** This streaming override allows you to pass a juce String directly into std output streams.
  2018. This is very handy for writing strings to std::cout, std::cerr, etc.
  2019. */
  2020. template <class charT, class traits>
  2021. std::basic_ostream <charT, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <charT, traits>& stream, const String& stringToWrite)
  2022. {
  2023. return stream << stringToWrite.toUTF8();
  2024. }
  2025. /** Writes a string to an OutputStream as UTF8. */
  2026. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text);
  2027. #endif // __JUCE_STRING_JUCEHEADER__
  2028. /*** End of inlined file: juce_String.h ***/
  2029. /**
  2030. Acts as an application-wide logging class.
  2031. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  2032. method and this will then be used by all calls to writeToLog.
  2033. The logger class also contains methods for writing messages to the debugger's
  2034. output stream.
  2035. @see FileLogger
  2036. */
  2037. class JUCE_API Logger
  2038. {
  2039. public:
  2040. /** Destructor. */
  2041. virtual ~Logger();
  2042. /** Sets the current logging class to use.
  2043. Note that the object passed in won't be deleted when no longer needed.
  2044. A null pointer can be passed-in to disable any logging.
  2045. If deleteOldLogger is set to true, the existing logger will be
  2046. deleted (if there is one).
  2047. */
  2048. static void JUCE_CALLTYPE setCurrentLogger (Logger* const newLogger,
  2049. const bool deleteOldLogger = false);
  2050. /** Writes a string to the current logger.
  2051. This will pass the string to the logger's logMessage() method if a logger
  2052. has been set.
  2053. @see logMessage
  2054. */
  2055. static void JUCE_CALLTYPE writeToLog (const String& message);
  2056. /** Writes a message to the standard error stream.
  2057. This can be called directly, or by using the DBG() macro in
  2058. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  2059. */
  2060. static void JUCE_CALLTYPE outputDebugString (const String& text);
  2061. protected:
  2062. Logger();
  2063. /** This is overloaded by subclasses to implement custom logging behaviour.
  2064. @see setCurrentLogger
  2065. */
  2066. virtual void logMessage (const String& message) = 0;
  2067. };
  2068. #endif // __JUCE_LOGGER_JUCEHEADER__
  2069. /*** End of inlined file: juce_Logger.h ***/
  2070. END_JUCE_NAMESPACE
  2071. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  2072. /*** End of inlined file: juce_StandardHeader.h ***/
  2073. BEGIN_JUCE_NAMESPACE
  2074. #if JUCE_MSVC
  2075. // this is set explicitly in case the app is using a different packing size.
  2076. #pragma pack (push, 8)
  2077. #pragma warning (push)
  2078. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  2079. #endif
  2080. // this is where all the class header files get brought in..
  2081. /*** Start of inlined file: juce_core_includes.h ***/
  2082. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  2083. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  2084. #ifndef __JUCE_ARRAY_JUCEHEADER__
  2085. /*** Start of inlined file: juce_Array.h ***/
  2086. #ifndef __JUCE_ARRAY_JUCEHEADER__
  2087. #define __JUCE_ARRAY_JUCEHEADER__
  2088. /*** Start of inlined file: juce_ArrayAllocationBase.h ***/
  2089. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2090. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2091. /*** Start of inlined file: juce_HeapBlock.h ***/
  2092. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  2093. #define __JUCE_HEAPBLOCK_JUCEHEADER__
  2094. /**
  2095. Very simple container class to hold a pointer to some data on the heap.
  2096. When you need to allocate some heap storage for something, always try to use
  2097. this class instead of allocating the memory directly using malloc/free.
  2098. A HeapBlock<char> object can be treated in pretty much exactly the same way
  2099. as an char*, but as long as you allocate it on the stack or as a class member,
  2100. it's almost impossible for it to leak memory.
  2101. It also makes your code much more concise and readable than doing the same thing
  2102. using direct allocations,
  2103. E.g. instead of this:
  2104. @code
  2105. int* temp = (int*) juce_malloc (1024 * sizeof (int));
  2106. memcpy (temp, xyz, 1024 * sizeof (int));
  2107. juce_free (temp);
  2108. temp = (int*) juce_calloc (2048 * sizeof (int));
  2109. temp[0] = 1234;
  2110. memcpy (foobar, temp, 2048 * sizeof (int));
  2111. juce_free (temp);
  2112. @endcode
  2113. ..you could just write this:
  2114. @code
  2115. HeapBlock <int> temp (1024);
  2116. memcpy (temp, xyz, 1024 * sizeof (int));
  2117. temp.calloc (2048);
  2118. temp[0] = 1234;
  2119. memcpy (foobar, temp, 2048 * sizeof (int));
  2120. @endcode
  2121. The class is extremely lightweight, containing only a pointer to the
  2122. data, and exposes malloc/realloc/calloc/free methods that do the same jobs
  2123. as their less object-oriented counterparts. Despite adding safety, you probably
  2124. won't sacrifice any performance by using this in place of normal pointers.
  2125. @see Array, OwnedArray, MemoryBlock
  2126. */
  2127. template <class ElementType>
  2128. class HeapBlock
  2129. {
  2130. public:
  2131. /** Creates a HeapBlock which is initially just a null pointer.
  2132. After creation, you can resize the array using the malloc(), calloc(),
  2133. or realloc() methods.
  2134. */
  2135. HeapBlock() throw() : data (0)
  2136. {
  2137. }
  2138. /** Creates a HeapBlock containing a number of elements.
  2139. The contents of the block are undefined, as it will have been created by a
  2140. malloc call.
  2141. If you want an array of zero values, you can use the calloc() method instead.
  2142. */
  2143. explicit HeapBlock (const size_t numElements)
  2144. : data (static_cast <ElementType*> (::juce_malloc (numElements * sizeof (ElementType))))
  2145. {
  2146. }
  2147. /** Destructor.
  2148. This will free the data, if any has been allocated.
  2149. */
  2150. ~HeapBlock()
  2151. {
  2152. ::juce_free (data);
  2153. }
  2154. /** Returns a raw pointer to the allocated data.
  2155. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2156. freed by calling the free() method.
  2157. */
  2158. inline operator ElementType*() const throw() { return data; }
  2159. /** Returns a raw pointer to the allocated data.
  2160. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2161. freed by calling the free() method.
  2162. */
  2163. inline ElementType* getData() const throw() { return data; }
  2164. /** Returns a void pointer to the allocated data.
  2165. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2166. freed by calling the free() method.
  2167. */
  2168. inline operator void*() const throw() { return static_cast <void*> (data); }
  2169. /** Lets you use indirect calls to the first element in the array.
  2170. Obviously this will cause problems if the array hasn't been initialised, because it'll
  2171. be referencing a null pointer.
  2172. */
  2173. inline ElementType* operator->() const throw() { return data; }
  2174. /** Returns a reference to one of the data elements.
  2175. Obviously there's no bounds-checking here, as this object is just a dumb pointer and
  2176. has no idea of the size it currently has allocated.
  2177. */
  2178. template <typename IndexType>
  2179. inline ElementType& operator[] (IndexType index) const throw() { return data [index]; }
  2180. /** Returns a pointer to a data element at an offset from the start of the array.
  2181. This is the same as doing pointer arithmetic on the raw pointer itself.
  2182. */
  2183. template <typename IndexType>
  2184. inline ElementType* operator+ (IndexType index) const throw() { return data + index; }
  2185. /** Returns a reference to the raw data pointer.
  2186. Beware that the pointer returned here will become invalid as soon as you call
  2187. any of the allocator methods on this object!
  2188. */
  2189. inline ElementType* const* operator&() const throw() { return static_cast <ElementType* const*> (&data); }
  2190. /** Returns a reference to the raw data pointer.
  2191. Beware that the pointer returned here will become invalid as soon as you call
  2192. any of the allocator methods on this object!
  2193. */
  2194. inline ElementType** operator&() throw() { return static_cast <ElementType**> (&data); }
  2195. /** Compares the pointer with another pointer.
  2196. This can be handy for checking whether this is a null pointer.
  2197. */
  2198. inline bool operator== (const ElementType* const otherPointer) const throw() { return otherPointer == data; }
  2199. /** Compares the pointer with another pointer.
  2200. This can be handy for checking whether this is a null pointer.
  2201. */
  2202. inline bool operator!= (const ElementType* const otherPointer) const throw() { return otherPointer != data; }
  2203. /** Allocates a specified amount of memory.
  2204. This uses the normal malloc to allocate an amount of memory for this object.
  2205. Any previously allocated memory will be freed by this method.
  2206. The number of bytes allocated will be (newNumElements * elementSize). Normally
  2207. you wouldn't need to specify the second parameter, but it can be handy if you need
  2208. to allocate a size in bytes rather than in terms of the number of elements.
  2209. The data that is allocated will be freed when this object is deleted, or when you
  2210. call free() or any of the allocation methods.
  2211. */
  2212. void malloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2213. {
  2214. ::juce_free (data);
  2215. data = static_cast <ElementType*> (::juce_malloc (newNumElements * elementSize));
  2216. }
  2217. /** Allocates a specified amount of memory and clears it.
  2218. This does the same job as the malloc() method, but clears the memory that it allocates.
  2219. */
  2220. void calloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2221. {
  2222. ::juce_free (data);
  2223. data = static_cast <ElementType*> (::juce_calloc (newNumElements * elementSize));
  2224. }
  2225. /** Allocates a specified amount of memory and optionally clears it.
  2226. This does the same job as either malloc() or calloc(), depending on the
  2227. initialiseToZero parameter.
  2228. */
  2229. void allocate (const size_t newNumElements, const bool initialiseToZero)
  2230. {
  2231. ::juce_free (data);
  2232. if (initialiseToZero)
  2233. data = static_cast <ElementType*> (::juce_calloc (newNumElements * sizeof (ElementType)));
  2234. else
  2235. data = static_cast <ElementType*> (::juce_malloc (newNumElements * sizeof (ElementType)));
  2236. }
  2237. /** Re-allocates a specified amount of memory.
  2238. The semantics of this method are the same as malloc() and calloc(), but it
  2239. uses realloc() to keep as much of the existing data as possible.
  2240. */
  2241. void realloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2242. {
  2243. if (data == 0)
  2244. data = static_cast <ElementType*> (::juce_malloc (newNumElements * elementSize));
  2245. else
  2246. data = static_cast <ElementType*> (::juce_realloc (data, newNumElements * elementSize));
  2247. }
  2248. /** Frees any currently-allocated data.
  2249. This will free the data and reset this object to be a null pointer.
  2250. */
  2251. void free()
  2252. {
  2253. ::juce_free (data);
  2254. data = 0;
  2255. }
  2256. /** Swaps this object's data with the data of another HeapBlock.
  2257. The two objects simply exchange their data pointers.
  2258. */
  2259. void swapWith (HeapBlock <ElementType>& other) throw()
  2260. {
  2261. swapVariables (data, other.data);
  2262. }
  2263. private:
  2264. ElementType* data;
  2265. HeapBlock (const HeapBlock&);
  2266. HeapBlock& operator= (const HeapBlock&);
  2267. };
  2268. #endif // __JUCE_HEAPBLOCK_JUCEHEADER__
  2269. /*** End of inlined file: juce_HeapBlock.h ***/
  2270. /**
  2271. Implements some basic array storage allocation functions.
  2272. This class isn't really for public use - it's used by the other
  2273. array classes, but might come in handy for some purposes.
  2274. It inherits from a critical section class to allow the arrays to use
  2275. the "empty base class optimisation" pattern to reduce their footprint.
  2276. @see Array, OwnedArray, ReferenceCountedArray
  2277. */
  2278. template <class ElementType, class TypeOfCriticalSectionToUse>
  2279. class ArrayAllocationBase : public TypeOfCriticalSectionToUse
  2280. {
  2281. public:
  2282. /** Creates an empty array. */
  2283. ArrayAllocationBase() throw()
  2284. : numAllocated (0)
  2285. {
  2286. }
  2287. /** Destructor. */
  2288. ~ArrayAllocationBase()
  2289. {
  2290. }
  2291. /** Changes the amount of storage allocated.
  2292. This will retain any data currently held in the array, and either add or
  2293. remove extra space at the end.
  2294. @param numElements the number of elements that are needed
  2295. */
  2296. void setAllocatedSize (const int numElements)
  2297. {
  2298. if (numAllocated != numElements)
  2299. {
  2300. if (numElements > 0)
  2301. elements.realloc (numElements);
  2302. else
  2303. elements.free();
  2304. numAllocated = numElements;
  2305. }
  2306. }
  2307. /** Increases the amount of storage allocated if it is less than a given amount.
  2308. This will retain any data currently held in the array, but will add
  2309. extra space at the end to make sure there it's at least as big as the size
  2310. passed in. If it's already bigger, no action is taken.
  2311. @param minNumElements the minimum number of elements that are needed
  2312. */
  2313. void ensureAllocatedSize (const int minNumElements)
  2314. {
  2315. if (minNumElements > numAllocated)
  2316. setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
  2317. }
  2318. /** Minimises the amount of storage allocated so that it's no more than
  2319. the given number of elements.
  2320. */
  2321. void shrinkToNoMoreThan (const int maxNumElements)
  2322. {
  2323. if (maxNumElements < numAllocated)
  2324. setAllocatedSize (maxNumElements);
  2325. }
  2326. /** Swap the contents of two objects. */
  2327. void swapWith (ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  2328. {
  2329. elements.swapWith (other.elements);
  2330. swapVariables (numAllocated, other.numAllocated);
  2331. }
  2332. HeapBlock <ElementType> elements;
  2333. int numAllocated;
  2334. private:
  2335. ArrayAllocationBase (const ArrayAllocationBase&);
  2336. ArrayAllocationBase& operator= (const ArrayAllocationBase&);
  2337. };
  2338. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2339. /*** End of inlined file: juce_ArrayAllocationBase.h ***/
  2340. /*** Start of inlined file: juce_ElementComparator.h ***/
  2341. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2342. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2343. /**
  2344. Sorts a range of elements in an array.
  2345. The comparator object that is passed-in must define a public method with the following
  2346. signature:
  2347. @code
  2348. int compareElements (ElementType first, ElementType second);
  2349. @endcode
  2350. ..and this method must return:
  2351. - a value of < 0 if the first comes before the second
  2352. - a value of 0 if the two objects are equivalent
  2353. - a value of > 0 if the second comes before the first
  2354. To improve performance, the compareElements() method can be declared as static or const.
  2355. @param comparator an object which defines a compareElements() method
  2356. @param array the array to sort
  2357. @param firstElement the index of the first element of the range to be sorted
  2358. @param lastElement the index of the last element in the range that needs
  2359. sorting (this is inclusive)
  2360. @param retainOrderOfEquivalentItems if true, the order of items that the
  2361. comparator deems the same will be maintained - this will be
  2362. a slower algorithm than if they are allowed to be moved around.
  2363. @see sortArrayRetainingOrder
  2364. */
  2365. template <class ElementType, class ElementComparator>
  2366. static void sortArray (ElementComparator& comparator,
  2367. ElementType* const array,
  2368. int firstElement,
  2369. int lastElement,
  2370. const bool retainOrderOfEquivalentItems)
  2371. {
  2372. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2373. // avoids getting warning messages about the parameter being unused
  2374. if (lastElement > firstElement)
  2375. {
  2376. if (retainOrderOfEquivalentItems)
  2377. {
  2378. for (int i = firstElement; i < lastElement; ++i)
  2379. {
  2380. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  2381. {
  2382. const ElementType temp = array [i];
  2383. array [i] = array[i + 1];
  2384. array [i + 1] = temp;
  2385. if (i > firstElement)
  2386. i -= 2;
  2387. }
  2388. }
  2389. }
  2390. else
  2391. {
  2392. int fromStack[30], toStack[30];
  2393. int stackIndex = 0;
  2394. for (;;)
  2395. {
  2396. const int size = (lastElement - firstElement) + 1;
  2397. if (size <= 8)
  2398. {
  2399. int j = lastElement;
  2400. int maxIndex;
  2401. while (j > firstElement)
  2402. {
  2403. maxIndex = firstElement;
  2404. for (int k = firstElement + 1; k <= j; ++k)
  2405. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  2406. maxIndex = k;
  2407. const ElementType temp = array [maxIndex];
  2408. array [maxIndex] = array[j];
  2409. array [j] = temp;
  2410. --j;
  2411. }
  2412. }
  2413. else
  2414. {
  2415. const int mid = firstElement + (size >> 1);
  2416. ElementType temp = array [mid];
  2417. array [mid] = array [firstElement];
  2418. array [firstElement] = temp;
  2419. int i = firstElement;
  2420. int j = lastElement + 1;
  2421. for (;;)
  2422. {
  2423. while (++i <= lastElement
  2424. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  2425. {}
  2426. while (--j > firstElement
  2427. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  2428. {}
  2429. if (j < i)
  2430. break;
  2431. temp = array[i];
  2432. array[i] = array[j];
  2433. array[j] = temp;
  2434. }
  2435. temp = array [firstElement];
  2436. array [firstElement] = array[j];
  2437. array [j] = temp;
  2438. if (j - 1 - firstElement >= lastElement - i)
  2439. {
  2440. if (firstElement + 1 < j)
  2441. {
  2442. fromStack [stackIndex] = firstElement;
  2443. toStack [stackIndex] = j - 1;
  2444. ++stackIndex;
  2445. }
  2446. if (i < lastElement)
  2447. {
  2448. firstElement = i;
  2449. continue;
  2450. }
  2451. }
  2452. else
  2453. {
  2454. if (i < lastElement)
  2455. {
  2456. fromStack [stackIndex] = i;
  2457. toStack [stackIndex] = lastElement;
  2458. ++stackIndex;
  2459. }
  2460. if (firstElement + 1 < j)
  2461. {
  2462. lastElement = j - 1;
  2463. continue;
  2464. }
  2465. }
  2466. }
  2467. if (--stackIndex < 0)
  2468. break;
  2469. jassert (stackIndex < numElementsInArray (fromStack));
  2470. firstElement = fromStack [stackIndex];
  2471. lastElement = toStack [stackIndex];
  2472. }
  2473. }
  2474. }
  2475. }
  2476. /**
  2477. Searches a sorted array of elements, looking for the index at which a specified value
  2478. should be inserted for it to be in the correct order.
  2479. The comparator object that is passed-in must define a public method with the following
  2480. signature:
  2481. @code
  2482. int compareElements (ElementType first, ElementType second);
  2483. @endcode
  2484. ..and this method must return:
  2485. - a value of < 0 if the first comes before the second
  2486. - a value of 0 if the two objects are equivalent
  2487. - a value of > 0 if the second comes before the first
  2488. To improve performance, the compareElements() method can be declared as static or const.
  2489. @param comparator an object which defines a compareElements() method
  2490. @param array the array to search
  2491. @param newElement the value that is going to be inserted
  2492. @param firstElement the index of the first element to search
  2493. @param lastElement the index of the last element in the range (this is non-inclusive)
  2494. */
  2495. template <class ElementType, class ElementComparator>
  2496. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  2497. ElementType* const array,
  2498. const ElementType newElement,
  2499. int firstElement,
  2500. int lastElement)
  2501. {
  2502. jassert (firstElement <= lastElement);
  2503. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2504. // avoids getting warning messages about the parameter being unused
  2505. while (firstElement < lastElement)
  2506. {
  2507. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  2508. {
  2509. ++firstElement;
  2510. break;
  2511. }
  2512. else
  2513. {
  2514. const int halfway = (firstElement + lastElement) >> 1;
  2515. if (halfway == firstElement)
  2516. {
  2517. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2518. ++firstElement;
  2519. break;
  2520. }
  2521. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2522. {
  2523. firstElement = halfway;
  2524. }
  2525. else
  2526. {
  2527. lastElement = halfway;
  2528. }
  2529. }
  2530. }
  2531. return firstElement;
  2532. }
  2533. /**
  2534. A simple ElementComparator class that can be used to sort an array of
  2535. objects that support the '<' operator.
  2536. This will work for primitive types and objects that implement operator<().
  2537. Example: @code
  2538. Array <int> myArray;
  2539. DefaultElementComparator<int> sorter;
  2540. myArray.sort (sorter);
  2541. @endcode
  2542. @see ElementComparator
  2543. */
  2544. template <class ElementType>
  2545. class DefaultElementComparator
  2546. {
  2547. private:
  2548. typedef PARAMETER_TYPE (ElementType) ParameterType;
  2549. public:
  2550. static int compareElements (ParameterType first, ParameterType second)
  2551. {
  2552. return (first < second) ? -1 : ((second < first) ? 1 : 0);
  2553. }
  2554. };
  2555. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2556. /*** End of inlined file: juce_ElementComparator.h ***/
  2557. /*** Start of inlined file: juce_CriticalSection.h ***/
  2558. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  2559. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  2560. class JUCE_API ScopedLock;
  2561. class JUCE_API ScopedUnlock;
  2562. /**
  2563. Prevents multiple threads from accessing shared objects at the same time.
  2564. @see ScopedLock, Thread, InterProcessLock
  2565. */
  2566. class JUCE_API CriticalSection
  2567. {
  2568. public:
  2569. /**
  2570. Creates a CriticalSection object
  2571. */
  2572. CriticalSection() throw();
  2573. /** Destroys a CriticalSection object.
  2574. If the critical section is deleted whilst locked, its subsequent behaviour
  2575. is unpredictable.
  2576. */
  2577. ~CriticalSection() throw();
  2578. /** Locks this critical section.
  2579. If the lock is currently held by another thread, this will wait until it
  2580. becomes free.
  2581. If the lock is already held by the caller thread, the method returns immediately.
  2582. @see exit, ScopedLock
  2583. */
  2584. void enter() const throw();
  2585. /** Attempts to lock this critical section without blocking.
  2586. This method behaves identically to CriticalSection::enter, except that the caller thread
  2587. does not wait if the lock is currently held by another thread but returns false immediately.
  2588. @returns false if the lock is currently held by another thread, true otherwise.
  2589. @see enter
  2590. */
  2591. bool tryEnter() const throw();
  2592. /** Releases the lock.
  2593. If the caller thread hasn't got the lock, this can have unpredictable results.
  2594. If the enter() method has been called multiple times by the thread, each
  2595. call must be matched by a call to exit() before other threads will be allowed
  2596. to take over the lock.
  2597. @see enter, ScopedLock
  2598. */
  2599. void exit() const throw();
  2600. /** Provides the type of scoped lock to use with this type of critical section object. */
  2601. typedef ScopedLock ScopedLockType;
  2602. /** Provides the type of scoped unlocker to use with this type of critical section object. */
  2603. typedef ScopedUnlock ScopedUnlockType;
  2604. juce_UseDebuggingNewOperator
  2605. private:
  2606. #if JUCE_WINDOWS
  2607. #if JUCE_64BIT
  2608. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  2609. // block of memory here that's big enough to be used internally as a windows critical
  2610. // section object.
  2611. uint8 internal [44];
  2612. #else
  2613. uint8 internal [24];
  2614. #endif
  2615. #else
  2616. mutable pthread_mutex_t internal;
  2617. #endif
  2618. CriticalSection (const CriticalSection&);
  2619. CriticalSection& operator= (const CriticalSection&);
  2620. };
  2621. /**
  2622. A class that can be used in place of a real CriticalSection object.
  2623. This is currently used by some templated classes, and should get
  2624. optimised out by the compiler.
  2625. @see Array, OwnedArray, ReferenceCountedArray
  2626. */
  2627. class JUCE_API DummyCriticalSection
  2628. {
  2629. public:
  2630. inline DummyCriticalSection() throw() {}
  2631. inline ~DummyCriticalSection() throw() {}
  2632. inline void enter() const throw() {}
  2633. inline void exit() const throw() {}
  2634. /** A dummy scoped-lock type to use with a dummy critical section. */
  2635. struct ScopedLockType
  2636. {
  2637. ScopedLockType (const DummyCriticalSection&) throw() {}
  2638. };
  2639. /** A dummy scoped-unlocker type to use with a dummy critical section. */
  2640. typedef ScopedLockType ScopedUnlockType;
  2641. private:
  2642. DummyCriticalSection (const DummyCriticalSection&);
  2643. DummyCriticalSection& operator= (const DummyCriticalSection&);
  2644. };
  2645. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  2646. /*** End of inlined file: juce_CriticalSection.h ***/
  2647. /**
  2648. Holds a list of simple objects, such as ints, doubles, or pointers.
  2649. Examples of arrays are: Array<int>, Array<Rectangle> or Array<MyClass*>
  2650. The array can be used to hold simple, non-polymorphic objects as well as primitive types - to
  2651. do so, the class must fulfil these requirements:
  2652. - it must have a copy constructor and operator=
  2653. - it must be able to be relocated in memory by a memcpy without this causing a problem - so no
  2654. objects whose functionality relies on pointers or references to themselves can be used.
  2655. You can of course have an array of pointers to any kind of object, e.g. Array <MyClass*>, but if
  2656. you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the
  2657. ReferenceCountedArray class for more powerful ways of holding lists of objects.
  2658. For holding lists of strings, you can use Array\<String\>, but it's usually better to use the
  2659. specialised class StringArray, which provides more useful functions.
  2660. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  2661. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  2662. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  2663. */
  2664. template <typename ElementType,
  2665. typename TypeOfCriticalSectionToUse = DummyCriticalSection>
  2666. class Array
  2667. {
  2668. private:
  2669. #if defined (_MSC_VER) && _MSC_VER <= 1400
  2670. typedef const ElementType& ParameterType;
  2671. #else
  2672. typedef PARAMETER_TYPE (ElementType) ParameterType;
  2673. #endif
  2674. public:
  2675. /** Creates an empty array. */
  2676. Array() throw()
  2677. : numUsed (0)
  2678. {
  2679. }
  2680. /** Creates a copy of another array.
  2681. @param other the array to copy
  2682. */
  2683. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other)
  2684. {
  2685. const ScopedLockType lock (other.getLock());
  2686. numUsed = other.numUsed;
  2687. data.setAllocatedSize (other.numUsed);
  2688. for (int i = 0; i < numUsed; ++i)
  2689. new (data.elements + i) ElementType (other.data.elements[i]);
  2690. }
  2691. /** Initalises from a null-terminated C array of values.
  2692. @param values the array to copy from
  2693. */
  2694. template <typename TypeToCreateFrom>
  2695. explicit Array (const TypeToCreateFrom* values)
  2696. : numUsed (0)
  2697. {
  2698. while (*values != TypeToCreateFrom())
  2699. add (*values++);
  2700. }
  2701. /** Initalises from a C array of values.
  2702. @param values the array to copy from
  2703. @param numValues the number of values in the array
  2704. */
  2705. template <typename TypeToCreateFrom>
  2706. Array (const TypeToCreateFrom* values, int numValues)
  2707. : numUsed (numValues)
  2708. {
  2709. data.setAllocatedSize (numValues);
  2710. for (int i = 0; i < numValues; ++i)
  2711. new (data.elements + i) ElementType (values[i]);
  2712. }
  2713. /** Destructor. */
  2714. ~Array()
  2715. {
  2716. for (int i = 0; i < numUsed; ++i)
  2717. data.elements[i].~ElementType();
  2718. }
  2719. /** Copies another array.
  2720. @param other the array to copy
  2721. */
  2722. Array& operator= (const Array& other)
  2723. {
  2724. if (this != &other)
  2725. {
  2726. Array<ElementType, TypeOfCriticalSectionToUse> otherCopy (other);
  2727. swapWithArray (otherCopy);
  2728. }
  2729. return *this;
  2730. }
  2731. /** Compares this array to another one.
  2732. Two arrays are considered equal if they both contain the same set of
  2733. elements, in the same order.
  2734. @param other the other array to compare with
  2735. */
  2736. template <class OtherArrayType>
  2737. bool operator== (const OtherArrayType& other) const
  2738. {
  2739. const ScopedLockType lock (getLock());
  2740. if (numUsed != other.numUsed)
  2741. return false;
  2742. for (int i = numUsed; --i >= 0;)
  2743. if (! (data.elements [i] == other.data.elements [i]))
  2744. return false;
  2745. return true;
  2746. }
  2747. /** Compares this array to another one.
  2748. Two arrays are considered equal if they both contain the same set of
  2749. elements, in the same order.
  2750. @param other the other array to compare with
  2751. */
  2752. template <class OtherArrayType>
  2753. bool operator!= (const OtherArrayType& other) const
  2754. {
  2755. return ! operator== (other);
  2756. }
  2757. /** Removes all elements from the array.
  2758. This will remove all the elements, and free any storage that the array is
  2759. using. To clear the array without freeing the storage, use the clearQuick()
  2760. method instead.
  2761. @see clearQuick
  2762. */
  2763. void clear()
  2764. {
  2765. const ScopedLockType lock (getLock());
  2766. for (int i = 0; i < numUsed; ++i)
  2767. data.elements[i].~ElementType();
  2768. data.setAllocatedSize (0);
  2769. numUsed = 0;
  2770. }
  2771. /** Removes all elements from the array without freeing the array's allocated storage.
  2772. @see clear
  2773. */
  2774. void clearQuick()
  2775. {
  2776. const ScopedLockType lock (getLock());
  2777. for (int i = 0; i < numUsed; ++i)
  2778. data.elements[i].~ElementType();
  2779. numUsed = 0;
  2780. }
  2781. /** Returns the current number of elements in the array.
  2782. */
  2783. inline int size() const throw()
  2784. {
  2785. return numUsed;
  2786. }
  2787. /** Returns one of the elements in the array.
  2788. If the index passed in is beyond the range of valid elements, this
  2789. will return zero.
  2790. If you're certain that the index will always be a valid element, you
  2791. can call getUnchecked() instead, which is faster.
  2792. @param index the index of the element being requested (0 is the first element in the array)
  2793. @see getUnchecked, getFirst, getLast
  2794. */
  2795. inline ElementType operator[] (const int index) const
  2796. {
  2797. const ScopedLockType lock (getLock());
  2798. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  2799. : ElementType();
  2800. }
  2801. /** Returns one of the elements in the array, without checking the index passed in.
  2802. Unlike the operator[] method, this will try to return an element without
  2803. checking that the index is within the bounds of the array, so should only
  2804. be used when you're confident that it will always be a valid index.
  2805. @param index the index of the element being requested (0 is the first element in the array)
  2806. @see operator[], getFirst, getLast
  2807. */
  2808. inline const ElementType getUnchecked (const int index) const
  2809. {
  2810. const ScopedLockType lock (getLock());
  2811. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2812. return data.elements [index];
  2813. }
  2814. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  2815. This is like getUnchecked, but returns a direct reference to the element, so that
  2816. you can alter it directly. Obviously this can be dangerous, so only use it when
  2817. absolutely necessary.
  2818. @param index the index of the element being requested (0 is the first element in the array)
  2819. @see operator[], getFirst, getLast
  2820. */
  2821. inline ElementType& getReference (const int index) const throw()
  2822. {
  2823. const ScopedLockType lock (getLock());
  2824. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2825. return data.elements [index];
  2826. }
  2827. /** Returns the first element in the array, or 0 if the array is empty.
  2828. @see operator[], getUnchecked, getLast
  2829. */
  2830. inline ElementType getFirst() const
  2831. {
  2832. const ScopedLockType lock (getLock());
  2833. return (numUsed > 0) ? data.elements [0]
  2834. : ElementType();
  2835. }
  2836. /** Returns the last element in the array, or 0 if the array is empty.
  2837. @see operator[], getUnchecked, getFirst
  2838. */
  2839. inline ElementType getLast() const
  2840. {
  2841. const ScopedLockType lock (getLock());
  2842. return (numUsed > 0) ? data.elements [numUsed - 1]
  2843. : ElementType();
  2844. }
  2845. /** Returns a pointer to the actual array data.
  2846. This pointer will only be valid until the next time a non-const method
  2847. is called on the array.
  2848. */
  2849. inline ElementType* getRawDataPointer() throw()
  2850. {
  2851. return data.elements;
  2852. }
  2853. /** Finds the index of the first element which matches the value passed in.
  2854. This will search the array for the given object, and return the index
  2855. of its first occurrence. If the object isn't found, the method will return -1.
  2856. @param elementToLookFor the value or object to look for
  2857. @returns the index of the object, or -1 if it's not found
  2858. */
  2859. int indexOf (ParameterType elementToLookFor) const
  2860. {
  2861. const ScopedLockType lock (getLock());
  2862. const ElementType* e = data.elements.getData();
  2863. const ElementType* const end = e + numUsed;
  2864. while (e != end)
  2865. {
  2866. if (elementToLookFor == *e)
  2867. return static_cast <int> (e - data.elements.getData());
  2868. ++e;
  2869. }
  2870. return -1;
  2871. }
  2872. /** Returns true if the array contains at least one occurrence of an object.
  2873. @param elementToLookFor the value or object to look for
  2874. @returns true if the item is found
  2875. */
  2876. bool contains (ParameterType elementToLookFor) const
  2877. {
  2878. const ScopedLockType lock (getLock());
  2879. const ElementType* e = data.elements.getData();
  2880. const ElementType* const end = e + numUsed;
  2881. while (e != end)
  2882. {
  2883. if (elementToLookFor == *e)
  2884. return true;
  2885. ++e;
  2886. }
  2887. return false;
  2888. }
  2889. /** Appends a new element at the end of the array.
  2890. @param newElement the new object to add to the array
  2891. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  2892. */
  2893. void add (ParameterType newElement)
  2894. {
  2895. const ScopedLockType lock (getLock());
  2896. data.ensureAllocatedSize (numUsed + 1);
  2897. new (data.elements + numUsed++) ElementType (newElement);
  2898. }
  2899. /** Inserts a new element into the array at a given position.
  2900. If the index is less than 0 or greater than the size of the array, the
  2901. element will be added to the end of the array.
  2902. Otherwise, it will be inserted into the array, moving all the later elements
  2903. along to make room.
  2904. @param indexToInsertAt the index at which the new element should be
  2905. inserted (pass in -1 to add it to the end)
  2906. @param newElement the new object to add to the array
  2907. @see add, addSorted, addUsingDefaultSort, set
  2908. */
  2909. void insert (int indexToInsertAt, ParameterType newElement)
  2910. {
  2911. const ScopedLockType lock (getLock());
  2912. data.ensureAllocatedSize (numUsed + 1);
  2913. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2914. {
  2915. ElementType* const insertPos = data.elements + indexToInsertAt;
  2916. const int numberToMove = numUsed - indexToInsertAt;
  2917. if (numberToMove > 0)
  2918. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  2919. new (insertPos) ElementType (newElement);
  2920. ++numUsed;
  2921. }
  2922. else
  2923. {
  2924. new (data.elements + numUsed++) ElementType (newElement);
  2925. }
  2926. }
  2927. /** Inserts multiple copies of an element into the array at a given position.
  2928. If the index is less than 0 or greater than the size of the array, the
  2929. element will be added to the end of the array.
  2930. Otherwise, it will be inserted into the array, moving all the later elements
  2931. along to make room.
  2932. @param indexToInsertAt the index at which the new element should be inserted
  2933. @param newElement the new object to add to the array
  2934. @param numberOfTimesToInsertIt how many copies of the value to insert
  2935. @see insert, add, addSorted, set
  2936. */
  2937. void insertMultiple (int indexToInsertAt, ParameterType newElement,
  2938. int numberOfTimesToInsertIt)
  2939. {
  2940. if (numberOfTimesToInsertIt > 0)
  2941. {
  2942. const ScopedLockType lock (getLock());
  2943. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  2944. ElementType* insertPos;
  2945. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2946. {
  2947. insertPos = data.elements + indexToInsertAt;
  2948. const int numberToMove = numUsed - indexToInsertAt;
  2949. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  2950. }
  2951. else
  2952. {
  2953. insertPos = data.elements + numUsed;
  2954. }
  2955. numUsed += numberOfTimesToInsertIt;
  2956. while (--numberOfTimesToInsertIt >= 0)
  2957. new (insertPos++) ElementType (newElement);
  2958. }
  2959. }
  2960. /** Inserts an array of values into this array at a given position.
  2961. If the index is less than 0 or greater than the size of the array, the
  2962. new elements will be added to the end of the array.
  2963. Otherwise, they will be inserted into the array, moving all the later elements
  2964. along to make room.
  2965. @param indexToInsertAt the index at which the first new element should be inserted
  2966. @param newElements the new values to add to the array
  2967. @param numberOfElements how many items are in the array
  2968. @see insert, add, addSorted, set
  2969. */
  2970. void insertArray (int indexToInsertAt,
  2971. const ElementType* newElements,
  2972. int numberOfElements)
  2973. {
  2974. if (numberOfElements > 0)
  2975. {
  2976. const ScopedLockType lock (getLock());
  2977. data.ensureAllocatedSize (numUsed + numberOfElements);
  2978. ElementType* insertPos;
  2979. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2980. {
  2981. insertPos = data.elements + indexToInsertAt;
  2982. const int numberToMove = numUsed - indexToInsertAt;
  2983. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  2984. }
  2985. else
  2986. {
  2987. insertPos = data.elements + numUsed;
  2988. }
  2989. numUsed += numberOfElements;
  2990. while (--numberOfElements >= 0)
  2991. new (insertPos++) ElementType (*newElements++);
  2992. }
  2993. }
  2994. /** Appends a new element at the end of the array as long as the array doesn't
  2995. already contain it.
  2996. If the array already contains an element that matches the one passed in, nothing
  2997. will be done.
  2998. @param newElement the new object to add to the array
  2999. */
  3000. void addIfNotAlreadyThere (ParameterType newElement)
  3001. {
  3002. const ScopedLockType lock (getLock());
  3003. if (! contains (newElement))
  3004. add (newElement);
  3005. }
  3006. /** Replaces an element with a new value.
  3007. If the index is less than zero, this method does nothing.
  3008. If the index is beyond the end of the array, the item is added to the end of the array.
  3009. @param indexToChange the index whose value you want to change
  3010. @param newValue the new value to set for this index.
  3011. @see add, insert
  3012. */
  3013. void set (const int indexToChange, ParameterType newValue)
  3014. {
  3015. jassert (indexToChange >= 0);
  3016. const ScopedLockType lock (getLock());
  3017. if (((unsigned int) indexToChange) < (unsigned int) numUsed)
  3018. {
  3019. data.elements [indexToChange] = newValue;
  3020. }
  3021. else if (indexToChange >= 0)
  3022. {
  3023. data.ensureAllocatedSize (numUsed + 1);
  3024. new (data.elements + numUsed++) ElementType (newValue);
  3025. }
  3026. }
  3027. /** Replaces an element with a new value without doing any bounds-checking.
  3028. This just sets a value directly in the array's internal storage, so you'd
  3029. better make sure it's in range!
  3030. @param indexToChange the index whose value you want to change
  3031. @param newValue the new value to set for this index.
  3032. @see set, getUnchecked
  3033. */
  3034. void setUnchecked (const int indexToChange, ParameterType newValue)
  3035. {
  3036. const ScopedLockType lock (getLock());
  3037. jassert (((unsigned int) indexToChange) < (unsigned int) numUsed);
  3038. data.elements [indexToChange] = newValue;
  3039. }
  3040. /** Adds elements from an array to the end of this array.
  3041. @param elementsToAdd the array of elements to add
  3042. @param numElementsToAdd how many elements are in this other array
  3043. @see add
  3044. */
  3045. void addArray (const ElementType* elementsToAdd, int numElementsToAdd)
  3046. {
  3047. const ScopedLockType lock (getLock());
  3048. if (numElementsToAdd > 0)
  3049. {
  3050. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  3051. while (--numElementsToAdd >= 0)
  3052. {
  3053. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  3054. ++numUsed;
  3055. }
  3056. }
  3057. }
  3058. /** This swaps the contents of this array with those of another array.
  3059. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  3060. because it just swaps their internal pointers.
  3061. */
  3062. void swapWithArray (Array& otherArray) throw()
  3063. {
  3064. const ScopedLockType lock1 (getLock());
  3065. const ScopedLockType lock2 (otherArray.getLock());
  3066. data.swapWith (otherArray.data);
  3067. swapVariables (numUsed, otherArray.numUsed);
  3068. }
  3069. /** Adds elements from another array to the end of this array.
  3070. @param arrayToAddFrom the array from which to copy the elements
  3071. @param startIndex the first element of the other array to start copying from
  3072. @param numElementsToAdd how many elements to add from the other array. If this
  3073. value is negative or greater than the number of available elements,
  3074. all available elements will be copied.
  3075. @see add
  3076. */
  3077. template <class OtherArrayType>
  3078. void addArray (const OtherArrayType& arrayToAddFrom,
  3079. int startIndex = 0,
  3080. int numElementsToAdd = -1)
  3081. {
  3082. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  3083. const ScopedLockType lock2 (getLock());
  3084. if (startIndex < 0)
  3085. {
  3086. jassertfalse;
  3087. startIndex = 0;
  3088. }
  3089. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  3090. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  3091. while (--numElementsToAdd >= 0)
  3092. add (arrayToAddFrom.getUnchecked (startIndex++));
  3093. }
  3094. /** Inserts a new element into the array, assuming that the array is sorted.
  3095. This will use a comparator to find the position at which the new element
  3096. should go. If the array isn't sorted, the behaviour of this
  3097. method will be unpredictable.
  3098. @param comparator the comparator to use to compare the elements - see the sort()
  3099. method for details about the form this object should take
  3100. @param newElement the new element to insert to the array
  3101. @see addUsingDefaultSort, add, sort
  3102. */
  3103. template <class ElementComparator>
  3104. void addSorted (ElementComparator& comparator, ParameterType newElement)
  3105. {
  3106. const ScopedLockType lock (getLock());
  3107. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed), newElement);
  3108. }
  3109. /** Inserts a new element into the array, assuming that the array is sorted.
  3110. This will use the DefaultElementComparator class for sorting, so your ElementType
  3111. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  3112. method will be unpredictable.
  3113. @param newElement the new element to insert to the array
  3114. @see addSorted, sort
  3115. */
  3116. void addUsingDefaultSort (ParameterType newElement)
  3117. {
  3118. DefaultElementComparator <ElementType> comparator;
  3119. addSorted (comparator, newElement);
  3120. }
  3121. /** Finds the index of an element in the array, assuming that the array is sorted.
  3122. This will use a comparator to do a binary-chop to find the index of the given
  3123. element, if it exists. If the array isn't sorted, the behaviour of this
  3124. method will be unpredictable.
  3125. @param comparator the comparator to use to compare the elements - see the sort()
  3126. method for details about the form this object should take
  3127. @param elementToLookFor the element to search for
  3128. @returns the index of the element, or -1 if it's not found
  3129. @see addSorted, sort
  3130. */
  3131. template <class ElementComparator>
  3132. int indexOfSorted (ElementComparator& comparator, ParameterType elementToLookFor) const
  3133. {
  3134. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3135. // avoids getting warning messages about the parameter being unused
  3136. const ScopedLockType lock (getLock());
  3137. int start = 0;
  3138. int end = numUsed;
  3139. for (;;)
  3140. {
  3141. if (start >= end)
  3142. {
  3143. return -1;
  3144. }
  3145. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  3146. {
  3147. return start;
  3148. }
  3149. else
  3150. {
  3151. const int halfway = (start + end) >> 1;
  3152. if (halfway == start)
  3153. return -1;
  3154. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  3155. start = halfway;
  3156. else
  3157. end = halfway;
  3158. }
  3159. }
  3160. }
  3161. /** Removes an element from the array.
  3162. This will remove the element at a given index, and move back
  3163. all the subsequent elements to close the gap.
  3164. If the index passed in is out-of-range, nothing will happen.
  3165. @param indexToRemove the index of the element to remove
  3166. @returns the element that has been removed
  3167. @see removeValue, removeRange
  3168. */
  3169. ElementType remove (const int indexToRemove)
  3170. {
  3171. const ScopedLockType lock (getLock());
  3172. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  3173. {
  3174. --numUsed;
  3175. ElementType* const e = data.elements + indexToRemove;
  3176. ElementType removed (*e);
  3177. e->~ElementType();
  3178. const int numberToShift = numUsed - indexToRemove;
  3179. if (numberToShift > 0)
  3180. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  3181. if ((numUsed << 1) < data.numAllocated)
  3182. minimiseStorageOverheads();
  3183. return removed;
  3184. }
  3185. else
  3186. {
  3187. return ElementType();
  3188. }
  3189. }
  3190. /** Removes an item from the array.
  3191. This will remove the first occurrence of the given element from the array.
  3192. If the item isn't found, no action is taken.
  3193. @param valueToRemove the object to try to remove
  3194. @see remove, removeRange
  3195. */
  3196. void removeValue (ParameterType valueToRemove)
  3197. {
  3198. const ScopedLockType lock (getLock());
  3199. ElementType* e = data.elements;
  3200. for (int i = numUsed; --i >= 0;)
  3201. {
  3202. if (valueToRemove == *e)
  3203. {
  3204. remove (static_cast <int> (e - data.elements.getData()));
  3205. break;
  3206. }
  3207. ++e;
  3208. }
  3209. }
  3210. /** Removes a range of elements from the array.
  3211. This will remove a set of elements, starting from the given index,
  3212. and move subsequent elements down to close the gap.
  3213. If the range extends beyond the bounds of the array, it will
  3214. be safely clipped to the size of the array.
  3215. @param startIndex the index of the first element to remove
  3216. @param numberToRemove how many elements should be removed
  3217. @see remove, removeValue
  3218. */
  3219. void removeRange (int startIndex, int numberToRemove)
  3220. {
  3221. const ScopedLockType lock (getLock());
  3222. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  3223. startIndex = jlimit (0, numUsed, startIndex);
  3224. if (endIndex > startIndex)
  3225. {
  3226. ElementType* const e = data.elements + startIndex;
  3227. numberToRemove = endIndex - startIndex;
  3228. for (int i = 0; i < numberToRemove; ++i)
  3229. e[i].~ElementType();
  3230. const int numToShift = numUsed - endIndex;
  3231. if (numToShift > 0)
  3232. memmove (e, e + numberToRemove, numToShift * sizeof (ElementType));
  3233. numUsed -= numberToRemove;
  3234. if ((numUsed << 1) < data.numAllocated)
  3235. minimiseStorageOverheads();
  3236. }
  3237. }
  3238. /** Removes the last n elements from the array.
  3239. @param howManyToRemove how many elements to remove from the end of the array
  3240. @see remove, removeValue, removeRange
  3241. */
  3242. void removeLast (int howManyToRemove = 1)
  3243. {
  3244. const ScopedLockType lock (getLock());
  3245. if (howManyToRemove > numUsed)
  3246. howManyToRemove = numUsed;
  3247. for (int i = 0; i < howManyToRemove; ++i)
  3248. data.elements [numUsed - i].~ElementType();
  3249. numUsed -= howManyToRemove;
  3250. if ((numUsed << 1) < data.numAllocated)
  3251. minimiseStorageOverheads();
  3252. }
  3253. /** Removes any elements which are also in another array.
  3254. @param otherArray the other array in which to look for elements to remove
  3255. @see removeValuesNotIn, remove, removeValue, removeRange
  3256. */
  3257. template <class OtherArrayType>
  3258. void removeValuesIn (const OtherArrayType& otherArray)
  3259. {
  3260. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  3261. const ScopedLockType lock2 (getLock());
  3262. if (this == &otherArray)
  3263. {
  3264. clear();
  3265. }
  3266. else
  3267. {
  3268. if (otherArray.size() > 0)
  3269. {
  3270. for (int i = numUsed; --i >= 0;)
  3271. if (otherArray.contains (data.elements [i]))
  3272. remove (i);
  3273. }
  3274. }
  3275. }
  3276. /** Removes any elements which are not found in another array.
  3277. Only elements which occur in this other array will be retained.
  3278. @param otherArray the array in which to look for elements NOT to remove
  3279. @see removeValuesIn, remove, removeValue, removeRange
  3280. */
  3281. template <class OtherArrayType>
  3282. void removeValuesNotIn (const OtherArrayType& otherArray)
  3283. {
  3284. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  3285. const ScopedLockType lock2 (getLock());
  3286. if (this != &otherArray)
  3287. {
  3288. if (otherArray.size() <= 0)
  3289. {
  3290. clear();
  3291. }
  3292. else
  3293. {
  3294. for (int i = numUsed; --i >= 0;)
  3295. if (! otherArray.contains (data.elements [i]))
  3296. remove (i);
  3297. }
  3298. }
  3299. }
  3300. /** Swaps over two elements in the array.
  3301. This swaps over the elements found at the two indexes passed in.
  3302. If either index is out-of-range, this method will do nothing.
  3303. @param index1 index of one of the elements to swap
  3304. @param index2 index of the other element to swap
  3305. */
  3306. void swap (const int index1,
  3307. const int index2)
  3308. {
  3309. const ScopedLockType lock (getLock());
  3310. if (((unsigned int) index1) < (unsigned int) numUsed
  3311. && ((unsigned int) index2) < (unsigned int) numUsed)
  3312. {
  3313. swapVariables (data.elements [index1],
  3314. data.elements [index2]);
  3315. }
  3316. }
  3317. /** Moves one of the values to a different position.
  3318. This will move the value to a specified index, shuffling along
  3319. any intervening elements as required.
  3320. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  3321. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  3322. @param currentIndex the index of the value to be moved. If this isn't a
  3323. valid index, then nothing will be done
  3324. @param newIndex the index at which you'd like this value to end up. If this
  3325. is less than zero, the value will be moved to the end
  3326. of the array
  3327. */
  3328. void move (const int currentIndex, int newIndex) throw()
  3329. {
  3330. if (currentIndex != newIndex)
  3331. {
  3332. const ScopedLockType lock (getLock());
  3333. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  3334. {
  3335. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  3336. newIndex = numUsed - 1;
  3337. char tempCopy [sizeof (ElementType)];
  3338. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  3339. if (newIndex > currentIndex)
  3340. {
  3341. memmove (data.elements + currentIndex,
  3342. data.elements + currentIndex + 1,
  3343. (newIndex - currentIndex) * sizeof (ElementType));
  3344. }
  3345. else
  3346. {
  3347. memmove (data.elements + newIndex + 1,
  3348. data.elements + newIndex,
  3349. (currentIndex - newIndex) * sizeof (ElementType));
  3350. }
  3351. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  3352. }
  3353. }
  3354. }
  3355. /** Reduces the amount of storage being used by the array.
  3356. Arrays typically allocate slightly more storage than they need, and after
  3357. removing elements, they may have quite a lot of unused space allocated.
  3358. This method will reduce the amount of allocated storage to a minimum.
  3359. */
  3360. void minimiseStorageOverheads()
  3361. {
  3362. const ScopedLockType lock (getLock());
  3363. data.shrinkToNoMoreThan (numUsed);
  3364. }
  3365. /** Increases the array's internal storage to hold a minimum number of elements.
  3366. Calling this before adding a large known number of elements means that
  3367. the array won't have to keep dynamically resizing itself as the elements
  3368. are added, and it'll therefore be more efficient.
  3369. */
  3370. void ensureStorageAllocated (const int minNumElements)
  3371. {
  3372. const ScopedLockType lock (getLock());
  3373. data.ensureAllocatedSize (minNumElements);
  3374. }
  3375. /** Sorts the elements in the array.
  3376. This will use a comparator object to sort the elements into order. The object
  3377. passed must have a method of the form:
  3378. @code
  3379. int compareElements (ElementType first, ElementType second);
  3380. @endcode
  3381. ..and this method must return:
  3382. - a value of < 0 if the first comes before the second
  3383. - a value of 0 if the two objects are equivalent
  3384. - a value of > 0 if the second comes before the first
  3385. To improve performance, the compareElements() method can be declared as static or const.
  3386. @param comparator the comparator to use for comparing elements.
  3387. @param retainOrderOfEquivalentItems if this is true, then items
  3388. which the comparator says are equivalent will be
  3389. kept in the order in which they currently appear
  3390. in the array. This is slower to perform, but may
  3391. be important in some cases. If it's false, a faster
  3392. algorithm is used, but equivalent elements may be
  3393. rearranged.
  3394. @see addSorted, indexOfSorted, sortArray
  3395. */
  3396. template <class ElementComparator>
  3397. void sort (ElementComparator& comparator,
  3398. const bool retainOrderOfEquivalentItems = false) const
  3399. {
  3400. const ScopedLockType lock (getLock());
  3401. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3402. // avoids getting warning messages about the parameter being unused
  3403. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  3404. }
  3405. /** Returns the CriticalSection that locks this array.
  3406. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  3407. an object of ScopedLockType as an RAII lock for it.
  3408. */
  3409. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  3410. /** Returns the type of scoped lock to use for locking this array */
  3411. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  3412. juce_UseDebuggingNewOperator
  3413. private:
  3414. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  3415. int numUsed;
  3416. };
  3417. #endif // __JUCE_ARRAY_JUCEHEADER__
  3418. /*** End of inlined file: juce_Array.h ***/
  3419. #endif
  3420. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  3421. #endif
  3422. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  3423. /*** Start of inlined file: juce_BigInteger.h ***/
  3424. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  3425. #define __JUCE_BIGINTEGER_JUCEHEADER__
  3426. class MemoryBlock;
  3427. /**
  3428. An arbitrarily large integer class.
  3429. A BigInteger can be used in a similar way to a normal integer, but has no size
  3430. limit (except for memory and performance constraints).
  3431. Negative values are possible, but the value isn't stored as 2s-complement, so
  3432. be careful if you use negative values and look at the values of individual bits.
  3433. */
  3434. class JUCE_API BigInteger
  3435. {
  3436. public:
  3437. /** Creates an empty BigInteger */
  3438. BigInteger();
  3439. /** Creates a BigInteger containing an integer value in its low bits.
  3440. The low 32 bits of the number are initialised with this value.
  3441. */
  3442. BigInteger (unsigned int value);
  3443. /** Creates a BigInteger containing an integer value in its low bits.
  3444. The low 32 bits of the number are initialised with the absolute value
  3445. passed in, and its sign is set to reflect the sign of the number.
  3446. */
  3447. BigInteger (int value);
  3448. /** Creates a BigInteger containing an integer value in its low bits.
  3449. The low 64 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 (int64 value);
  3453. /** Creates a copy of another BigInteger. */
  3454. BigInteger (const BigInteger& other);
  3455. /** Destructor. */
  3456. ~BigInteger();
  3457. /** Copies another BigInteger onto this one. */
  3458. BigInteger& operator= (const BigInteger& other);
  3459. /** Swaps the internal contents of this with another object. */
  3460. void swapWith (BigInteger& other) throw();
  3461. /** Returns the value of a specified bit in the number.
  3462. If the index is out-of-range, the result will be false.
  3463. */
  3464. bool operator[] (int bit) const throw();
  3465. /** Returns true if no bits are set. */
  3466. bool isZero() const throw();
  3467. /** Returns true if the value is 1. */
  3468. bool isOne() const throw();
  3469. /** Attempts to get the lowest bits of the value as an integer.
  3470. If the value is bigger than the integer limits, this will return only the lower bits.
  3471. */
  3472. int toInteger() const throw();
  3473. /** Resets the value to 0. */
  3474. void clear();
  3475. /** Clears a particular bit in the number. */
  3476. void clearBit (int bitNumber) throw();
  3477. /** Sets a specified bit to 1. */
  3478. void setBit (int bitNumber);
  3479. /** Sets or clears a specified bit. */
  3480. void setBit (int bitNumber, bool shouldBeSet);
  3481. /** Sets a range of bits to be either on or off.
  3482. @param startBit the first bit to change
  3483. @param numBits the number of bits to change
  3484. @param shouldBeSet whether to turn these bits on or off
  3485. */
  3486. void setRange (int startBit, int numBits, bool shouldBeSet);
  3487. /** Inserts a bit an a given position, shifting up any bits above it. */
  3488. void insertBit (int bitNumber, bool shouldBeSet);
  3489. /** Returns a range of bits as a new BigInteger.
  3490. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  3491. @see getBitRangeAsInt
  3492. */
  3493. const BigInteger getBitRange (int startBit, int numBits) const;
  3494. /** Returns a range of bits as an integer value.
  3495. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  3496. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  3497. getBitRange().
  3498. */
  3499. int getBitRangeAsInt (int startBit, int numBits) const throw();
  3500. /** Sets a range of bits to an integer value.
  3501. Copies the given integer onto a range of bits, starting at startBit,
  3502. and using up to numBits of the available bits.
  3503. */
  3504. void setBitRangeAsInt (int startBit, int numBits, unsigned int valueToSet);
  3505. /** Shifts a section of bits left or right.
  3506. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  3507. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  3508. */
  3509. void shiftBits (int howManyBitsLeft, int startBit);
  3510. /** Returns the total number of set bits in the value. */
  3511. int countNumberOfSetBits() const throw();
  3512. /** Looks for the index of the next set bit after a given starting point.
  3513. This searches from startIndex (inclusive) upwards for the first set bit,
  3514. and returns its index. If no set bits are found, it returns -1.
  3515. */
  3516. int findNextSetBit (int startIndex = 0) const throw();
  3517. /** Looks for the index of the next clear bit after a given starting point.
  3518. This searches from startIndex (inclusive) upwards for the first clear bit,
  3519. and returns its index.
  3520. */
  3521. int findNextClearBit (int startIndex = 0) const throw();
  3522. /** Returns the index of the highest set bit in the number.
  3523. If the value is zero, this will return -1.
  3524. */
  3525. int getHighestBit() const throw();
  3526. // All the standard arithmetic ops...
  3527. BigInteger& operator+= (const BigInteger& other);
  3528. BigInteger& operator-= (const BigInteger& other);
  3529. BigInteger& operator*= (const BigInteger& other);
  3530. BigInteger& operator/= (const BigInteger& other);
  3531. BigInteger& operator|= (const BigInteger& other);
  3532. BigInteger& operator&= (const BigInteger& other);
  3533. BigInteger& operator^= (const BigInteger& other);
  3534. BigInteger& operator%= (const BigInteger& other);
  3535. BigInteger& operator<<= (int numBitsToShift);
  3536. BigInteger& operator>>= (int numBitsToShift);
  3537. BigInteger& operator++();
  3538. BigInteger& operator--();
  3539. const BigInteger operator++ (int);
  3540. const BigInteger operator-- (int);
  3541. const BigInteger operator-() const;
  3542. const BigInteger operator+ (const BigInteger& other) const;
  3543. const BigInteger operator- (const BigInteger& other) const;
  3544. const BigInteger operator* (const BigInteger& other) const;
  3545. const BigInteger operator/ (const BigInteger& other) const;
  3546. const BigInteger operator| (const BigInteger& other) const;
  3547. const BigInteger operator& (const BigInteger& other) const;
  3548. const BigInteger operator^ (const BigInteger& other) const;
  3549. const BigInteger operator% (const BigInteger& other) const;
  3550. const BigInteger operator<< (int numBitsToShift) const;
  3551. const BigInteger operator>> (int numBitsToShift) const;
  3552. bool operator== (const BigInteger& other) const throw();
  3553. bool operator!= (const BigInteger& other) const throw();
  3554. bool operator< (const BigInteger& other) const throw();
  3555. bool operator<= (const BigInteger& other) const throw();
  3556. bool operator> (const BigInteger& other) const throw();
  3557. bool operator>= (const BigInteger& other) const throw();
  3558. /** Does a signed comparison of two BigIntegers.
  3559. Return values are:
  3560. - 0 if the numbers are the same
  3561. - < 0 if this number is smaller than the other
  3562. - > 0 if this number is bigger than the other
  3563. */
  3564. int compare (const BigInteger& other) const throw();
  3565. /** Compares the magnitudes of two BigIntegers, ignoring their signs.
  3566. Return values are:
  3567. - 0 if the numbers are the same
  3568. - < 0 if this number is smaller than the other
  3569. - > 0 if this number is bigger than the other
  3570. */
  3571. int compareAbsolute (const BigInteger& other) const throw();
  3572. /** Divides this value by another one and returns the remainder.
  3573. This number is divided by other, leaving the quotient in this number,
  3574. with the remainder being copied to the other BigInteger passed in.
  3575. */
  3576. void divideBy (const BigInteger& divisor, BigInteger& remainder);
  3577. /** Returns the largest value that will divide both this value and the one passed-in.
  3578. */
  3579. const BigInteger findGreatestCommonDivisor (BigInteger other) const;
  3580. /** Performs a combined exponent and modulo operation.
  3581. This BigInteger's value becomes (this ^ exponent) % modulus.
  3582. */
  3583. void exponentModulo (const BigInteger& exponent, const BigInteger& modulus);
  3584. /** Performs an inverse modulo on the value.
  3585. i.e. the result is (this ^ -1) mod (modulus).
  3586. */
  3587. void inverseModulo (const BigInteger& modulus);
  3588. /** Returns true if the value is less than zero.
  3589. @see setNegative, negate
  3590. */
  3591. bool isNegative() const throw();
  3592. /** Changes the sign of the number to be positive or negative.
  3593. @see isNegative, negate
  3594. */
  3595. void setNegative (const bool shouldBeNegative) throw();
  3596. /** Inverts the sign of the number.
  3597. @see isNegative, setNegative
  3598. */
  3599. void negate() throw();
  3600. /** Converts the number to a string.
  3601. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  3602. If minimumNumCharacters is greater than 0, the returned string will be
  3603. padded with leading zeros to reach at least that length.
  3604. */
  3605. const String toString (int base, int minimumNumCharacters = 1) const;
  3606. /** Reads the numeric value from a string.
  3607. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  3608. Any invalid characters will be ignored.
  3609. */
  3610. void parseString (const String& text, int base);
  3611. /** Turns the number into a block of binary data.
  3612. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  3613. of the number, and so on.
  3614. @see loadFromMemoryBlock
  3615. */
  3616. const MemoryBlock toMemoryBlock() const;
  3617. /** Converts a block of raw data into a number.
  3618. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  3619. of the number, and so on.
  3620. @see toMemoryBlock
  3621. */
  3622. void loadFromMemoryBlock (const MemoryBlock& data);
  3623. juce_UseDebuggingNewOperator
  3624. private:
  3625. HeapBlock <unsigned int> values;
  3626. int numValues, highestBit;
  3627. bool negative;
  3628. void ensureSize (int numVals);
  3629. static const BigInteger simpleGCD (BigInteger* m, BigInteger* n);
  3630. };
  3631. /** Writes a BigInteger to an OutputStream as a UTF8 decimal string. */
  3632. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value);
  3633. /** For backwards compatibility, BitArray is defined to be an alias for BigInteger.
  3634. */
  3635. typedef BigInteger BitArray;
  3636. #endif // __JUCE_BIGINTEGER_JUCEHEADER__
  3637. /*** End of inlined file: juce_BigInteger.h ***/
  3638. #endif
  3639. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  3640. /*** Start of inlined file: juce_DynamicObject.h ***/
  3641. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  3642. #define __JUCE_DYNAMICOBJECT_JUCEHEADER__
  3643. /*** Start of inlined file: juce_NamedValueSet.h ***/
  3644. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  3645. #define __JUCE_NAMEDVALUESET_JUCEHEADER__
  3646. /*** Start of inlined file: juce_Variant.h ***/
  3647. #ifndef __JUCE_VARIANT_JUCEHEADER__
  3648. #define __JUCE_VARIANT_JUCEHEADER__
  3649. /*** Start of inlined file: juce_Identifier.h ***/
  3650. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  3651. #define __JUCE_IDENTIFIER_JUCEHEADER__
  3652. /*** Start of inlined file: juce_StringPool.h ***/
  3653. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  3654. #define __JUCE_STRINGPOOL_JUCEHEADER__
  3655. /**
  3656. A StringPool holds a set of shared strings, which reduces storage overheads and improves
  3657. comparison speed when dealing with many duplicate strings.
  3658. When you add a string to a pool using getPooledString, it'll return a character
  3659. array containing the same string. This array is owned by the pool, and the same array
  3660. is returned every time a matching string is asked for. This means that it's trivial to
  3661. compare two pooled strings for equality, as you can simply compare their pointers. It
  3662. also cuts down on storage if you're using many copies of the same string.
  3663. */
  3664. class JUCE_API StringPool
  3665. {
  3666. public:
  3667. /** Creates an empty pool. */
  3668. StringPool() throw();
  3669. /** Destructor */
  3670. ~StringPool();
  3671. /** Returns a pointer to a copy of the string that is passed in.
  3672. The pool will always return the same pointer when asked for a string that matches it.
  3673. The pool will own all the pointers that it returns, deleting them when the pool itself
  3674. is deleted.
  3675. */
  3676. const juce_wchar* getPooledString (const String& original);
  3677. /** Returns a pointer to a copy of the string that is passed in.
  3678. The pool will always return the same pointer when asked for a string that matches it.
  3679. The pool will own all the pointers that it returns, deleting them when the pool itself
  3680. is deleted.
  3681. */
  3682. const juce_wchar* getPooledString (const char* original);
  3683. /** Returns a pointer to a copy of the string that is passed in.
  3684. The pool will always return the same pointer when asked for a string that matches it.
  3685. The pool will own all the pointers that it returns, deleting them when the pool itself
  3686. is deleted.
  3687. */
  3688. const juce_wchar* getPooledString (const juce_wchar* original);
  3689. /** Returns the number of strings in the pool. */
  3690. int size() const throw();
  3691. /** Returns one of the strings in the pool, by index. */
  3692. const juce_wchar* operator[] (int index) const throw();
  3693. private:
  3694. Array <String> strings;
  3695. };
  3696. #endif // __JUCE_STRINGPOOL_JUCEHEADER__
  3697. /*** End of inlined file: juce_StringPool.h ***/
  3698. /**
  3699. Represents a string identifier, designed for accessing properties by name.
  3700. Identifier objects are very light and fast to copy, but slower to initialise
  3701. from a string, so it's much faster to keep a static identifier object to refer
  3702. to frequently-used names, rather than constructing them each time you need it.
  3703. @see NamedPropertySet, ValueTree
  3704. */
  3705. class JUCE_API Identifier
  3706. {
  3707. public:
  3708. /** Creates a null identifier. */
  3709. Identifier() throw();
  3710. /** Creates an identifier with a specified name.
  3711. Because this name may need to be used in contexts such as script variables or XML
  3712. tags, it must only contain ascii letters and digits, or the underscore character.
  3713. */
  3714. Identifier (const char* name);
  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 String& name);
  3720. /** Creates a copy of another identifier. */
  3721. Identifier (const Identifier& other) throw();
  3722. /** Creates a copy of another identifier. */
  3723. Identifier& operator= (const Identifier& other) throw();
  3724. /** Destructor */
  3725. ~Identifier();
  3726. /** Compares two identifiers. This is a very fast operation. */
  3727. inline bool operator== (const Identifier& other) const throw() { return name == other.name; }
  3728. /** Compares two identifiers. This is a very fast operation. */
  3729. inline bool operator!= (const Identifier& other) const throw() { return name != other.name; }
  3730. /** Returns this identifier as a string. */
  3731. const String toString() const { return name; }
  3732. /** Returns this identifier's raw string pointer. */
  3733. operator const juce_wchar*() const throw() { return name; }
  3734. private:
  3735. const juce_wchar* name;
  3736. static StringPool& getPool();
  3737. };
  3738. #endif // __JUCE_IDENTIFIER_JUCEHEADER__
  3739. /*** End of inlined file: juce_Identifier.h ***/
  3740. /*** Start of inlined file: juce_OutputStream.h ***/
  3741. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  3742. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  3743. /*** Start of inlined file: juce_InputStream.h ***/
  3744. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  3745. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  3746. /*** Start of inlined file: juce_MemoryBlock.h ***/
  3747. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  3748. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  3749. /**
  3750. A class to hold a resizable block of raw data.
  3751. */
  3752. class JUCE_API MemoryBlock
  3753. {
  3754. public:
  3755. /** Create an uninitialised block with 0 size. */
  3756. MemoryBlock() throw();
  3757. /** Creates a memory block with a given initial size.
  3758. @param initialSize the size of block to create
  3759. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  3760. */
  3761. MemoryBlock (const size_t initialSize,
  3762. const bool initialiseToZero = false) throw();
  3763. /** Creates a copy of another memory block. */
  3764. MemoryBlock (const MemoryBlock& other) throw();
  3765. /** Creates a memory block using a copy of a block of data.
  3766. @param dataToInitialiseFrom some data to copy into this block
  3767. @param sizeInBytes how much space to use
  3768. */
  3769. MemoryBlock (const void* const dataToInitialiseFrom,
  3770. const size_t sizeInBytes) throw();
  3771. /** Destructor. */
  3772. ~MemoryBlock() throw();
  3773. /** Copies another memory block onto this one.
  3774. This block will be resized and copied to exactly match the other one.
  3775. */
  3776. MemoryBlock& operator= (const MemoryBlock& other) throw();
  3777. /** Compares two memory blocks.
  3778. @returns true only if the two blocks are the same size and have identical contents.
  3779. */
  3780. bool operator== (const MemoryBlock& other) const throw();
  3781. /** Compares two memory blocks.
  3782. @returns true if the two blocks are different sizes or have different contents.
  3783. */
  3784. bool operator!= (const MemoryBlock& other) const throw();
  3785. /** Returns true if the data in this MemoryBlock matches the raw bytes passed-in.
  3786. */
  3787. bool matches (const void* data, size_t dataSize) const throw();
  3788. /** Returns a void pointer to the data.
  3789. Note that the pointer returned will probably become invalid when the
  3790. block is resized.
  3791. */
  3792. void* getData() const throw() { return data; }
  3793. /** Returns a byte from the memory block.
  3794. This returns a reference, so you can also use it to set a byte.
  3795. */
  3796. template <typename Type>
  3797. char& operator[] (const Type offset) const throw() { return data [offset]; }
  3798. /** Returns the block's current allocated size, in bytes. */
  3799. size_t getSize() const throw() { return size; }
  3800. /** Resizes the memory block.
  3801. This will try to keep as much of the block's current content as it can,
  3802. and can optionally be made to clear any new space that gets allocated at
  3803. the end of the block.
  3804. @param newSize the new desired size for the block
  3805. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  3806. whether to clear the new section or just leave it
  3807. uninitialised
  3808. @see ensureSize
  3809. */
  3810. void setSize (const size_t newSize,
  3811. const bool initialiseNewSpaceToZero = false) throw();
  3812. /** Increases the block's size only if it's smaller than a given size.
  3813. @param minimumSize if the block is already bigger than this size, no action
  3814. will be taken; otherwise it will be increased to this size
  3815. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  3816. whether to clear the new section or just leave it
  3817. uninitialised
  3818. @see setSize
  3819. */
  3820. void ensureSize (const size_t minimumSize,
  3821. const bool initialiseNewSpaceToZero = false) throw();
  3822. /** Fills the entire memory block with a repeated byte value.
  3823. This is handy for clearing a block of memory to zero.
  3824. */
  3825. void fillWith (const uint8 valueToUse) throw();
  3826. /** Adds another block of data to the end of this one.
  3827. This block's size will be increased accordingly.
  3828. */
  3829. void append (const void* const data,
  3830. const size_t numBytes) throw();
  3831. /** Exchanges the contents of this and another memory block.
  3832. No actual copying is required for this, so it's very fast.
  3833. */
  3834. void swapWith (MemoryBlock& other) throw();
  3835. /** Copies data into this MemoryBlock from a memory address.
  3836. @param srcData the memory location of the data to copy into this block
  3837. @param destinationOffset the offset in this block at which the data being copied should begin
  3838. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  3839. it will be clipped so not to do anything nasty)
  3840. */
  3841. void copyFrom (const void* srcData,
  3842. int destinationOffset,
  3843. size_t numBytes) throw();
  3844. /** Copies data from this MemoryBlock to a memory address.
  3845. @param destData the memory location to write to
  3846. @param sourceOffset the offset within this block from which the copied data will be read
  3847. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  3848. zeros will be used for that portion of the data)
  3849. */
  3850. void copyTo (void* destData,
  3851. int sourceOffset,
  3852. size_t numBytes) const throw();
  3853. /** Chops out a section of the block.
  3854. This will remove a section of the memory block and close the gap around it,
  3855. shifting any subsequent data downwards and reducing the size of the block.
  3856. If the range specified goes beyond the size of the block, it will be clipped.
  3857. */
  3858. void removeSection (size_t startByte, size_t numBytesToRemove) throw();
  3859. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  3860. characters in the system's default encoding. */
  3861. const String toString() const throw();
  3862. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  3863. The block will be resized to the number of valid bytes read from the string.
  3864. Non-hex characters in the string will be ignored.
  3865. @see String::toHexString()
  3866. */
  3867. void loadFromHexString (const String& sourceHexString) throw();
  3868. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  3869. void setBitRange (size_t bitRangeStart,
  3870. size_t numBits,
  3871. int binaryNumberToApply) throw();
  3872. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  3873. int getBitRange (size_t bitRangeStart,
  3874. size_t numBitsToRead) const throw();
  3875. /** Returns a string of characters that represent the binary contents of this block.
  3876. Uses a 64-bit encoding system to allow binary data to be turned into a string
  3877. of simple non-extended characters, e.g. for storage in XML.
  3878. @see fromBase64Encoding
  3879. */
  3880. const String toBase64Encoding() const throw();
  3881. /** Takes a string of encoded characters and turns it into binary data.
  3882. The string passed in must have been created by to64BitEncoding(), and this
  3883. block will be resized to recreate the original data block.
  3884. @see toBase64Encoding
  3885. */
  3886. bool fromBase64Encoding (const String& encodedString) throw();
  3887. juce_UseDebuggingNewOperator
  3888. private:
  3889. HeapBlock <char> data;
  3890. size_t size;
  3891. };
  3892. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  3893. /*** End of inlined file: juce_MemoryBlock.h ***/
  3894. /** The base class for streams that read data.
  3895. Input and output streams are used throughout the library - subclasses can override
  3896. some or all of the virtual functions to implement their behaviour.
  3897. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  3898. */
  3899. class JUCE_API InputStream
  3900. {
  3901. public:
  3902. /** Destructor. */
  3903. virtual ~InputStream() {}
  3904. /** Returns the total number of bytes available for reading in this stream.
  3905. Note that this is the number of bytes available from the start of the
  3906. stream, not from the current position.
  3907. If the size of the stream isn't actually known, this may return -1.
  3908. */
  3909. virtual int64 getTotalLength() = 0;
  3910. /** Returns true if the stream has no more data to read. */
  3911. virtual bool isExhausted() = 0;
  3912. /** Reads a set of bytes from the stream into a memory buffer.
  3913. This is the only read method that subclasses actually need to implement, as the
  3914. InputStream base class implements the other read methods in terms of this one (although
  3915. it's often more efficient for subclasses to implement them directly).
  3916. @param destBuffer the destination buffer for the data
  3917. @param maxBytesToRead the maximum number of bytes to read - make sure the
  3918. memory block passed in is big enough to contain this
  3919. many bytes.
  3920. @returns the actual number of bytes that were read, which may be less than
  3921. maxBytesToRead if the stream is exhausted before it gets that far
  3922. */
  3923. virtual int read (void* destBuffer, int maxBytesToRead) = 0;
  3924. /** Reads a byte from the stream.
  3925. If the stream is exhausted, this will return zero.
  3926. @see OutputStream::writeByte
  3927. */
  3928. virtual char readByte();
  3929. /** Reads a boolean from the stream.
  3930. The bool is encoded as a single byte - 1 for true, 0 for false.
  3931. If the stream is exhausted, this will return false.
  3932. @see OutputStream::writeBool
  3933. */
  3934. virtual bool readBool();
  3935. /** Reads two bytes from the stream as a little-endian 16-bit value.
  3936. If the next two bytes read are byte1 and byte2, this returns
  3937. (byte1 | (byte2 << 8)).
  3938. If the stream is exhausted partway through reading the bytes, this will return zero.
  3939. @see OutputStream::writeShort, readShortBigEndian
  3940. */
  3941. virtual short readShort();
  3942. /** Reads two bytes from the stream as a little-endian 16-bit value.
  3943. If the next two bytes read are byte1 and byte2, this returns
  3944. (byte2 | (byte1 << 8)).
  3945. If the stream is exhausted partway through reading the bytes, this will return zero.
  3946. @see OutputStream::writeShortBigEndian, readShort
  3947. */
  3948. virtual short readShortBigEndian();
  3949. /** Reads four bytes from the stream as a little-endian 32-bit value.
  3950. If the next four bytes are byte1 to byte4, this returns
  3951. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  3952. If the stream is exhausted partway through reading the bytes, this will return zero.
  3953. @see OutputStream::writeInt, readIntBigEndian
  3954. */
  3955. virtual int readInt();
  3956. /** Reads four bytes from the stream as a big-endian 32-bit value.
  3957. If the next four bytes are byte1 to byte4, this returns
  3958. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  3959. If the stream is exhausted partway through reading the bytes, this will return zero.
  3960. @see OutputStream::writeIntBigEndian, readInt
  3961. */
  3962. virtual int readIntBigEndian();
  3963. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  3964. If the next eight bytes are byte1 to byte8, this returns
  3965. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  3966. If the stream is exhausted partway through reading the bytes, this will return zero.
  3967. @see OutputStream::writeInt64, readInt64BigEndian
  3968. */
  3969. virtual int64 readInt64();
  3970. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  3971. If the next eight bytes are byte1 to byte8, this returns
  3972. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  3973. If the stream is exhausted partway through reading the bytes, this will return zero.
  3974. @see OutputStream::writeInt64BigEndian, readInt64
  3975. */
  3976. virtual int64 readInt64BigEndian();
  3977. /** Reads four bytes as a 32-bit floating point value.
  3978. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  3979. If the stream is exhausted partway through reading the bytes, this will return zero.
  3980. @see OutputStream::writeFloat, readDouble
  3981. */
  3982. virtual float readFloat();
  3983. /** Reads four bytes as a 32-bit floating point value.
  3984. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  3985. If the stream is exhausted partway through reading the bytes, this will return zero.
  3986. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  3987. */
  3988. virtual float readFloatBigEndian();
  3989. /** Reads eight bytes as a 64-bit floating point value.
  3990. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  3991. If the stream is exhausted partway through reading the bytes, this will return zero.
  3992. @see OutputStream::writeDouble, readFloat
  3993. */
  3994. virtual double readDouble();
  3995. /** Reads eight bytes as a 64-bit floating point value.
  3996. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  3997. If the stream is exhausted partway through reading the bytes, this will return zero.
  3998. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  3999. */
  4000. virtual double readDoubleBigEndian();
  4001. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  4002. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  4003. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  4004. @see OutputStream::writeCompressedInt()
  4005. */
  4006. virtual int readCompressedInt();
  4007. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  4008. This will read up to the next "\n" or "\r\n" or end-of-stream.
  4009. After this call, the stream's position will be left pointing to the next character
  4010. following the line-feed, but the linefeeds aren't included in the string that
  4011. is returned.
  4012. */
  4013. virtual const String readNextLine();
  4014. /** Reads a zero-terminated UTF8 string from the stream.
  4015. This will read characters from the stream until it hits a zero character or
  4016. end-of-stream.
  4017. @see OutputStream::writeString, readEntireStreamAsString
  4018. */
  4019. virtual const String readString();
  4020. /** Tries to read the whole stream and turn it into a string.
  4021. This will read from the stream's current position until the end-of-stream, and
  4022. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  4023. */
  4024. virtual const String readEntireStreamAsString();
  4025. /** Reads from the stream and appends the data to a MemoryBlock.
  4026. @param destBlock the block to append the data onto
  4027. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  4028. of bytes that will be read - if it's negative, data
  4029. will be read until the stream is exhausted.
  4030. @returns the number of bytes that were added to the memory block
  4031. */
  4032. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  4033. int maxNumBytesToRead = -1);
  4034. /** Returns the offset of the next byte that will be read from the stream.
  4035. @see setPosition
  4036. */
  4037. virtual int64 getPosition() = 0;
  4038. /** Tries to move the current read position of the stream.
  4039. The position is an absolute number of bytes from the stream's start.
  4040. Some streams might not be able to do this, in which case they should do
  4041. nothing and return false. Others might be able to manage it by resetting
  4042. themselves and skipping to the correct position, although this is
  4043. obviously a bit slow.
  4044. @returns true if the stream manages to reposition itself correctly
  4045. @see getPosition
  4046. */
  4047. virtual bool setPosition (int64 newPosition) = 0;
  4048. /** Reads and discards a number of bytes from the stream.
  4049. Some input streams might implement this efficiently, but the base
  4050. class will just keep reading data until the requisite number of bytes
  4051. have been done.
  4052. */
  4053. virtual void skipNextBytes (int64 numBytesToSkip);
  4054. juce_UseDebuggingNewOperator
  4055. protected:
  4056. InputStream() throw() {}
  4057. };
  4058. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  4059. /*** End of inlined file: juce_InputStream.h ***/
  4060. class File;
  4061. /**
  4062. The base class for streams that write data to some kind of destination.
  4063. Input and output streams are used throughout the library - subclasses can override
  4064. some or all of the virtual functions to implement their behaviour.
  4065. @see InputStream, MemoryOutputStream, FileOutputStream
  4066. */
  4067. class JUCE_API OutputStream
  4068. {
  4069. protected:
  4070. OutputStream();
  4071. public:
  4072. /** Destructor.
  4073. Some subclasses might want to do things like call flush() during their
  4074. destructors.
  4075. */
  4076. virtual ~OutputStream();
  4077. /** If the stream is using a buffer, this will ensure it gets written
  4078. out to the destination. */
  4079. virtual void flush() = 0;
  4080. /** Tries to move the stream's output position.
  4081. Not all streams will be able to seek to a new position - this will return
  4082. false if it fails to work.
  4083. @see getPosition
  4084. */
  4085. virtual bool setPosition (int64 newPosition) = 0;
  4086. /** Returns the stream's current position.
  4087. @see setPosition
  4088. */
  4089. virtual int64 getPosition() = 0;
  4090. /** Writes a block of data to the stream.
  4091. When creating a subclass of OutputStream, this is the only write method
  4092. that needs to be overloaded - the base class has methods for writing other
  4093. types of data which use this to do the work.
  4094. @returns false if the write operation fails for some reason
  4095. */
  4096. virtual bool write (const void* dataToWrite,
  4097. int howManyBytes) = 0;
  4098. /** Writes a single byte to the stream.
  4099. @see InputStream::readByte
  4100. */
  4101. virtual void writeByte (char byte);
  4102. /** Writes a boolean to the stream as a single byte.
  4103. This is encoded as a binary byte (not as text) with a value of 1 or 0.
  4104. @see InputStream::readBool
  4105. */
  4106. virtual void writeBool (bool boolValue);
  4107. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  4108. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  4109. @see InputStream::readShort
  4110. */
  4111. virtual void writeShort (short value);
  4112. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  4113. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  4114. @see InputStream::readShortBigEndian
  4115. */
  4116. virtual void writeShortBigEndian (short value);
  4117. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  4118. @see InputStream::readInt
  4119. */
  4120. virtual void writeInt (int value);
  4121. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  4122. @see InputStream::readIntBigEndian
  4123. */
  4124. virtual void writeIntBigEndian (int value);
  4125. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  4126. @see InputStream::readInt64
  4127. */
  4128. virtual void writeInt64 (int64 value);
  4129. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  4130. @see InputStream::readInt64BigEndian
  4131. */
  4132. virtual void writeInt64BigEndian (int64 value);
  4133. /** Writes a 32-bit floating point value to the stream in a binary format.
  4134. The binary 32-bit encoding of the float is written as a little-endian int.
  4135. @see InputStream::readFloat
  4136. */
  4137. virtual void writeFloat (float 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 big-endian int.
  4140. @see InputStream::readFloatBigEndian
  4141. */
  4142. virtual void writeFloatBigEndian (float value);
  4143. /** Writes a 64-bit floating point value to the stream in a binary format.
  4144. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  4145. @see InputStream::readDouble
  4146. */
  4147. virtual void writeDouble (double 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 big-endian 64-bit int.
  4150. @see InputStream::readDoubleBigEndian
  4151. */
  4152. virtual void writeDoubleBigEndian (double value);
  4153. /** Writes a condensed binary encoding of a 32-bit integer.
  4154. If you're storing a lot of integers which are unlikely to have very large values,
  4155. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  4156. under 0xffff only 3 bytes, etc.
  4157. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  4158. @see InputStream::readCompressedInt
  4159. */
  4160. virtual void writeCompressedInt (int value);
  4161. /** Stores a string in the stream in a binary format.
  4162. This isn't the method to use if you're trying to append text to the end of a
  4163. text-file! It's intended for storing a string so that it can be retrieved later
  4164. by InputStream::readString().
  4165. It writes the string to the stream as UTF8, including the null termination character.
  4166. For appending text to a file, instead use writeText, or operator<<
  4167. @see InputStream::readString, writeText, operator<<
  4168. */
  4169. virtual void writeString (const String& text);
  4170. /** Writes a string of text to the stream.
  4171. It can either write it as UTF8 characters or as unicode, and
  4172. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  4173. should only be done at the start of a file).
  4174. The method also replaces '\\n' characters in the text with '\\r\\n'.
  4175. */
  4176. virtual void writeText (const String& text,
  4177. bool asUnicode,
  4178. bool writeUnicodeHeaderBytes);
  4179. /** Reads data from an input stream and writes it to this stream.
  4180. @param source the stream to read from
  4181. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  4182. less than zero, it will keep reading until the input
  4183. is exhausted)
  4184. */
  4185. virtual int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  4186. juce_UseDebuggingNewOperator
  4187. };
  4188. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  4189. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, int number);
  4190. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  4191. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, double number);
  4192. /** Writes a character to a stream. */
  4193. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, char character);
  4194. /** Writes a null-terminated text string to a stream. */
  4195. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* text);
  4196. /** Writes a block of data from a MemoryBlock to a stream. */
  4197. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data);
  4198. /** Writes the contents of a file to a stream. */
  4199. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead);
  4200. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  4201. /*** End of inlined file: juce_OutputStream.h ***/
  4202. class JUCE_API DynamicObject;
  4203. /**
  4204. A variant class, that can be used to hold a range of primitive values.
  4205. A var object can hold a range of simple primitive values, strings, or
  4206. a reference-counted pointer to a DynamicObject. The var class is intended
  4207. to act like the values used in dynamic scripting languages.
  4208. @see DynamicObject
  4209. */
  4210. class JUCE_API var
  4211. {
  4212. public:
  4213. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  4214. typedef Identifier identifier;
  4215. /** Creates a void variant. */
  4216. var() throw();
  4217. /** Destructor. */
  4218. ~var() throw();
  4219. /** A static var object that can be used where you need an empty variant object. */
  4220. static const var null;
  4221. var (const var& valueToCopy);
  4222. var (int value) throw();
  4223. var (bool value) throw();
  4224. var (double value) throw();
  4225. var (const char* value);
  4226. var (const juce_wchar* value);
  4227. var (const String& value);
  4228. var (DynamicObject* object);
  4229. var (MethodFunction method) throw();
  4230. var& operator= (const var& valueToCopy);
  4231. var& operator= (int value);
  4232. var& operator= (bool value);
  4233. var& operator= (double value);
  4234. var& operator= (const char* value);
  4235. var& operator= (const juce_wchar* value);
  4236. var& operator= (const String& value);
  4237. var& operator= (DynamicObject* object);
  4238. var& operator= (MethodFunction method);
  4239. void swapWith (var& other) throw();
  4240. operator int() const;
  4241. operator bool() const;
  4242. operator float() const;
  4243. operator double() const;
  4244. operator const String() const;
  4245. const String toString() const;
  4246. DynamicObject* getObject() const;
  4247. bool isVoid() const throw() { return type == voidType; }
  4248. bool isInt() const throw() { return type == intType; }
  4249. bool isBool() const throw() { return type == boolType; }
  4250. bool isDouble() const throw() { return type == doubleType; }
  4251. bool isString() const throw() { return type == stringType; }
  4252. bool isObject() const throw() { return type == objectType; }
  4253. bool isMethod() const throw() { return type == methodType; }
  4254. /** Writes a binary representation of this value to a stream.
  4255. The data can be read back later using readFromStream().
  4256. */
  4257. void writeToStream (OutputStream& output) const;
  4258. /** Reads back a stored binary representation of a value.
  4259. The data in the stream must have been written using writeToStream(), or this
  4260. will have unpredictable results.
  4261. */
  4262. static const var readFromStream (InputStream& input);
  4263. /** If this variant is an object, this returns one of its properties. */
  4264. const var operator[] (const Identifier& propertyName) const;
  4265. /** If this variant is an object, this invokes one of its methods with no arguments. */
  4266. const var call (const Identifier& method) const;
  4267. /** If this variant is an object, this invokes one of its methods with one argument. */
  4268. const var call (const Identifier& method, const var& arg1) const;
  4269. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  4270. const var call (const Identifier& method, const var& arg1, const var& arg2) const;
  4271. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  4272. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3);
  4273. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  4274. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  4275. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  4276. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  4277. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  4278. const var invoke (const Identifier& method, const var* arguments, int numArguments) const;
  4279. /** If this variant is a method pointer, this invokes it on a target object. */
  4280. const var invoke (const var& targetObject, const var* arguments, int numArguments) const;
  4281. juce_UseDebuggingNewOperator
  4282. /** Returns true if this var has the same value as the one supplied. */
  4283. bool equals (const var& other) const throw();
  4284. private:
  4285. enum Type
  4286. {
  4287. voidType = 0,
  4288. intType,
  4289. boolType,
  4290. doubleType,
  4291. stringType,
  4292. objectType,
  4293. methodType
  4294. };
  4295. union ValueUnion
  4296. {
  4297. int intValue;
  4298. bool boolValue;
  4299. double doubleValue;
  4300. String* stringValue;
  4301. DynamicObject* objectValue;
  4302. MethodFunction methodValue;
  4303. };
  4304. Type type;
  4305. ValueUnion value;
  4306. };
  4307. bool operator== (const var& v1, const var& v2) throw();
  4308. bool operator!= (const var& v1, const var& v2) throw();
  4309. bool operator== (const var& v1, const String& v2) throw();
  4310. bool operator!= (const var& v1, const String& v2) throw();
  4311. #endif // __JUCE_VARIANT_JUCEHEADER__
  4312. /*** End of inlined file: juce_Variant.h ***/
  4313. /** Holds a set of named var objects.
  4314. This can be used as a basic structure to hold a set of var object, which can
  4315. be retrieved by using their identifier.
  4316. */
  4317. class JUCE_API NamedValueSet
  4318. {
  4319. public:
  4320. /** Creates an empty set. */
  4321. NamedValueSet() throw();
  4322. /** Creates a copy of another set. */
  4323. NamedValueSet (const NamedValueSet& other);
  4324. /** Replaces this set with a copy of another set. */
  4325. NamedValueSet& operator= (const NamedValueSet& other);
  4326. /** Destructor. */
  4327. ~NamedValueSet();
  4328. bool operator== (const NamedValueSet& other) const;
  4329. bool operator!= (const NamedValueSet& other) const;
  4330. /** Returns the total number of values that the set contains. */
  4331. int size() const throw();
  4332. /** Returns the value of a named item.
  4333. If the name isn't found, this will return a void variant.
  4334. @see getProperty
  4335. */
  4336. const var& operator[] (const Identifier& name) const;
  4337. /** Tries to return the named value, but if no such value is found, this will
  4338. instead return the supplied default value.
  4339. */
  4340. const var getWithDefault (const Identifier& name, const var& defaultReturnValue) const;
  4341. /** Returns a pointer to the object holding a named value, or
  4342. null if there is no value with this name. */
  4343. var* getItem (const Identifier& name) const;
  4344. /** Changes or adds a named value.
  4345. @returns true if a value was changed or added; false if the
  4346. value was already set the the value passed-in.
  4347. */
  4348. bool set (const Identifier& name, const var& newValue);
  4349. /** Returns true if the set contains an item with the specified name. */
  4350. bool contains (const Identifier& name) const;
  4351. /** Removes a value from the set.
  4352. @returns true if a value was removed; false if there was no value
  4353. with the name that was given.
  4354. */
  4355. bool remove (const Identifier& name);
  4356. /** Returns the name of the value at a given index.
  4357. The index must be between 0 and size() - 1. Out-of-range indexes will
  4358. return an empty identifier.
  4359. */
  4360. const Identifier getName (int index) const;
  4361. /** Returns the value of the item 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 var getValueAt (int index) const;
  4366. /** Removes all values. */
  4367. void clear();
  4368. juce_UseDebuggingNewOperator
  4369. private:
  4370. struct NamedValue
  4371. {
  4372. NamedValue() throw();
  4373. NamedValue (const Identifier& name, const var& value);
  4374. bool operator== (const NamedValue& other) const throw();
  4375. Identifier name;
  4376. var value;
  4377. };
  4378. Array <NamedValue> values;
  4379. };
  4380. #endif // __JUCE_NAMEDVALUESET_JUCEHEADER__
  4381. /*** End of inlined file: juce_NamedValueSet.h ***/
  4382. /*** Start of inlined file: juce_ReferenceCountedObject.h ***/
  4383. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  4384. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  4385. /*** Start of inlined file: juce_Atomic.h ***/
  4386. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  4387. #define __JUCE_ATOMIC_JUCEHEADER__
  4388. /**
  4389. Simple class to hold a primitive value and perform atomic operations on it.
  4390. The type used must be a 32 or 64 bit primitive, like an int, pointer, etc.
  4391. There are methods to perform most of the basic atomic operations.
  4392. */
  4393. template <typename Type>
  4394. class Atomic
  4395. {
  4396. public:
  4397. /** Creates a new value, initialised to zero. */
  4398. inline Atomic() throw()
  4399. : value (0)
  4400. {
  4401. }
  4402. /** Creates a new value, with a given initial value. */
  4403. inline Atomic (const Type initialValue) throw()
  4404. : value (initialValue)
  4405. {
  4406. }
  4407. /** Copies another value (atomically). */
  4408. inline Atomic (const Atomic& other) throw()
  4409. : value (other.get())
  4410. {
  4411. }
  4412. /** Copies another value onto this one (atomically). */
  4413. inline Atomic& operator= (const Atomic& other) throw()
  4414. {
  4415. set (other.get());
  4416. return *this;
  4417. }
  4418. /** Destructor. */
  4419. inline ~Atomic() throw()
  4420. {
  4421. // This class can only be used for types which are 32 or 64 bits in size.
  4422. static_jassert (sizeof (Type) == 4 || sizeof (Type) == 8);
  4423. }
  4424. /** Atomically reads and returns the current value. */
  4425. Type get() const throw();
  4426. /** Atomically sets the current value. */
  4427. void set (Type newValue) throw();
  4428. /** Atomically sets the current value, returning the value that was replaced. */
  4429. Type exchange (Type value) throw();
  4430. /** Atomically adds a number to this value, returning the new value. */
  4431. Type operator+= (Type amountToAdd) throw();
  4432. /** Atomically subtracts a number from this value, returning the new value. */
  4433. Type operator-= (Type amountToSubtract) throw();
  4434. /** Atomically increments this value, returning the new value. */
  4435. Type operator++() throw();
  4436. /** Atomically decrements this value, returning the new value. */
  4437. Type operator--() throw();
  4438. /** Atomically compares this value with a target value, and if it is equal, sets
  4439. this to be equal to a new value.
  4440. This operation is the atomic equivalent of doing this:
  4441. @code
  4442. bool compareAndSetBool (Type newValue, Type valueToCompare)
  4443. {
  4444. if (get() == valueToCompare)
  4445. {
  4446. set (newValue);
  4447. return true;
  4448. }
  4449. return false;
  4450. }
  4451. @endcode
  4452. @returns true if the comparison was true and the value was replaced; false if
  4453. the comparison failed and the value was left unchanged.
  4454. @see compareAndSetValue
  4455. */
  4456. bool compareAndSetBool (Type newValue, Type valueToCompare) throw();
  4457. /** Atomically compares this value with a target value, and if it is equal, sets
  4458. this to be equal to a new value.
  4459. This operation is the atomic equivalent of doing this:
  4460. @code
  4461. Type compareAndSetValue (Type newValue, Type valueToCompare)
  4462. {
  4463. Type oldValue = get();
  4464. if (oldValue == valueToCompare)
  4465. set (newValue);
  4466. return oldValue;
  4467. }
  4468. @endcode
  4469. @returns the old value before it was changed.
  4470. @see compareAndSetBool
  4471. */
  4472. Type compareAndSetValue (Type newValue, Type valueToCompare) throw();
  4473. /** Implements a memory read/write barrier. */
  4474. static void memoryBarrier() throw();
  4475. JUCE_ALIGN(8)
  4476. /** The raw value that this class operates on.
  4477. This is exposed publically in case you need to manipulate it directly
  4478. for performance reasons.
  4479. */
  4480. Type value;
  4481. };
  4482. /*
  4483. The following code is in the header so that the atomics can be inlined where possible...
  4484. */
  4485. #if (JUCE_IPHONE && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_3_2 || ! defined (__IPHONE_3_2))) \
  4486. || (JUCE_MAC && (JUCE_PPC || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)))
  4487. #define JUCE_ATOMICS_MAC 1 // Older OSX builds using gcc4.1 or earlier
  4488. #if JUCE_PPC || JUCE_IPHONE
  4489. // None of these atomics are available for PPC or for iPhoneOS 3.1 or earlier!!
  4490. template <typename Type> static Type OSAtomicAdd64 (Type b, volatile Type* a) throw() { jassertfalse; return *a += b; }
  4491. template <typename Type> static Type OSAtomicIncrement64 (volatile Type* a) throw() { jassertfalse; return ++*a; }
  4492. template <typename Type> static Type OSAtomicDecrement64 (volatile Type* a) throw() { jassertfalse; return --*a; }
  4493. template <typename Type> static bool OSAtomicCompareAndSwap64Barrier (Type old, Type newValue, volatile Type* value) throw()
  4494. { jassertfalse; if (old == *value) { *value = newValue; return true; } return false; }
  4495. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  4496. #endif
  4497. #elif JUCE_GCC
  4498. #define JUCE_ATOMICS_GCC 1 // GCC with intrinsics
  4499. #else
  4500. #define JUCE_ATOMICS_WINDOWS 1 // Windows with intrinsics
  4501. #if JUCE_USE_INTRINSICS || JUCE_64BIT
  4502. #pragma intrinsic (_InterlockedExchange, _InterlockedIncrement, _InterlockedDecrement, _InterlockedCompareExchange, \
  4503. _InterlockedCompareExchange64, _InterlockedExchangeAdd, _ReadWriteBarrier)
  4504. #define juce_InterlockedExchange(a, b) _InterlockedExchange(a, b)
  4505. #define juce_InterlockedIncrement(a) _InterlockedIncrement(a)
  4506. #define juce_InterlockedDecrement(a) _InterlockedDecrement(a)
  4507. #define juce_InterlockedExchangeAdd(a, b) _InterlockedExchangeAdd(a, b)
  4508. #define juce_InterlockedCompareExchange(a, b, c) _InterlockedCompareExchange(a, b, c)
  4509. #define juce_InterlockedCompareExchange64(a, b, c) _InterlockedCompareExchange64(a, b, c)
  4510. #define juce_MemoryBarrier _ReadWriteBarrier
  4511. #else
  4512. // (these are defined in juce_win32_Threads.cpp)
  4513. long juce_InterlockedExchange (volatile long* a, long b) throw();
  4514. long juce_InterlockedIncrement (volatile long* a) throw();
  4515. long juce_InterlockedDecrement (volatile long* a) throw();
  4516. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw();
  4517. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw();
  4518. __int64 juce_InterlockedCompareExchange64 (volatile __int64* a, __int64 b, __int64 c) throw();
  4519. static void juce_MemoryBarrier() throw() { long x = 0; juce_InterlockedIncrement (&x); }
  4520. #endif
  4521. #if JUCE_64BIT
  4522. #pragma intrinsic (_InterlockedExchangeAdd64, _InterlockedExchange64, _InterlockedIncrement64, _InterlockedDecrement64)
  4523. #define juce_InterlockedExchangeAdd64(a, b) _InterlockedExchangeAdd64(a, b)
  4524. #define juce_InterlockedExchange64(a, b) _InterlockedExchange64(a, b)
  4525. #define juce_InterlockedIncrement64(a) _InterlockedIncrement64(a)
  4526. #define juce_InterlockedDecrement64(a) _InterlockedDecrement64(a)
  4527. #else
  4528. // None of these atomics are available in a 32-bit Windows build!!
  4529. template <typename Type> static Type juce_InterlockedExchangeAdd64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a += b; return old; }
  4530. template <typename Type> static Type juce_InterlockedExchange64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a = b; return old; }
  4531. template <typename Type> static Type juce_InterlockedIncrement64 (volatile Type* a) throw() { jassertfalse; return ++*a; }
  4532. template <typename Type> static Type juce_InterlockedDecrement64 (volatile Type* a) throw() { jassertfalse; return --*a; }
  4533. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  4534. #endif
  4535. #endif
  4536. #if JUCE_MSVC
  4537. #pragma warning (push)
  4538. #pragma warning (disable: 4311) // (truncation warning)
  4539. #endif
  4540. template <typename Type>
  4541. inline Type Atomic<Type>::get() const throw()
  4542. {
  4543. return const_cast <Atomic<Type>*> (this)->operator+= (0);
  4544. }
  4545. template <typename Type>
  4546. inline void Atomic<Type>::set (const Type newValue) throw()
  4547. {
  4548. exchange (newValue);
  4549. }
  4550. template <typename Type>
  4551. inline Type Atomic<Type>::exchange (const Type newValue) throw()
  4552. {
  4553. #if JUCE_ATOMICS_MAC || JUCE_ATOMICS_GCC
  4554. Type currentVal = value;
  4555. while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; }
  4556. return currentVal;
  4557. #elif JUCE_ATOMICS_WINDOWS
  4558. return sizeof (Type) == 4 ? (Type) juce_InterlockedExchange ((volatile long*) &value, (long) newValue)
  4559. : (Type) juce_InterlockedExchange64 ((volatile __int64*) &value, (__int64) newValue);
  4560. #endif
  4561. }
  4562. template <typename Type>
  4563. inline Type Atomic<Type>::operator+= (const Type amountToAdd) throw()
  4564. {
  4565. #if JUCE_ATOMICS_MAC
  4566. return sizeof (Type) == 4 ? (Type) OSAtomicAdd32 ((int32_t) amountToAdd, (int32_t*) &value)
  4567. : (Type) OSAtomicAdd64 ((int64_t) amountToAdd, (int64_t*) &value);
  4568. #elif JUCE_ATOMICS_WINDOWS
  4569. return sizeof (Type) == 4 ? (Type) (juce_InterlockedExchangeAdd ((volatile long*) &value, (long) amountToAdd) + (long) amountToAdd)
  4570. : (Type) (juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) amountToAdd) + (__int64) amountToAdd);
  4571. #elif JUCE_ATOMICS_GCC
  4572. return (Type) __sync_add_and_fetch (&value, amountToAdd);
  4573. #endif
  4574. }
  4575. template <typename Type>
  4576. inline Type Atomic<Type>::operator-= (const Type amountToSubtract) throw()
  4577. {
  4578. return operator+= (juce_negate (amountToSubtract));
  4579. }
  4580. template <typename Type>
  4581. inline Type Atomic<Type>::operator++() throw()
  4582. {
  4583. #if JUCE_ATOMICS_MAC
  4584. return sizeof (Type) == 4 ? (Type) OSAtomicIncrement32 ((int32_t*) &value)
  4585. : (Type) OSAtomicIncrement64 ((int64_t*) &value);
  4586. #elif JUCE_ATOMICS_WINDOWS
  4587. return sizeof (Type) == 4 ? (Type) juce_InterlockedIncrement ((volatile long*) &value)
  4588. : (Type) juce_InterlockedIncrement64 ((volatile __int64*) &value);
  4589. #elif JUCE_ATOMICS_GCC
  4590. return (Type) __sync_add_and_fetch (&value, 1);
  4591. #endif
  4592. }
  4593. template <typename Type>
  4594. inline Type Atomic<Type>::operator--() throw()
  4595. {
  4596. #if JUCE_ATOMICS_MAC
  4597. return sizeof (Type) == 4 ? (Type) OSAtomicDecrement32 ((int32_t*) &value)
  4598. : (Type) OSAtomicDecrement64 ((int64_t*) &value);
  4599. #elif JUCE_ATOMICS_WINDOWS
  4600. return sizeof (Type) == 4 ? (Type) juce_InterlockedDecrement ((volatile long*) &value)
  4601. : (Type) juce_InterlockedDecrement64 ((volatile __int64*) &value);
  4602. #elif JUCE_ATOMICS_GCC
  4603. return (Type) __sync_add_and_fetch (&value, -1);
  4604. #endif
  4605. }
  4606. template <typename Type>
  4607. inline bool Atomic<Type>::compareAndSetBool (const Type newValue, const Type valueToCompare) throw()
  4608. {
  4609. #if JUCE_ATOMICS_MAC
  4610. return sizeof (Type) == 4 ? OSAtomicCompareAndSwap32Barrier ((int32_t) valueToCompare, (int32_t) newValue, (int32_t*) &value)
  4611. : OSAtomicCompareAndSwap64Barrier ((int64_t) valueToCompare, (int64_t) newValue, (int64_t*) &value);
  4612. #elif JUCE_ATOMICS_WINDOWS
  4613. return compareAndSetValue (newValue, valueToCompare) == valueToCompare;
  4614. #elif JUCE_ATOMICS_GCC
  4615. return __sync_bool_compare_and_swap (&value, valueToCompare, newValue);
  4616. #endif
  4617. }
  4618. template <typename Type>
  4619. inline Type Atomic<Type>::compareAndSetValue (const Type newValue, const Type valueToCompare) throw()
  4620. {
  4621. #if JUCE_ATOMICS_MAC
  4622. for (;;) // Annoying workaround for OSX only having a bool CAS operation..
  4623. {
  4624. if (compareAndSetBool (newValue, valueToCompare))
  4625. return valueToCompare;
  4626. const Type result = value;
  4627. if (result != valueToCompare)
  4628. return result;
  4629. }
  4630. #elif JUCE_ATOMICS_WINDOWS
  4631. return sizeof (Type) == 4 ? (Type) juce_InterlockedCompareExchange ((volatile long*) &value, (long) newValue, (long) valueToCompare)
  4632. : (Type) juce_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) newValue, (__int64) valueToCompare);
  4633. #elif JUCE_ATOMICS_GCC
  4634. return __sync_val_compare_and_swap (&value, valueToCompare, newValue);
  4635. #endif
  4636. }
  4637. template <typename Type>
  4638. inline void Atomic<Type>::memoryBarrier() throw()
  4639. {
  4640. #if JUCE_ATOMICS_MAC
  4641. OSMemoryBarrier();
  4642. #elif JUCE_ATOMICS_GCC
  4643. __sync_synchronize();
  4644. #elif JUCE_ATOMICS_WINDOWS
  4645. juce_MemoryBarrier();
  4646. #endif
  4647. }
  4648. #if JUCE_MSVC
  4649. #pragma warning (pop)
  4650. #endif
  4651. #endif // __JUCE_ATOMIC_JUCEHEADER__
  4652. /*** End of inlined file: juce_Atomic.h ***/
  4653. /**
  4654. Adds reference-counting to an object.
  4655. To add reference-counting to a class, derive it from this class, and
  4656. use the ReferenceCountedObjectPtr class to point to it.
  4657. e.g. @code
  4658. class MyClass : public ReferenceCountedObject
  4659. {
  4660. void foo();
  4661. // This is a neat way of declaring a typedef for a pointer class,
  4662. // rather than typing out the full templated name each time..
  4663. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  4664. };
  4665. MyClass::Ptr p = new MyClass();
  4666. MyClass::Ptr p2 = p;
  4667. p = 0;
  4668. p2->foo();
  4669. @endcode
  4670. Once a new ReferenceCountedObject has been assigned to a pointer, be
  4671. careful not to delete the object manually.
  4672. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  4673. */
  4674. class JUCE_API ReferenceCountedObject
  4675. {
  4676. public:
  4677. /** Increments the object's reference count.
  4678. This is done automatically by the smart pointer, but is public just
  4679. in case it's needed for nefarious purposes.
  4680. */
  4681. inline void incReferenceCount() throw()
  4682. {
  4683. ++refCount;
  4684. }
  4685. /** Decreases the object's reference count.
  4686. If the count gets to zero, the object will be deleted.
  4687. */
  4688. inline void decReferenceCount() throw()
  4689. {
  4690. jassert (getReferenceCount() > 0);
  4691. if (--refCount == 0)
  4692. delete this;
  4693. }
  4694. /** Returns the object's current reference count. */
  4695. inline int getReferenceCount() const throw()
  4696. {
  4697. return refCount.get();
  4698. }
  4699. protected:
  4700. /** Creates the reference-counted object (with an initial ref count of zero). */
  4701. ReferenceCountedObject()
  4702. {
  4703. }
  4704. /** Destructor. */
  4705. virtual ~ReferenceCountedObject()
  4706. {
  4707. // it's dangerous to delete an object that's still referenced by something else!
  4708. jassert (getReferenceCount() == 0);
  4709. }
  4710. private:
  4711. Atomic <int> refCount;
  4712. };
  4713. /**
  4714. Used to point to an object of type ReferenceCountedObject.
  4715. It's wise to use a typedef instead of typing out the templated name
  4716. each time - e.g.
  4717. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  4718. @see ReferenceCountedObject, ReferenceCountedObjectArray
  4719. */
  4720. template <class ReferenceCountedObjectClass>
  4721. class ReferenceCountedObjectPtr
  4722. {
  4723. public:
  4724. /** Creates a pointer to a null object. */
  4725. inline ReferenceCountedObjectPtr() throw()
  4726. : referencedObject (0)
  4727. {
  4728. }
  4729. /** Creates a pointer to an object.
  4730. This will increment the object's reference-count if it is non-null.
  4731. */
  4732. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  4733. : referencedObject (refCountedObject)
  4734. {
  4735. if (refCountedObject != 0)
  4736. refCountedObject->incReferenceCount();
  4737. }
  4738. /** Copies another pointer.
  4739. This will increment the object's reference-count (if it is non-null).
  4740. */
  4741. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  4742. : referencedObject (other.referencedObject)
  4743. {
  4744. if (referencedObject != 0)
  4745. referencedObject->incReferenceCount();
  4746. }
  4747. /** Changes this pointer to point at a different object.
  4748. The reference count of the old object is decremented, and it might be
  4749. deleted if it hits zero. The new object's count is incremented.
  4750. */
  4751. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  4752. {
  4753. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  4754. if (newObject != referencedObject)
  4755. {
  4756. if (newObject != 0)
  4757. newObject->incReferenceCount();
  4758. ReferenceCountedObjectClass* const oldObject = referencedObject;
  4759. referencedObject = newObject;
  4760. if (oldObject != 0)
  4761. oldObject->decReferenceCount();
  4762. }
  4763. return *this;
  4764. }
  4765. /** Changes this pointer to point at a different object.
  4766. The reference count of the old object is decremented, and it might be
  4767. deleted if it hits zero. The new object's count is incremented.
  4768. */
  4769. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  4770. {
  4771. if (referencedObject != newObject)
  4772. {
  4773. if (newObject != 0)
  4774. newObject->incReferenceCount();
  4775. ReferenceCountedObjectClass* const oldObject = referencedObject;
  4776. referencedObject = newObject;
  4777. if (oldObject != 0)
  4778. oldObject->decReferenceCount();
  4779. }
  4780. return *this;
  4781. }
  4782. /** Destructor.
  4783. This will decrement the object's reference-count, and may delete it if it
  4784. gets to zero.
  4785. */
  4786. inline ~ReferenceCountedObjectPtr()
  4787. {
  4788. if (referencedObject != 0)
  4789. referencedObject->decReferenceCount();
  4790. }
  4791. /** Returns the object that this pointer references.
  4792. The pointer returned may be zero, of course.
  4793. */
  4794. inline operator ReferenceCountedObjectClass*() const throw()
  4795. {
  4796. return referencedObject;
  4797. }
  4798. /** Returns true if this pointer refers to the given object. */
  4799. inline bool operator== (ReferenceCountedObjectClass* const object) const throw()
  4800. {
  4801. return referencedObject == object;
  4802. }
  4803. /** Returns true if this pointer doesn't refer to the given object. */
  4804. inline bool operator!= (ReferenceCountedObjectClass* const object) const throw()
  4805. {
  4806. return referencedObject != object;
  4807. }
  4808. // the -> operator is called on the referenced object
  4809. inline ReferenceCountedObjectClass* operator->() const throw()
  4810. {
  4811. return referencedObject;
  4812. }
  4813. /** Returns the object that this pointer references.
  4814. The pointer returned may be zero, of course.
  4815. */
  4816. inline ReferenceCountedObjectClass* getObject() const throw()
  4817. {
  4818. return referencedObject;
  4819. }
  4820. private:
  4821. ReferenceCountedObjectClass* referencedObject;
  4822. };
  4823. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  4824. /*** End of inlined file: juce_ReferenceCountedObject.h ***/
  4825. /**
  4826. Represents a dynamically implemented object.
  4827. This class is primarily intended for wrapping scripting language objects,
  4828. but could be used for other purposes.
  4829. An instance of a DynamicObject can be used to store named properties, and
  4830. by subclassing hasMethod() and invokeMethod(), you can give your object
  4831. methods.
  4832. */
  4833. class JUCE_API DynamicObject : public ReferenceCountedObject
  4834. {
  4835. public:
  4836. DynamicObject();
  4837. /** Destructor. */
  4838. virtual ~DynamicObject();
  4839. /** Returns true if the object has a property with this name.
  4840. Note that if the property is actually a method, this will return false.
  4841. */
  4842. virtual bool hasProperty (const Identifier& propertyName) const;
  4843. /** Returns a named property.
  4844. This returns a void if no such property exists.
  4845. */
  4846. virtual const var getProperty (const Identifier& propertyName) const;
  4847. /** Sets a named property. */
  4848. virtual void setProperty (const Identifier& propertyName, const var& newValue);
  4849. /** Removes a named property. */
  4850. virtual void removeProperty (const Identifier& propertyName);
  4851. /** Checks whether this object has the specified method.
  4852. The default implementation of this just checks whether there's a property
  4853. with this name that's actually a method, but this can be overridden for
  4854. building objects with dynamic invocation.
  4855. */
  4856. virtual bool hasMethod (const Identifier& methodName) const;
  4857. /** Invokes a named method on this object.
  4858. The default implementation looks up the named property, and if it's a method
  4859. call, then it invokes it.
  4860. This method is virtual to allow more dynamic invocation to used for objects
  4861. where the methods may not already be set as properies.
  4862. */
  4863. virtual const var invokeMethod (const Identifier& methodName,
  4864. const var* parameters,
  4865. int numParameters);
  4866. /** Sets up a method.
  4867. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  4868. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  4869. the code easier to read,
  4870. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  4871. @code
  4872. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  4873. @endcode
  4874. */
  4875. void setMethod (const Identifier& methodName,
  4876. var::MethodFunction methodFunction);
  4877. /** Removes all properties and methods from the object. */
  4878. void clear();
  4879. juce_UseDebuggingNewOperator
  4880. private:
  4881. NamedValueSet properties;
  4882. };
  4883. #endif // __JUCE_DYNAMICOBJECT_JUCEHEADER__
  4884. /*** End of inlined file: juce_DynamicObject.h ***/
  4885. #endif
  4886. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  4887. #endif
  4888. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  4889. #endif
  4890. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  4891. #endif
  4892. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  4893. #endif
  4894. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  4895. #endif
  4896. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  4897. /*** Start of inlined file: juce_OwnedArray.h ***/
  4898. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  4899. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  4900. /*** Start of inlined file: juce_ScopedPointer.h ***/
  4901. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  4902. #define __JUCE_SCOPEDPOINTER_JUCEHEADER__
  4903. /**
  4904. This class holds a pointer which is automatically deleted when this object goes
  4905. out of scope.
  4906. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  4907. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  4908. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  4909. created objects.
  4910. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  4911. to an object. If you use the assignment operator to assign a different object to a
  4912. ScopedPointer, the old one will be automatically deleted.
  4913. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  4914. object to which it points during its lifetime. This means that making a copy of a const
  4915. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  4916. old one.
  4917. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  4918. can use the release() method.
  4919. */
  4920. template <class ObjectType>
  4921. class ScopedPointer
  4922. {
  4923. public:
  4924. /** Creates a ScopedPointer containing a null pointer. */
  4925. inline ScopedPointer() throw() : object (0)
  4926. {
  4927. }
  4928. /** Creates a ScopedPointer that owns the specified object. */
  4929. inline ScopedPointer (ObjectType* const objectToTakePossessionOf) throw()
  4930. : object (objectToTakePossessionOf)
  4931. {
  4932. }
  4933. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  4934. Because a pointer can only belong to one ScopedPointer, this transfers
  4935. the pointer from the other object to this one, and the other object is reset to
  4936. be a null pointer.
  4937. */
  4938. ScopedPointer (ScopedPointer& objectToTransferFrom) throw()
  4939. : object (objectToTransferFrom.object)
  4940. {
  4941. objectToTransferFrom.object = 0;
  4942. }
  4943. /** Destructor.
  4944. This will delete the object that this ScopedPointer currently refers to.
  4945. */
  4946. inline ~ScopedPointer() { delete object; }
  4947. /** Changes this ScopedPointer to point to a new object.
  4948. Because a pointer can only belong to one ScopedPointer, this transfers
  4949. the pointer from the other object to this one, and the other object is reset to
  4950. be a null pointer.
  4951. If this ScopedPointer already points to an object, that object
  4952. will first be deleted.
  4953. */
  4954. ScopedPointer& operator= (ScopedPointer& objectToTransferFrom)
  4955. {
  4956. if (this != objectToTransferFrom.getAddress())
  4957. {
  4958. // Two ScopedPointers should never be able to refer to the same object - if
  4959. // this happens, you must have done something dodgy!
  4960. jassert (object == 0 || object != objectToTransferFrom.object);
  4961. ObjectType* const oldObject = object;
  4962. object = objectToTransferFrom.object;
  4963. objectToTransferFrom.object = 0;
  4964. delete oldObject;
  4965. }
  4966. return *this;
  4967. }
  4968. /** Changes this ScopedPointer to point to a new object.
  4969. If this ScopedPointer already points to an object, that object
  4970. will first be deleted.
  4971. The pointer that you pass is may be null.
  4972. */
  4973. ScopedPointer& operator= (ObjectType* const newObjectToTakePossessionOf)
  4974. {
  4975. if (object != newObjectToTakePossessionOf)
  4976. {
  4977. ObjectType* const oldObject = object;
  4978. object = newObjectToTakePossessionOf;
  4979. delete oldObject;
  4980. }
  4981. return *this;
  4982. }
  4983. /** Returns the object that this ScopedPointer refers to.
  4984. */
  4985. inline operator ObjectType*() const throw() { return object; }
  4986. /** Returns the object that this ScopedPointer refers to.
  4987. */
  4988. inline ObjectType& operator*() const throw() { return *object; }
  4989. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  4990. inline ObjectType* operator->() const throw() { return object; }
  4991. /** Returns a reference to the address of the object that this ScopedPointer refers to. */
  4992. inline ObjectType* const* operator&() const throw() { return static_cast <ObjectType* const*> (&object); }
  4993. /** Returns a reference to the address of the object that this ScopedPointer refers to. */
  4994. inline ObjectType** operator&() throw() { return static_cast <ObjectType**> (&object); }
  4995. /** Removes the current object from this ScopedPointer without deleting it.
  4996. This will return the current object, and set the ScopedPointer to a null pointer.
  4997. */
  4998. ObjectType* release() throw() { ObjectType* const o = object; object = 0; return o; }
  4999. /** Swaps this object with that of another ScopedPointer.
  5000. The two objects simply exchange their pointers.
  5001. */
  5002. void swapWith (ScopedPointer <ObjectType>& other) throw()
  5003. {
  5004. // Two ScopedPointers should never be able to refer to the same object - if
  5005. // this happens, you must have done something dodgy!
  5006. jassert (object != other.object);
  5007. swapVariables (object, other.object);
  5008. }
  5009. private:
  5010. ObjectType* object;
  5011. // (Required as an alternative to the overloaded & operator).
  5012. const ScopedPointer* getAddress() const throw() { return this; }
  5013. #if ! JUCE_MSVC // (MSVC can't deal with multiple copy constructors)
  5014. // This is private to stop people accidentally copying a const ScopedPointer (the compiler
  5015. // will let you do so by implicitly casting the source to its raw object pointer).
  5016. ScopedPointer (const ScopedPointer&);
  5017. #endif
  5018. };
  5019. /** Compares a ScopedPointer with another pointer.
  5020. This can be handy for checking whether this is a null pointer.
  5021. */
  5022. template <class ObjectType>
  5023. inline bool operator== (const ScopedPointer<ObjectType>& pointer1, const ObjectType* const pointer2) throw()
  5024. {
  5025. return static_cast <ObjectType*> (pointer1) == pointer2;
  5026. }
  5027. /** Compares a ScopedPointer with another pointer.
  5028. This can be handy for checking whether this is a null pointer.
  5029. */
  5030. template <class ObjectType>
  5031. inline bool operator!= (const ScopedPointer<ObjectType>& pointer1, const ObjectType* const pointer2) throw()
  5032. {
  5033. return static_cast <ObjectType*> (pointer1) != pointer2;
  5034. }
  5035. #endif // __JUCE_SCOPEDPOINTER_JUCEHEADER__
  5036. /*** End of inlined file: juce_ScopedPointer.h ***/
  5037. /** An array designed for holding objects.
  5038. This holds a list of pointers to objects, and will automatically
  5039. delete the objects when they are removed from the array, or when the
  5040. array is itself deleted.
  5041. Declare it in the form: OwnedArray<MyObjectClass>
  5042. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  5043. After adding objects, they are 'owned' by the array and will be deleted when
  5044. removed or replaced.
  5045. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  5046. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  5047. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  5048. */
  5049. template <class ObjectClass,
  5050. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  5051. class OwnedArray
  5052. {
  5053. public:
  5054. /** Creates an empty array. */
  5055. OwnedArray() throw()
  5056. : numUsed (0)
  5057. {
  5058. }
  5059. /** Deletes the array and also deletes any objects inside it.
  5060. To get rid of the array without deleting its objects, use its
  5061. clear (false) method before deleting it.
  5062. */
  5063. ~OwnedArray()
  5064. {
  5065. clear (true);
  5066. }
  5067. /** Clears the array, optionally deleting the objects inside it first. */
  5068. void clear (const bool deleteObjects = true)
  5069. {
  5070. const ScopedLockType lock (getLock());
  5071. if (deleteObjects)
  5072. {
  5073. while (numUsed > 0)
  5074. delete data.elements [--numUsed];
  5075. }
  5076. data.setAllocatedSize (0);
  5077. numUsed = 0;
  5078. }
  5079. /** Returns the number of items currently in the array.
  5080. @see operator[]
  5081. */
  5082. inline int size() const throw()
  5083. {
  5084. return numUsed;
  5085. }
  5086. /** Returns a pointer to the object at this index in the array.
  5087. If the index is out-of-range, this will return a null pointer, (and
  5088. it could be null anyway, because it's ok for the array to hold null
  5089. pointers as well as objects).
  5090. @see getUnchecked
  5091. */
  5092. inline ObjectClass* operator[] (const int index) const throw()
  5093. {
  5094. const ScopedLockType lock (getLock());
  5095. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  5096. : static_cast <ObjectClass*> (0);
  5097. }
  5098. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  5099. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  5100. it can be used when you're sure the index if always going to be legal.
  5101. */
  5102. inline ObjectClass* getUnchecked (const int index) const throw()
  5103. {
  5104. const ScopedLockType lock (getLock());
  5105. jassert (((unsigned int) index) < (unsigned int) numUsed);
  5106. return data.elements [index];
  5107. }
  5108. /** Returns a pointer to the first object in the array.
  5109. This will return a null pointer if the array's empty.
  5110. @see getLast
  5111. */
  5112. inline ObjectClass* getFirst() const throw()
  5113. {
  5114. const ScopedLockType lock (getLock());
  5115. return numUsed > 0 ? data.elements [0]
  5116. : static_cast <ObjectClass*> (0);
  5117. }
  5118. /** Returns a pointer to the last object in the array.
  5119. This will return a null pointer if the array's empty.
  5120. @see getFirst
  5121. */
  5122. inline ObjectClass* getLast() const throw()
  5123. {
  5124. const ScopedLockType lock (getLock());
  5125. return numUsed > 0 ? data.elements [numUsed - 1]
  5126. : static_cast <ObjectClass*> (0);
  5127. }
  5128. /** Returns a pointer to the actual array data.
  5129. This pointer will only be valid until the next time a non-const method
  5130. is called on the array.
  5131. */
  5132. inline ObjectClass** getRawDataPointer() throw()
  5133. {
  5134. return data.elements;
  5135. }
  5136. /** Finds the index of an object which might be in the array.
  5137. @param objectToLookFor the object to look for
  5138. @returns the index at which the object was found, or -1 if it's not found
  5139. */
  5140. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  5141. {
  5142. const ScopedLockType lock (getLock());
  5143. ObjectClass* const* e = data.elements.getData();
  5144. ObjectClass* const* const end = e + numUsed;
  5145. while (e != end)
  5146. {
  5147. if (objectToLookFor == *e)
  5148. return static_cast <int> (e - data.elements.getData());
  5149. ++e;
  5150. }
  5151. return -1;
  5152. }
  5153. /** Returns true if the array contains a specified object.
  5154. @param objectToLookFor the object to look for
  5155. @returns true if the object is in the array
  5156. */
  5157. bool contains (const ObjectClass* const objectToLookFor) const throw()
  5158. {
  5159. const ScopedLockType lock (getLock());
  5160. ObjectClass* const* e = data.elements.getData();
  5161. ObjectClass* const* const end = e + numUsed;
  5162. while (e != end)
  5163. {
  5164. if (objectToLookFor == *e)
  5165. return true;
  5166. ++e;
  5167. }
  5168. return false;
  5169. }
  5170. /** Appends a new object to the end of the array.
  5171. Note that the this object will be deleted by the OwnedArray when it
  5172. is removed, so be careful not to delete it somewhere else.
  5173. Also be careful not to add the same object to the array more than once,
  5174. as this will obviously cause deletion of dangling pointers.
  5175. @param newObject the new object to add to the array
  5176. @see set, insert, addIfNotAlreadyThere, addSorted
  5177. */
  5178. void add (const ObjectClass* const newObject) throw()
  5179. {
  5180. const ScopedLockType lock (getLock());
  5181. data.ensureAllocatedSize (numUsed + 1);
  5182. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  5183. }
  5184. /** Inserts a new object into the array at the given index.
  5185. Note that the this object will be deleted by the OwnedArray when it
  5186. is removed, so be careful not to delete it somewhere else.
  5187. If the index is less than 0 or greater than the size of the array, the
  5188. element will be added to the end of the array.
  5189. Otherwise, it will be inserted into the array, moving all the later elements
  5190. along to make room.
  5191. Be careful not to add the same object to the array more than once,
  5192. as this will obviously cause deletion of dangling pointers.
  5193. @param indexToInsertAt the index at which the new element should be inserted
  5194. @param newObject the new object to add to the array
  5195. @see add, addSorted, addIfNotAlreadyThere, set
  5196. */
  5197. void insert (int indexToInsertAt,
  5198. const ObjectClass* const newObject) throw()
  5199. {
  5200. if (indexToInsertAt >= 0)
  5201. {
  5202. const ScopedLockType lock (getLock());
  5203. if (indexToInsertAt > numUsed)
  5204. indexToInsertAt = numUsed;
  5205. data.ensureAllocatedSize (numUsed + 1);
  5206. ObjectClass** const e = data.elements + indexToInsertAt;
  5207. const int numToMove = numUsed - indexToInsertAt;
  5208. if (numToMove > 0)
  5209. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  5210. *e = const_cast <ObjectClass*> (newObject);
  5211. ++numUsed;
  5212. }
  5213. else
  5214. {
  5215. add (newObject);
  5216. }
  5217. }
  5218. /** Appends a new object at the end of the array as long as the array doesn't
  5219. already contain it.
  5220. If the array already contains a matching object, nothing will be done.
  5221. @param newObject the new object to add to the array
  5222. */
  5223. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  5224. {
  5225. const ScopedLockType lock (getLock());
  5226. if (! contains (newObject))
  5227. add (newObject);
  5228. }
  5229. /** Replaces an object in the array with a different one.
  5230. If the index is less than zero, this method does nothing.
  5231. If the index is beyond the end of the array, the new object is added to the end of the array.
  5232. Be careful not to add the same object to the array more than once,
  5233. as this will obviously cause deletion of dangling pointers.
  5234. @param indexToChange the index whose value you want to change
  5235. @param newObject the new value to set for this index.
  5236. @param deleteOldElement whether to delete the object that's being replaced with the new one
  5237. @see add, insert, remove
  5238. */
  5239. void set (const int indexToChange,
  5240. const ObjectClass* const newObject,
  5241. const bool deleteOldElement = true)
  5242. {
  5243. if (indexToChange >= 0)
  5244. {
  5245. ScopedPointer <ObjectClass> toDelete;
  5246. const ScopedLockType lock (getLock());
  5247. if (indexToChange < numUsed)
  5248. {
  5249. if (deleteOldElement)
  5250. {
  5251. toDelete = data.elements [indexToChange];
  5252. if (toDelete == newObject)
  5253. toDelete = 0;
  5254. }
  5255. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  5256. }
  5257. else
  5258. {
  5259. data.ensureAllocatedSize (numUsed + 1);
  5260. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  5261. }
  5262. }
  5263. }
  5264. /** Adds elements from another array to the end of this array.
  5265. @param arrayToAddFrom the array from which to copy the elements
  5266. @param startIndex the first element of the other array to start copying from
  5267. @param numElementsToAdd how many elements to add from the other array. If this
  5268. value is negative or greater than the number of available elements,
  5269. all available elements will be copied.
  5270. @see add
  5271. */
  5272. template <class OtherArrayType>
  5273. void addArray (const OtherArrayType& arrayToAddFrom,
  5274. int startIndex = 0,
  5275. int numElementsToAdd = -1)
  5276. {
  5277. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5278. const ScopedLockType lock2 (getLock());
  5279. if (startIndex < 0)
  5280. {
  5281. jassertfalse;
  5282. startIndex = 0;
  5283. }
  5284. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5285. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5286. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5287. while (--numElementsToAdd >= 0)
  5288. {
  5289. data.elements [numUsed] = arrayToAddFrom.getUnchecked (startIndex++);
  5290. ++numUsed;
  5291. }
  5292. }
  5293. /** Adds copies of the elements in another array to the end of this array.
  5294. The other array must be either an OwnedArray of a compatible type of object, or an Array
  5295. containing pointers to the same kind of object. The objects involved must provide
  5296. a copy constructor, and this will be used to create new copies of each element, and
  5297. add them to this array.
  5298. @param arrayToAddFrom the array from which to copy the elements
  5299. @param startIndex the first element of the other array to start copying from
  5300. @param numElementsToAdd how many elements to add from the other array. If this
  5301. value is negative or greater than the number of available elements,
  5302. all available elements will be copied.
  5303. @see add
  5304. */
  5305. template <class OtherArrayType>
  5306. void addCopiesOf (const OtherArrayType& arrayToAddFrom,
  5307. int startIndex = 0,
  5308. int numElementsToAdd = -1)
  5309. {
  5310. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5311. const ScopedLockType lock2 (getLock());
  5312. if (startIndex < 0)
  5313. {
  5314. jassertfalse;
  5315. startIndex = 0;
  5316. }
  5317. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5318. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5319. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5320. while (--numElementsToAdd >= 0)
  5321. {
  5322. data.elements [numUsed] = new ObjectClass (*arrayToAddFrom.getUnchecked (startIndex++));
  5323. ++numUsed;
  5324. }
  5325. }
  5326. /** Inserts a new object into the array assuming that the array is sorted.
  5327. This will use a comparator to find the position at which the new object
  5328. should go. If the array isn't sorted, the behaviour of this
  5329. method will be unpredictable.
  5330. @param comparator the comparator to use to compare the elements - see the sort method
  5331. for details about this object's structure
  5332. @param newObject the new object to insert to the array
  5333. @see add, sort, indexOfSorted
  5334. */
  5335. template <class ElementComparator>
  5336. void addSorted (ElementComparator& comparator,
  5337. ObjectClass* const newObject) throw()
  5338. {
  5339. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5340. // avoids getting warning messages about the parameter being unused
  5341. const ScopedLockType lock (getLock());
  5342. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  5343. }
  5344. /** Finds the index of an object in the array, assuming that the array is sorted.
  5345. This will use a comparator to do a binary-chop to find the index of the given
  5346. element, if it exists. If the array isn't sorted, the behaviour of this
  5347. method will be unpredictable.
  5348. @param comparator the comparator to use to compare the elements - see the sort()
  5349. method for details about the form this object should take
  5350. @param objectToLookFor the object to search for
  5351. @returns the index of the element, or -1 if it's not found
  5352. @see addSorted, sort
  5353. */
  5354. template <class ElementComparator>
  5355. int indexOfSorted (ElementComparator& comparator,
  5356. const ObjectClass* const objectToLookFor) const throw()
  5357. {
  5358. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5359. // avoids getting warning messages about the parameter being unused
  5360. const ScopedLockType lock (getLock());
  5361. int start = 0;
  5362. int end = numUsed;
  5363. for (;;)
  5364. {
  5365. if (start >= end)
  5366. {
  5367. return -1;
  5368. }
  5369. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  5370. {
  5371. return start;
  5372. }
  5373. else
  5374. {
  5375. const int halfway = (start + end) >> 1;
  5376. if (halfway == start)
  5377. return -1;
  5378. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  5379. start = halfway;
  5380. else
  5381. end = halfway;
  5382. }
  5383. }
  5384. }
  5385. /** Removes an object from the array.
  5386. This will remove the object at a given index (optionally also
  5387. deleting it) and move back all the subsequent objects to close the gap.
  5388. If the index passed in is out-of-range, nothing will happen.
  5389. @param indexToRemove the index of the element to remove
  5390. @param deleteObject whether to delete the object that is removed
  5391. @see removeObject, removeRange
  5392. */
  5393. void remove (const int indexToRemove,
  5394. const bool deleteObject = true)
  5395. {
  5396. ScopedPointer <ObjectClass> toDelete;
  5397. const ScopedLockType lock (getLock());
  5398. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  5399. {
  5400. ObjectClass** const e = data.elements + indexToRemove;
  5401. if (deleteObject)
  5402. toDelete = *e;
  5403. --numUsed;
  5404. const int numToShift = numUsed - indexToRemove;
  5405. if (numToShift > 0)
  5406. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  5407. if ((numUsed << 1) < data.numAllocated)
  5408. minimiseStorageOverheads();
  5409. }
  5410. }
  5411. /** Removes a specified object from the array.
  5412. If the item isn't found, no action is taken.
  5413. @param objectToRemove the object to try to remove
  5414. @param deleteObject whether to delete the object (if it's found)
  5415. @see remove, removeRange
  5416. */
  5417. void removeObject (const ObjectClass* const objectToRemove,
  5418. const bool deleteObject = true)
  5419. {
  5420. const ScopedLockType lock (getLock());
  5421. ObjectClass** e = data.elements.getData();
  5422. for (int i = numUsed; --i >= 0;)
  5423. {
  5424. if (objectToRemove == *e)
  5425. {
  5426. remove (static_cast <int> (e - data.elements.getData()), deleteObject);
  5427. break;
  5428. }
  5429. ++e;
  5430. }
  5431. }
  5432. /** Removes a range of objects from the array.
  5433. This will remove a set of objects, starting from the given index,
  5434. and move any subsequent elements down to close the gap.
  5435. If the range extends beyond the bounds of the array, it will
  5436. be safely clipped to the size of the array.
  5437. @param startIndex the index of the first object to remove
  5438. @param numberToRemove how many objects should be removed
  5439. @param deleteObjects whether to delete the objects that get removed
  5440. @see remove, removeObject
  5441. */
  5442. void removeRange (int startIndex,
  5443. const int numberToRemove,
  5444. const bool deleteObjects = true)
  5445. {
  5446. const ScopedLockType lock (getLock());
  5447. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  5448. startIndex = jlimit (0, numUsed, startIndex);
  5449. if (endIndex > startIndex)
  5450. {
  5451. if (deleteObjects)
  5452. {
  5453. for (int i = startIndex; i < endIndex; ++i)
  5454. {
  5455. delete data.elements [i];
  5456. data.elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  5457. }
  5458. }
  5459. const int rangeSize = endIndex - startIndex;
  5460. ObjectClass** e = data.elements + startIndex;
  5461. int numToShift = numUsed - endIndex;
  5462. numUsed -= rangeSize;
  5463. while (--numToShift >= 0)
  5464. {
  5465. *e = e [rangeSize];
  5466. ++e;
  5467. }
  5468. if ((numUsed << 1) < data.numAllocated)
  5469. minimiseStorageOverheads();
  5470. }
  5471. }
  5472. /** Removes the last n objects from the array.
  5473. @param howManyToRemove how many objects to remove from the end of the array
  5474. @param deleteObjects whether to also delete the objects that are removed
  5475. @see remove, removeObject, removeRange
  5476. */
  5477. void removeLast (int howManyToRemove = 1,
  5478. const bool deleteObjects = true)
  5479. {
  5480. const ScopedLockType lock (getLock());
  5481. if (howManyToRemove >= numUsed)
  5482. {
  5483. clear (deleteObjects);
  5484. }
  5485. else
  5486. {
  5487. while (--howManyToRemove >= 0)
  5488. remove (numUsed - 1, deleteObjects);
  5489. }
  5490. }
  5491. /** Swaps a pair of objects in the array.
  5492. If either of the indexes passed in is out-of-range, nothing will happen,
  5493. otherwise the two objects at these positions will be exchanged.
  5494. */
  5495. void swap (const int index1,
  5496. const int index2) throw()
  5497. {
  5498. const ScopedLockType lock (getLock());
  5499. if (((unsigned int) index1) < (unsigned int) numUsed
  5500. && ((unsigned int) index2) < (unsigned int) numUsed)
  5501. {
  5502. swapVariables (data.elements [index1],
  5503. data.elements [index2]);
  5504. }
  5505. }
  5506. /** Moves one of the objects to a different position.
  5507. This will move the object to a specified index, shuffling along
  5508. any intervening elements as required.
  5509. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  5510. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  5511. @param currentIndex the index of the object to be moved. If this isn't a
  5512. valid index, then nothing will be done
  5513. @param newIndex the index at which you'd like this object to end up. If this
  5514. is less than zero, it will be moved to the end of the array
  5515. */
  5516. void move (const int currentIndex,
  5517. int newIndex) throw()
  5518. {
  5519. if (currentIndex != newIndex)
  5520. {
  5521. const ScopedLockType lock (getLock());
  5522. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  5523. {
  5524. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  5525. newIndex = numUsed - 1;
  5526. ObjectClass* const value = data.elements [currentIndex];
  5527. if (newIndex > currentIndex)
  5528. {
  5529. memmove (data.elements + currentIndex,
  5530. data.elements + currentIndex + 1,
  5531. (newIndex - currentIndex) * sizeof (ObjectClass*));
  5532. }
  5533. else
  5534. {
  5535. memmove (data.elements + newIndex + 1,
  5536. data.elements + newIndex,
  5537. (currentIndex - newIndex) * sizeof (ObjectClass*));
  5538. }
  5539. data.elements [newIndex] = value;
  5540. }
  5541. }
  5542. }
  5543. /** This swaps the contents of this array with those of another array.
  5544. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  5545. because it just swaps their internal pointers.
  5546. */
  5547. void swapWithArray (OwnedArray& otherArray) throw()
  5548. {
  5549. const ScopedLockType lock1 (getLock());
  5550. const ScopedLockType lock2 (otherArray.getLock());
  5551. data.swapWith (otherArray.data);
  5552. swapVariables (numUsed, otherArray.numUsed);
  5553. }
  5554. /** Reduces the amount of storage being used by the array.
  5555. Arrays typically allocate slightly more storage than they need, and after
  5556. removing elements, they may have quite a lot of unused space allocated.
  5557. This method will reduce the amount of allocated storage to a minimum.
  5558. */
  5559. void minimiseStorageOverheads() throw()
  5560. {
  5561. const ScopedLockType lock (getLock());
  5562. data.shrinkToNoMoreThan (numUsed);
  5563. }
  5564. /** Increases the array's internal storage to hold a minimum number of elements.
  5565. Calling this before adding a large known number of elements means that
  5566. the array won't have to keep dynamically resizing itself as the elements
  5567. are added, and it'll therefore be more efficient.
  5568. */
  5569. void ensureStorageAllocated (const int minNumElements) throw()
  5570. {
  5571. const ScopedLockType lock (getLock());
  5572. data.ensureAllocatedSize (minNumElements);
  5573. }
  5574. /** Sorts the elements in the array.
  5575. This will use a comparator object to sort the elements into order. The object
  5576. passed must have a method of the form:
  5577. @code
  5578. int compareElements (ElementType first, ElementType second);
  5579. @endcode
  5580. ..and this method must return:
  5581. - a value of < 0 if the first comes before the second
  5582. - a value of 0 if the two objects are equivalent
  5583. - a value of > 0 if the second comes before the first
  5584. To improve performance, the compareElements() method can be declared as static or const.
  5585. @param comparator the comparator to use for comparing elements.
  5586. @param retainOrderOfEquivalentItems if this is true, then items
  5587. which the comparator says are equivalent will be
  5588. kept in the order in which they currently appear
  5589. in the array. This is slower to perform, but may
  5590. be important in some cases. If it's false, a faster
  5591. algorithm is used, but equivalent elements may be
  5592. rearranged.
  5593. @see sortArray, indexOfSorted
  5594. */
  5595. template <class ElementComparator>
  5596. void sort (ElementComparator& comparator,
  5597. const bool retainOrderOfEquivalentItems = false) const throw()
  5598. {
  5599. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5600. // avoids getting warning messages about the parameter being unused
  5601. const ScopedLockType lock (getLock());
  5602. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  5603. }
  5604. /** Returns the CriticalSection that locks this array.
  5605. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  5606. an object of ScopedLockType as an RAII lock for it.
  5607. */
  5608. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  5609. /** Returns the type of scoped lock to use for locking this array */
  5610. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  5611. juce_UseDebuggingNewOperator
  5612. private:
  5613. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  5614. int numUsed;
  5615. // disallow copy constructor and assignment
  5616. OwnedArray (const OwnedArray&);
  5617. OwnedArray& operator= (const OwnedArray&);
  5618. };
  5619. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  5620. /*** End of inlined file: juce_OwnedArray.h ***/
  5621. #endif
  5622. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  5623. /*** Start of inlined file: juce_PropertySet.h ***/
  5624. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  5625. #define __JUCE_PROPERTYSET_JUCEHEADER__
  5626. /*** Start of inlined file: juce_StringPairArray.h ***/
  5627. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5628. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5629. /*** Start of inlined file: juce_StringArray.h ***/
  5630. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  5631. #define __JUCE_STRINGARRAY_JUCEHEADER__
  5632. /**
  5633. A special array for holding a list of strings.
  5634. @see String, StringPairArray
  5635. */
  5636. class JUCE_API StringArray
  5637. {
  5638. public:
  5639. /** Creates an empty string array */
  5640. StringArray() throw();
  5641. /** Creates a copy of another string array */
  5642. StringArray (const StringArray& other);
  5643. /** Creates an array containing a single string. */
  5644. explicit StringArray (const String& firstValue);
  5645. /** Creates a copy of an array of string literals.
  5646. @param strings an array of strings to add. Null pointers in the array will be
  5647. treated as empty strings
  5648. @param numberOfStrings how many items there are in the array
  5649. */
  5650. StringArray (const juce_wchar* const* strings, int numberOfStrings);
  5651. /** Creates a copy of an array of string literals.
  5652. @param strings an array of strings to add. Null pointers in the array will be
  5653. treated as empty strings
  5654. @param numberOfStrings how many items there are in the array
  5655. */
  5656. StringArray (const char* const* strings, int numberOfStrings);
  5657. /** Creates a copy of a null-terminated array of string literals.
  5658. Each item from the array passed-in is added, until it encounters a null pointer,
  5659. at which point it stops.
  5660. */
  5661. explicit StringArray (const juce_wchar* const* strings);
  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 char* const* strings);
  5667. /** Destructor. */
  5668. ~StringArray();
  5669. /** Copies the contents of another string array into this one */
  5670. StringArray& operator= (const StringArray& other);
  5671. /** Compares two arrays.
  5672. Comparisons are case-sensitive.
  5673. @returns true only if the other array contains exactly the same strings in the same order
  5674. */
  5675. bool operator== (const StringArray& other) const throw();
  5676. /** Compares two arrays.
  5677. Comparisons are case-sensitive.
  5678. @returns false if the other array contains exactly the same strings in the same order
  5679. */
  5680. bool operator!= (const StringArray& other) const throw();
  5681. /** Returns the number of strings in the array */
  5682. inline int size() const throw() { return strings.size(); };
  5683. /** Returns one of the strings from the array.
  5684. If the index is out-of-range, an empty string is returned.
  5685. Obviously the reference returned shouldn't be stored for later use, as the
  5686. string it refers to may disappear when the array changes.
  5687. */
  5688. const String& operator[] (int index) const throw();
  5689. /** Returns a reference to one of the strings in the array.
  5690. This lets you modify a string in-place in the array, but you must be sure that
  5691. the index is in-range.
  5692. */
  5693. String& getReference (int index) throw();
  5694. /** Searches for a string in the array.
  5695. The comparison will be case-insensitive if the ignoreCase parameter is true.
  5696. @returns true if the string is found inside the array
  5697. */
  5698. bool contains (const String& stringToLookFor,
  5699. bool ignoreCase = false) const;
  5700. /** Searches for a string in the array.
  5701. The comparison will be case-insensitive if the ignoreCase parameter is true.
  5702. @param stringToLookFor the string to try to find
  5703. @param ignoreCase whether the comparison should be case-insensitive
  5704. @param startIndex the first index to start searching from
  5705. @returns the index of the first occurrence of the string in this array,
  5706. or -1 if it isn't found.
  5707. */
  5708. int indexOf (const String& stringToLookFor,
  5709. bool ignoreCase = false,
  5710. int startIndex = 0) const;
  5711. /** Appends a string at the end of the array. */
  5712. void add (const String& stringToAdd);
  5713. /** Inserts a string into the array.
  5714. This will insert a string into the array at the given index, moving
  5715. up the other elements to make room for it.
  5716. If the index is less than zero or greater than the size of the array,
  5717. the new string will be added to the end of the array.
  5718. */
  5719. void insert (int index, const String& stringToAdd);
  5720. /** Adds a string to the array as long as it's not already in there.
  5721. The search can optionally be case-insensitive.
  5722. */
  5723. void addIfNotAlreadyThere (const String& stringToAdd, bool ignoreCase = false);
  5724. /** Replaces one of the strings in the array with another one.
  5725. If the index is higher than the array's size, the new string will be
  5726. added to the end of the array; if it's less than zero nothing happens.
  5727. */
  5728. void set (int index, const String& newString);
  5729. /** Appends some strings from another array to the end of this one.
  5730. @param other the array to add
  5731. @param startIndex the first element of the other array to add
  5732. @param numElementsToAdd the maximum number of elements to add (if this is
  5733. less than zero, they are all added)
  5734. */
  5735. void addArray (const StringArray& other,
  5736. int startIndex = 0,
  5737. int numElementsToAdd = -1);
  5738. /** Breaks up a string into tokens and adds them to this array.
  5739. This will tokenise the given string using whitespace characters as the
  5740. token delimiters, and will add these tokens to the end of the array.
  5741. @returns the number of tokens added
  5742. */
  5743. int addTokens (const String& stringToTokenise,
  5744. bool preserveQuotedStrings);
  5745. /** Breaks up a string into tokens and adds them to this array.
  5746. This will tokenise the given string (using the string passed in to define the
  5747. token delimiters), and will add these tokens to the end of the array.
  5748. @param stringToTokenise the string to tokenise
  5749. @param breakCharacters a string of characters, any of which will be considered
  5750. to be a token delimiter.
  5751. @param quoteCharacters if this string isn't empty, it defines a set of characters
  5752. which are treated as quotes. Any text occurring
  5753. between quotes is not broken up into tokens.
  5754. @returns the number of tokens added
  5755. */
  5756. int addTokens (const String& stringToTokenise,
  5757. const String& breakCharacters,
  5758. const String& quoteCharacters);
  5759. /** Breaks up a string into lines and adds them to this array.
  5760. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  5761. to the array. Line-break characters are omitted from the strings that are added to
  5762. the array.
  5763. */
  5764. int addLines (const String& stringToBreakUp);
  5765. /** Removes all elements from the array. */
  5766. void clear();
  5767. /** Removes a string from the array.
  5768. If the index is out-of-range, no action will be taken.
  5769. */
  5770. void remove (int index);
  5771. /** Finds a string in the array and removes it.
  5772. This will remove the first occurrence of the given string from the array. The
  5773. comparison may be case-insensitive depending on the ignoreCase parameter.
  5774. */
  5775. void removeString (const String& stringToRemove,
  5776. bool ignoreCase = false);
  5777. /** Removes a range of elements from the array.
  5778. This will remove a set of elements, starting from the given index,
  5779. and move subsequent elements down to close the gap.
  5780. If the range extends beyond the bounds of the array, it will
  5781. be safely clipped to the size of the array.
  5782. @param startIndex the index of the first element to remove
  5783. @param numberToRemove how many elements should be removed
  5784. */
  5785. void removeRange (int startIndex, int numberToRemove);
  5786. /** Removes any duplicated elements from the array.
  5787. If any string appears in the array more than once, only the first occurrence of
  5788. it will be retained.
  5789. @param ignoreCase whether to use a case-insensitive comparison
  5790. */
  5791. void removeDuplicates (bool ignoreCase);
  5792. /** Removes empty strings from the array.
  5793. @param removeWhitespaceStrings if true, strings that only contain whitespace
  5794. characters will also be removed
  5795. */
  5796. void removeEmptyStrings (bool removeWhitespaceStrings = true);
  5797. /** Moves one of the strings to a different position.
  5798. This will move the string to a specified index, shuffling along
  5799. any intervening elements as required.
  5800. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  5801. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  5802. @param currentIndex the index of the value to be moved. If this isn't a
  5803. valid index, then nothing will be done
  5804. @param newIndex the index at which you'd like this value to end up. If this
  5805. is less than zero, the value will be moved to the end
  5806. of the array
  5807. */
  5808. void move (int currentIndex, int newIndex) throw();
  5809. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  5810. void trim();
  5811. /** Adds numbers to the strings in the array, to make each string unique.
  5812. This will add numbers to the ends of groups of similar strings.
  5813. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  5814. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  5815. @param appendNumberToFirstInstance whether the first of a group of similar strings
  5816. also has a number appended to it.
  5817. @param preNumberString when adding a number, this string is added before the number.
  5818. If you pass 0, a default string will be used, which adds
  5819. brackets around the number.
  5820. @param postNumberString this string is appended after any numbers that are added.
  5821. If you pass 0, a default string will be used, which adds
  5822. brackets around the number.
  5823. */
  5824. void appendNumbersToDuplicates (bool ignoreCaseWhenComparing,
  5825. bool appendNumberToFirstInstance,
  5826. const juce_wchar* preNumberString = 0,
  5827. const juce_wchar* postNumberString = 0);
  5828. /** Joins the strings in the array together into one string.
  5829. This will join a range of elements from the array into a string, separating
  5830. them with a given string.
  5831. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  5832. @param separatorString the string to insert between all the strings
  5833. @param startIndex the first element to join
  5834. @param numberOfElements how many elements to join together. If this is less
  5835. than zero, all available elements will be used.
  5836. */
  5837. const String joinIntoString (const String& separatorString,
  5838. int startIndex = 0,
  5839. int numberOfElements = -1) const;
  5840. /** Sorts the array into alphabetical order.
  5841. @param ignoreCase if true, the comparisons used will be case-sensitive.
  5842. */
  5843. void sort (bool ignoreCase);
  5844. /** Reduces the amount of storage being used by the array.
  5845. Arrays typically allocate slightly more storage than they need, and after
  5846. removing elements, they may have quite a lot of unused space allocated.
  5847. This method will reduce the amount of allocated storage to a minimum.
  5848. */
  5849. void minimiseStorageOverheads();
  5850. juce_UseDebuggingNewOperator
  5851. private:
  5852. Array <String> strings;
  5853. };
  5854. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  5855. /*** End of inlined file: juce_StringArray.h ***/
  5856. /**
  5857. A container for holding a set of strings which are keyed by another string.
  5858. @see StringArray
  5859. */
  5860. class JUCE_API StringPairArray
  5861. {
  5862. public:
  5863. /** Creates an empty array */
  5864. StringPairArray (bool ignoreCaseWhenComparingKeys = true);
  5865. /** Creates a copy of another array */
  5866. StringPairArray (const StringPairArray& other);
  5867. /** Destructor. */
  5868. ~StringPairArray();
  5869. /** Copies the contents of another string array into this one */
  5870. StringPairArray& operator= (const StringPairArray& other);
  5871. /** Compares two arrays.
  5872. Comparisons are case-sensitive.
  5873. @returns true only if the other array contains exactly the same strings with the same keys
  5874. */
  5875. bool operator== (const StringPairArray& other) const;
  5876. /** Compares two arrays.
  5877. Comparisons are case-sensitive.
  5878. @returns false if the other array contains exactly the same strings with the same keys
  5879. */
  5880. bool operator!= (const StringPairArray& other) const;
  5881. /** Finds the value corresponding to a key string.
  5882. If no such key is found, this will just return an empty string. To check whether
  5883. a given key actually exists (because it might actually be paired with an empty string), use
  5884. the getAllKeys() method to obtain a list.
  5885. Obviously the reference returned shouldn't be stored for later use, as the
  5886. string it refers to may disappear when the array changes.
  5887. @see getValue
  5888. */
  5889. const String& operator[] (const String& key) const;
  5890. /** Finds the value corresponding to a key string.
  5891. If no such key is found, this will just return the value provided as a default.
  5892. @see operator[]
  5893. */
  5894. const String getValue (const String& key, const String& defaultReturnValue) const;
  5895. /** Returns a list of all keys in the array. */
  5896. const StringArray& getAllKeys() const throw() { return keys; }
  5897. /** Returns a list of all values in the array. */
  5898. const StringArray& getAllValues() const throw() { return values; }
  5899. /** Returns the number of strings in the array */
  5900. inline int size() const throw() { return keys.size(); };
  5901. /** Adds or amends a key/value pair.
  5902. If a value already exists with this key, its value will be overwritten,
  5903. otherwise the key/value pair will be added to the array.
  5904. */
  5905. void set (const String& key, const String& value);
  5906. /** Adds the items from another array to this one.
  5907. This is equivalent to using set() to add each of the pairs from the other array.
  5908. */
  5909. void addArray (const StringPairArray& other);
  5910. /** Removes all elements from the array. */
  5911. void clear();
  5912. /** Removes a string from the array based on its key.
  5913. If the key isn't found, nothing will happen.
  5914. */
  5915. void remove (const String& key);
  5916. /** Removes a string from the array based on its index.
  5917. If the index is out-of-range, no action will be taken.
  5918. */
  5919. void remove (int index);
  5920. /** Indicates whether to use a case-insensitive search when looking up a key string.
  5921. */
  5922. void setIgnoresCase (bool shouldIgnoreCase);
  5923. /** Returns a descriptive string containing the items.
  5924. This is handy for dumping the contents of an array.
  5925. */
  5926. const String getDescription() const;
  5927. /** Reduces the amount of storage being used by the array.
  5928. Arrays typically allocate slightly more storage than they need, and after
  5929. removing elements, they may have quite a lot of unused space allocated.
  5930. This method will reduce the amount of allocated storage to a minimum.
  5931. */
  5932. void minimiseStorageOverheads();
  5933. juce_UseDebuggingNewOperator
  5934. private:
  5935. StringArray keys, values;
  5936. bool ignoreCase;
  5937. };
  5938. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5939. /*** End of inlined file: juce_StringPairArray.h ***/
  5940. /*** Start of inlined file: juce_XmlElement.h ***/
  5941. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  5942. #define __JUCE_XMLELEMENT_JUCEHEADER__
  5943. /*** Start of inlined file: juce_File.h ***/
  5944. #ifndef __JUCE_FILE_JUCEHEADER__
  5945. #define __JUCE_FILE_JUCEHEADER__
  5946. /*** Start of inlined file: juce_Time.h ***/
  5947. #ifndef __JUCE_TIME_JUCEHEADER__
  5948. #define __JUCE_TIME_JUCEHEADER__
  5949. /*** Start of inlined file: juce_RelativeTime.h ***/
  5950. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  5951. #define __JUCE_RELATIVETIME_JUCEHEADER__
  5952. /** A relative measure of time.
  5953. The time is stored as a number of seconds, at double-precision floating
  5954. point accuracy, and may be positive or negative.
  5955. If you need an absolute time, (i.e. a date + time), see the Time class.
  5956. */
  5957. class JUCE_API RelativeTime
  5958. {
  5959. public:
  5960. /** Creates a RelativeTime.
  5961. @param seconds the number of seconds, which may be +ve or -ve.
  5962. @see milliseconds, minutes, hours, days, weeks
  5963. */
  5964. explicit RelativeTime (double seconds = 0.0) throw();
  5965. /** Copies another relative time. */
  5966. RelativeTime (const RelativeTime& other) throw();
  5967. /** Copies another relative time. */
  5968. RelativeTime& operator= (const RelativeTime& other) throw();
  5969. /** Destructor. */
  5970. ~RelativeTime() throw();
  5971. /** Creates a new RelativeTime object representing a number of milliseconds.
  5972. @see minutes, hours, days, weeks
  5973. */
  5974. static const RelativeTime milliseconds (int milliseconds) throw();
  5975. /** Creates a new RelativeTime object representing a number of milliseconds.
  5976. @see minutes, hours, days, weeks
  5977. */
  5978. static const RelativeTime milliseconds (int64 milliseconds) throw();
  5979. /** Creates a new RelativeTime object representing a number of minutes.
  5980. @see milliseconds, hours, days, weeks
  5981. */
  5982. static const RelativeTime minutes (double numberOfMinutes) throw();
  5983. /** Creates a new RelativeTime object representing a number of hours.
  5984. @see milliseconds, minutes, days, weeks
  5985. */
  5986. static const RelativeTime hours (double numberOfHours) throw();
  5987. /** Creates a new RelativeTime object representing a number of days.
  5988. @see milliseconds, minutes, hours, weeks
  5989. */
  5990. static const RelativeTime days (double numberOfDays) throw();
  5991. /** Creates a new RelativeTime object representing a number of weeks.
  5992. @see milliseconds, minutes, hours, days
  5993. */
  5994. static const RelativeTime weeks (double numberOfWeeks) throw();
  5995. /** Returns the number of milliseconds this time represents.
  5996. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  5997. */
  5998. int64 inMilliseconds() const throw();
  5999. /** Returns the number of seconds this time represents.
  6000. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  6001. */
  6002. double inSeconds() const throw() { return seconds; }
  6003. /** Returns the number of minutes this time represents.
  6004. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  6005. */
  6006. double inMinutes() const throw();
  6007. /** Returns the number of hours this time represents.
  6008. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  6009. */
  6010. double inHours() const throw();
  6011. /** Returns the number of days this time represents.
  6012. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  6013. */
  6014. double inDays() const throw();
  6015. /** Returns the number of weeks this time represents.
  6016. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  6017. */
  6018. double inWeeks() const throw();
  6019. /** Returns a readable textual description of the time.
  6020. The exact format of the string returned will depend on
  6021. the magnitude of the time - e.g.
  6022. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  6023. so that only the two most significant units are printed.
  6024. The returnValueForZeroTime value is the result that is returned if the
  6025. length is zero. Depending on your application you might want to use this
  6026. to return something more relevant like "empty" or "0 secs", etc.
  6027. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  6028. */
  6029. const String getDescription (const String& returnValueForZeroTime = "0") const throw();
  6030. /** Compares two RelativeTimes. */
  6031. bool operator== (const RelativeTime& other) const throw();
  6032. /** Compares two RelativeTimes. */
  6033. bool operator!= (const RelativeTime& other) const throw();
  6034. /** Compares two RelativeTimes. */
  6035. bool operator> (const RelativeTime& other) const throw();
  6036. /** Compares two RelativeTimes. */
  6037. bool operator< (const RelativeTime& other) const throw();
  6038. /** Compares two RelativeTimes. */
  6039. bool operator>= (const RelativeTime& other) const throw();
  6040. /** Compares two RelativeTimes. */
  6041. bool operator<= (const RelativeTime& other) const throw();
  6042. /** Adds another RelativeTime to this one and returns the result. */
  6043. const RelativeTime operator+ (const RelativeTime& timeToAdd) const throw();
  6044. /** Subtracts another RelativeTime from this one and returns the result. */
  6045. const RelativeTime operator- (const RelativeTime& timeToSubtract) const throw();
  6046. /** Adds a number of seconds to this RelativeTime and returns the result. */
  6047. const RelativeTime operator+ (double secondsToAdd) const throw();
  6048. /** Subtracts a number of seconds from this RelativeTime and returns the result. */
  6049. const RelativeTime operator- (double secondsToSubtract) const throw();
  6050. /** Adds another RelativeTime to this one. */
  6051. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  6052. /** Subtracts another RelativeTime from this one. */
  6053. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  6054. /** Adds a number of seconds to this time. */
  6055. const RelativeTime& operator+= (double secondsToAdd) throw();
  6056. /** Subtracts a number of seconds from this time. */
  6057. const RelativeTime& operator-= (double secondsToSubtract) throw();
  6058. juce_UseDebuggingNewOperator
  6059. private:
  6060. double seconds;
  6061. };
  6062. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  6063. /*** End of inlined file: juce_RelativeTime.h ***/
  6064. /**
  6065. Holds an absolute date and time.
  6066. Internally, the time is stored at millisecond precision.
  6067. @see RelativeTime
  6068. */
  6069. class JUCE_API Time
  6070. {
  6071. public:
  6072. /** Creates a Time object.
  6073. This default constructor creates a time of 1st January 1970, (which is
  6074. represented internally as 0ms).
  6075. To create a time object representing the current time, use getCurrentTime().
  6076. @see getCurrentTime
  6077. */
  6078. Time() throw();
  6079. /** Creates a copy of another Time object. */
  6080. Time (const Time& other) throw();
  6081. /** Creates a time based on a number of milliseconds.
  6082. The internal millisecond count is set to 0 (1st January 1970). To create a
  6083. time object set to the current time, use getCurrentTime().
  6084. @param millisecondsSinceEpoch the number of milliseconds since the unix
  6085. 'epoch' (midnight Jan 1st 1970).
  6086. @see getCurrentTime, currentTimeMillis
  6087. */
  6088. Time (int64 millisecondsSinceEpoch) throw();
  6089. /** Creates a time from a set of date components.
  6090. The timezone is assumed to be whatever the system is using as its locale.
  6091. @param year the year, in 4-digit format, e.g. 2004
  6092. @param month the month, in the range 0 to 11
  6093. @param day the day of the month, in the range 1 to 31
  6094. @param hours hours in 24-hour clock format, 0 to 23
  6095. @param minutes minutes 0 to 59
  6096. @param seconds seconds 0 to 59
  6097. @param milliseconds milliseconds 0 to 999
  6098. @param useLocalTime if true, encode using the current machine's local time; if
  6099. false, it will always work in GMT.
  6100. */
  6101. Time (int year,
  6102. int month,
  6103. int day,
  6104. int hours,
  6105. int minutes,
  6106. int seconds = 0,
  6107. int milliseconds = 0,
  6108. bool useLocalTime = true) throw();
  6109. /** Destructor. */
  6110. ~Time() throw();
  6111. /** Copies this time from another one. */
  6112. Time& operator= (const Time& other) throw();
  6113. /** Returns a Time object that is set to the current system time.
  6114. @see currentTimeMillis
  6115. */
  6116. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  6117. /** Returns the time as a number of milliseconds.
  6118. @returns the number of milliseconds this Time object represents, since
  6119. midnight jan 1st 1970.
  6120. @see getMilliseconds
  6121. */
  6122. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  6123. /** Returns the year.
  6124. A 4-digit format is used, e.g. 2004.
  6125. */
  6126. int getYear() const throw();
  6127. /** Returns the number of the month.
  6128. The value returned is in the range 0 to 11.
  6129. @see getMonthName
  6130. */
  6131. int getMonth() const throw();
  6132. /** Returns the name of the month.
  6133. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  6134. it'll return the long form, e.g. "January"
  6135. @see getMonth
  6136. */
  6137. const String getMonthName (bool threeLetterVersion) const throw();
  6138. /** Returns the day of the month.
  6139. The value returned is in the range 1 to 31.
  6140. */
  6141. int getDayOfMonth() const throw();
  6142. /** Returns the number of the day of the week.
  6143. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  6144. */
  6145. int getDayOfWeek() const throw();
  6146. /** Returns the name of the weekday.
  6147. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  6148. false, it'll return the full version, e.g. "Tuesday".
  6149. */
  6150. const String getWeekdayName (bool threeLetterVersion) const throw();
  6151. /** Returns the number of hours since midnight.
  6152. This is in 24-hour clock format, in the range 0 to 23.
  6153. @see getHoursInAmPmFormat, isAfternoon
  6154. */
  6155. int getHours() const throw();
  6156. /** Returns true if the time is in the afternoon.
  6157. So it returns true for "PM", false for "AM".
  6158. @see getHoursInAmPmFormat, getHours
  6159. */
  6160. bool isAfternoon() const throw();
  6161. /** Returns the hours in 12-hour clock format.
  6162. This will return a value 1 to 12 - use isAfternoon() to find out
  6163. whether this is in the afternoon or morning.
  6164. @see getHours, isAfternoon
  6165. */
  6166. int getHoursInAmPmFormat() const throw();
  6167. /** Returns the number of minutes, 0 to 59. */
  6168. int getMinutes() const throw();
  6169. /** Returns the number of seconds, 0 to 59. */
  6170. int getSeconds() const throw();
  6171. /** Returns the number of milliseconds, 0 to 999.
  6172. Unlike toMilliseconds(), this just returns the position within the
  6173. current second rather than the total number since the epoch.
  6174. @see toMilliseconds
  6175. */
  6176. int getMilliseconds() const throw();
  6177. /** Returns true if the local timezone uses a daylight saving correction. */
  6178. bool isDaylightSavingTime() const throw();
  6179. /** Returns a 3-character string to indicate the local timezone. */
  6180. const String getTimeZone() const throw();
  6181. /** Quick way of getting a string version of a date and time.
  6182. For a more powerful way of formatting the date and time, see the formatted() method.
  6183. @param includeDate whether to include the date in the string
  6184. @param includeTime whether to include the time in the string
  6185. @param includeSeconds if the time is being included, this provides an option not to include
  6186. the seconds in it
  6187. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  6188. hour notation.
  6189. @see formatted
  6190. */
  6191. const String toString (bool includeDate,
  6192. bool includeTime,
  6193. bool includeSeconds = true,
  6194. bool use24HourClock = false) const throw();
  6195. /** Converts this date/time to a string with a user-defined format.
  6196. This uses the C strftime() function to format this time as a string. To save you
  6197. looking it up, these are the escape codes that strftime uses (other codes might
  6198. work on some platforms and not others, but these are the common ones):
  6199. %a is replaced by the locale's abbreviated weekday name.
  6200. %A is replaced by the locale's full weekday name.
  6201. %b is replaced by the locale's abbreviated month name.
  6202. %B is replaced by the locale's full month name.
  6203. %c is replaced by the locale's appropriate date and time representation.
  6204. %d is replaced by the day of the month as a decimal number [01,31].
  6205. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  6206. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  6207. %j is replaced by the day of the year as a decimal number [001,366].
  6208. %m is replaced by the month as a decimal number [01,12].
  6209. %M is replaced by the minute as a decimal number [00,59].
  6210. %p is replaced by the locale's equivalent of either a.m. or p.m.
  6211. %S is replaced by the second as a decimal number [00,61].
  6212. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  6213. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  6214. %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.
  6215. %x is replaced by the locale's appropriate date representation.
  6216. %X is replaced by the locale's appropriate time representation.
  6217. %y is replaced by the year without century as a decimal number [00,99].
  6218. %Y is replaced by the year with century as a decimal number.
  6219. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  6220. %% is replaced by %.
  6221. @see toString
  6222. */
  6223. const String formatted (const String& format) const throw();
  6224. /** Adds a RelativeTime to this time and returns the result. */
  6225. const Time operator+ (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch + delta.inMilliseconds()); }
  6226. /** Subtracts a RelativeTime from this time and returns the result. */
  6227. const Time operator- (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch - delta.inMilliseconds()); }
  6228. /** Returns the relative time difference between this time and another one. */
  6229. const RelativeTime operator- (const Time& other) const throw() { return RelativeTime::milliseconds (millisSinceEpoch - other.millisSinceEpoch); }
  6230. /** Compares two Time objects. */
  6231. bool operator== (const Time& other) const throw() { return millisSinceEpoch == other.millisSinceEpoch; }
  6232. /** Compares two Time objects. */
  6233. bool operator!= (const Time& other) const throw() { return millisSinceEpoch != other.millisSinceEpoch; }
  6234. /** Compares two Time objects. */
  6235. bool operator< (const Time& other) const throw() { return millisSinceEpoch < other.millisSinceEpoch; }
  6236. /** Compares two Time objects. */
  6237. bool operator<= (const Time& other) const throw() { return millisSinceEpoch <= other.millisSinceEpoch; }
  6238. /** Compares two Time objects. */
  6239. bool operator> (const Time& other) const throw() { return millisSinceEpoch > other.millisSinceEpoch; }
  6240. /** Compares two Time objects. */
  6241. bool operator>= (const Time& other) const throw() { return millisSinceEpoch >= other.millisSinceEpoch; }
  6242. /** Tries to set the computer's clock.
  6243. @returns true if this succeeds, although depending on the system, the
  6244. application might not have sufficient privileges to do this.
  6245. */
  6246. bool setSystemTimeToThisTime() const;
  6247. /** Returns the name of a day of the week.
  6248. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  6249. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  6250. false, it'll return the full version, e.g. "Tuesday".
  6251. */
  6252. static const String getWeekdayName (int dayNumber,
  6253. bool threeLetterVersion) throw();
  6254. /** Returns the name of one of the months.
  6255. @param monthNumber the month, 0 to 11
  6256. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  6257. it'll return the long form, e.g. "January"
  6258. */
  6259. static const String getMonthName (int monthNumber,
  6260. bool threeLetterVersion) throw();
  6261. // Static methods for getting system timers directly..
  6262. /** Returns the current system time.
  6263. Returns the number of milliseconds since midnight jan 1st 1970.
  6264. Should be accurate to within a few millisecs, depending on platform,
  6265. hardware, etc.
  6266. */
  6267. static int64 currentTimeMillis() throw();
  6268. /** Returns the number of millisecs since system startup.
  6269. Should be accurate to within a few millisecs, depending on platform,
  6270. hardware, etc.
  6271. @see getApproximateMillisecondCounter
  6272. */
  6273. static uint32 getMillisecondCounter() throw();
  6274. /** Returns the number of millisecs since system startup.
  6275. Same as getMillisecondCounter(), but returns a more accurate value, using
  6276. the high-res timer.
  6277. @see getMillisecondCounter
  6278. */
  6279. static double getMillisecondCounterHiRes() throw();
  6280. /** Waits until the getMillisecondCounter() reaches a given value.
  6281. This will make the thread sleep as efficiently as it can while it's waiting.
  6282. */
  6283. static void waitForMillisecondCounter (uint32 targetTime) throw();
  6284. /** Less-accurate but faster version of getMillisecondCounter().
  6285. This will return the last value that getMillisecondCounter() returned, so doesn't
  6286. need to make a system call, but is less accurate - it shouldn't be more than
  6287. 100ms away from the correct time, though, so is still accurate enough for a
  6288. lot of purposes.
  6289. @see getMillisecondCounter
  6290. */
  6291. static uint32 getApproximateMillisecondCounter() throw();
  6292. // High-resolution timers..
  6293. /** Returns the current high-resolution counter's tick-count.
  6294. This is a similar idea to getMillisecondCounter(), but with a higher
  6295. resolution.
  6296. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  6297. secondsToHighResolutionTicks
  6298. */
  6299. static int64 getHighResolutionTicks() throw();
  6300. /** Returns the resolution of the high-resolution counter in ticks per second.
  6301. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  6302. secondsToHighResolutionTicks
  6303. */
  6304. static int64 getHighResolutionTicksPerSecond() throw();
  6305. /** Converts a number of high-resolution ticks into seconds.
  6306. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  6307. secondsToHighResolutionTicks
  6308. */
  6309. static double highResolutionTicksToSeconds (int64 ticks) throw();
  6310. /** Converts a number seconds into high-resolution ticks.
  6311. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  6312. highResolutionTicksToSeconds
  6313. */
  6314. static int64 secondsToHighResolutionTicks (double seconds) throw();
  6315. private:
  6316. int64 millisSinceEpoch;
  6317. };
  6318. #endif // __JUCE_TIME_JUCEHEADER__
  6319. /*** End of inlined file: juce_Time.h ***/
  6320. class FileInputStream;
  6321. class FileOutputStream;
  6322. /**
  6323. Represents a local file or directory.
  6324. This class encapsulates the absolute pathname of a file or directory, and
  6325. has methods for finding out about the file and changing its properties.
  6326. To read or write to the file, there are methods for returning an input or
  6327. output stream.
  6328. @see FileInputStream, FileOutputStream
  6329. */
  6330. class JUCE_API File
  6331. {
  6332. public:
  6333. /** Creates an (invalid) file object.
  6334. The file is initially set to an empty path, so getFullPath() will return
  6335. an empty string, and comparing the file to File::nonexistent will return
  6336. true.
  6337. You can use its operator= method to point it at a proper file.
  6338. */
  6339. File() {}
  6340. /** Creates a file from an absolute path.
  6341. If the path supplied is a relative path, it is taken to be relative
  6342. to the current working directory (see File::getCurrentWorkingDirectory()),
  6343. but this isn't a recommended way of creating a file, because you
  6344. never know what the CWD is going to be.
  6345. On the Mac/Linux, the path can include "~" notation for referring to
  6346. user home directories.
  6347. */
  6348. File (const String& path);
  6349. /** Creates a copy of another file object. */
  6350. File (const File& other);
  6351. /** Destructor. */
  6352. ~File() {}
  6353. /** Sets the file based on an absolute pathname.
  6354. If the path supplied is a relative path, it is taken to be relative
  6355. to the current working directory (see File::getCurrentWorkingDirectory()),
  6356. but this isn't a recommended way of creating a file, because you
  6357. never know what the CWD is going to be.
  6358. On the Mac/Linux, the path can include "~" notation for referring to
  6359. user home directories.
  6360. */
  6361. File& operator= (const String& newFilePath);
  6362. /** Copies from another file object. */
  6363. File& operator= (const File& otherFile);
  6364. /** This static constant is used for referring to an 'invalid' file. */
  6365. static const File nonexistent;
  6366. /** Checks whether the file actually exists.
  6367. @returns true if the file exists, either as a file or a directory.
  6368. @see existsAsFile, isDirectory
  6369. */
  6370. bool exists() const;
  6371. /** Checks whether the file exists and is a file rather than a directory.
  6372. @returns true only if this is a real file, false if it's a directory
  6373. or doesn't exist
  6374. @see exists, isDirectory
  6375. */
  6376. bool existsAsFile() const;
  6377. /** Checks whether the file is a directory that exists.
  6378. @returns true only if the file is a directory which actually exists, so
  6379. false if it's a file or doesn't exist at all
  6380. @see exists, existsAsFile
  6381. */
  6382. bool isDirectory() const;
  6383. /** Returns the size of the file in bytes.
  6384. @returns the number of bytes in the file, or 0 if it doesn't exist.
  6385. */
  6386. int64 getSize() const;
  6387. /** Utility function to convert a file size in bytes to a neat string description.
  6388. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  6389. 2000000 would produce "2 MB", etc.
  6390. */
  6391. static const String descriptionOfSizeInBytes (int64 bytes);
  6392. /** Returns the complete, absolute path of this file.
  6393. This includes the filename and all its parent folders. On Windows it'll
  6394. also include the drive letter prefix; on Mac or Linux it'll be a complete
  6395. path starting from the root folder.
  6396. If you just want the file's name, you should use getFileName() or
  6397. getFileNameWithoutExtension().
  6398. @see getFileName, getRelativePathFrom
  6399. */
  6400. const String& getFullPathName() const throw() { return fullPath; }
  6401. /** Returns the last section of the pathname.
  6402. Returns just the final part of the path - e.g. if the whole path
  6403. is "/moose/fish/foo.txt" this will return "foo.txt".
  6404. For a directory, it returns the final part of the path - e.g. for the
  6405. directory "/moose/fish" it'll return "fish".
  6406. If the filename begins with a dot, it'll return the whole filename, e.g. for
  6407. "/moose/.fish", it'll return ".fish"
  6408. @see getFullPathName, getFileNameWithoutExtension
  6409. */
  6410. const String getFileName() const;
  6411. /** Creates a relative path that refers to a file relatively to a given directory.
  6412. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  6413. would return "../../foo.txt".
  6414. If it's not possible to navigate from one file to the other, an absolute
  6415. path is returned. If the paths are invalid, an empty string may also be
  6416. returned.
  6417. @param directoryToBeRelativeTo the directory which the resultant string will
  6418. be relative to. If this is actually a file rather than
  6419. a directory, its parent directory will be used instead.
  6420. If it doesn't exist, it's assumed to be a directory.
  6421. @see getChildFile, isAbsolutePath
  6422. */
  6423. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  6424. /** Returns the file's extension.
  6425. Returns the file extension of this file, also including the dot.
  6426. e.g. "/moose/fish/foo.txt" would return ".txt"
  6427. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  6428. */
  6429. const String getFileExtension() const;
  6430. /** Checks whether the file has a given extension.
  6431. @param extensionToTest the extension to look for - it doesn't matter whether or
  6432. not this string has a dot at the start, so ".wav" and "wav"
  6433. will have the same effect. The comparison used is
  6434. case-insensitve. To compare with multiple extensions, this
  6435. parameter can contain multiple strings, separated by semi-colons -
  6436. so, for example: hasFileExtension (".jpeg;png;gif") would return
  6437. true if the file has any of those three extensions.
  6438. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  6439. */
  6440. bool hasFileExtension (const String& extensionToTest) const;
  6441. /** Returns a version of this file with a different file extension.
  6442. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  6443. @param newExtension the new extension, either with or without a dot at the start (this
  6444. doesn't make any difference). To get remove a file's extension altogether,
  6445. pass an empty string into this function.
  6446. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  6447. */
  6448. const File withFileExtension (const String& newExtension) const;
  6449. /** Returns the last part of the filename, without its file extension.
  6450. e.g. for "/moose/fish/foo.txt" this will return "foo".
  6451. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  6452. */
  6453. const String getFileNameWithoutExtension() const;
  6454. /** Returns a 32-bit hash-code that identifies this file.
  6455. This is based on the filename. Obviously it's possible, although unlikely, that
  6456. two files will have the same hash-code.
  6457. */
  6458. int hashCode() const;
  6459. /** Returns a 64-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. int64 hashCode64() const;
  6464. /** Returns a file based on a relative path.
  6465. This will find a child file or directory of the current object.
  6466. e.g.
  6467. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  6468. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  6469. If the string is actually an absolute path, it will be treated as such, e.g.
  6470. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  6471. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  6472. */
  6473. const File getChildFile (String relativePath) const;
  6474. /** Returns a file which is in the same directory as this one.
  6475. This is equivalent to getParentDirectory().getChildFile (name).
  6476. @see getChildFile, getParentDirectory
  6477. */
  6478. const File getSiblingFile (const String& siblingFileName) const;
  6479. /** Returns the directory that contains this file or directory.
  6480. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  6481. */
  6482. const File getParentDirectory() const;
  6483. /** Checks whether a file is somewhere inside a directory.
  6484. Returns true if this file is somewhere inside a subdirectory of the directory
  6485. that is passed in. Neither file actually has to exist, because the function
  6486. just checks the paths for similarities.
  6487. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  6488. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  6489. */
  6490. bool isAChildOf (const File& potentialParentDirectory) const;
  6491. /** Chooses a filename relative to this one that doesn't already exist.
  6492. If this file is a directory, this will return a child file of this
  6493. directory that doesn't exist, by adding numbers to a prefix and suffix until
  6494. it finds one that isn't already there.
  6495. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  6496. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  6497. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  6498. @param prefix the string to use for the filename before the number
  6499. @param suffix the string to add to the filename after the number
  6500. @param putNumbersInBrackets if true, this will create filenames in the
  6501. format "prefix(number)suffix", if false, it will leave the
  6502. brackets out.
  6503. */
  6504. const File getNonexistentChildFile (const String& prefix,
  6505. const String& suffix,
  6506. bool putNumbersInBrackets = true) const;
  6507. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  6508. If this file doesn't exist, this will just return itself, otherwise it
  6509. will return an appropriate sibling that doesn't exist, e.g. if a file
  6510. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  6511. @param putNumbersInBrackets whether to add brackets around the numbers that
  6512. get appended to the new filename.
  6513. */
  6514. const File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  6515. /** Compares the pathnames for two files. */
  6516. bool operator== (const File& otherFile) const;
  6517. /** Compares the pathnames for two files. */
  6518. bool operator!= (const File& otherFile) const;
  6519. /** Compares the pathnames for two files. */
  6520. bool operator< (const File& otherFile) const;
  6521. /** Compares the pathnames for two files. */
  6522. bool operator> (const File& otherFile) const;
  6523. /** Checks whether a file can be created or written to.
  6524. @returns true if it's possible to create and write to this file. If the file
  6525. doesn't already exist, this will check its parent directory to
  6526. see if writing is allowed.
  6527. @see setReadOnly
  6528. */
  6529. bool hasWriteAccess() const;
  6530. /** Changes the write-permission of a file or directory.
  6531. @param shouldBeReadOnly whether to add or remove write-permission
  6532. @param applyRecursively if the file is a directory and this is true, it will
  6533. recurse through all the subfolders changing the permissions
  6534. of all files
  6535. @returns true if it manages to change the file's permissions.
  6536. @see hasWriteAccess
  6537. */
  6538. bool setReadOnly (bool shouldBeReadOnly,
  6539. bool applyRecursively = false) const;
  6540. /** Returns true if this file is a hidden or system file.
  6541. The criteria for deciding whether a file is hidden are platform-dependent.
  6542. */
  6543. bool isHidden() const;
  6544. /** If this file is a link, this returns the file that it points to.
  6545. If this file isn't actually link, it'll just return itself.
  6546. */
  6547. const File getLinkedTarget() const;
  6548. /** Returns the last modification time of this file.
  6549. @returns the time, or an invalid time if the file doesn't exist.
  6550. @see setLastModificationTime, getLastAccessTime, getCreationTime
  6551. */
  6552. const Time getLastModificationTime() const;
  6553. /** Returns the last time this file was accessed.
  6554. @returns the time, or an invalid time if the file doesn't exist.
  6555. @see setLastAccessTime, getLastModificationTime, getCreationTime
  6556. */
  6557. const Time getLastAccessTime() const;
  6558. /** Returns the time that this file was created.
  6559. @returns the time, or an invalid time if the file doesn't exist.
  6560. @see getLastModificationTime, getLastAccessTime
  6561. */
  6562. const Time getCreationTime() const;
  6563. /** Changes the modification time for this file.
  6564. @param newTime the time to apply to the file
  6565. @returns true if it manages to change the file's time.
  6566. @see getLastModificationTime, setLastAccessTime, setCreationTime
  6567. */
  6568. bool setLastModificationTime (const Time& newTime) const;
  6569. /** Changes the last-access time for this file.
  6570. @param newTime the time to apply to the file
  6571. @returns true if it manages to change the file's time.
  6572. @see getLastAccessTime, setLastModificationTime, setCreationTime
  6573. */
  6574. bool setLastAccessTime (const Time& newTime) const;
  6575. /** Changes the creation date for this file.
  6576. @param newTime the time to apply to the file
  6577. @returns true if it manages to change the file's time.
  6578. @see getCreationTime, setLastModificationTime, setLastAccessTime
  6579. */
  6580. bool setCreationTime (const Time& newTime) const;
  6581. /** If possible, this will try to create a version string for the given file.
  6582. The OS may be able to look at the file and give a version for it - e.g. with
  6583. executables, bundles, dlls, etc. If no version is available, this will
  6584. return an empty string.
  6585. */
  6586. const String getVersion() const;
  6587. /** Creates an empty file if it doesn't already exist.
  6588. If the file that this object refers to doesn't exist, this will create a file
  6589. of zero size.
  6590. If it already exists or is a directory, this method will do nothing.
  6591. @returns true if the file has been created (or if it already existed).
  6592. @see createDirectory
  6593. */
  6594. bool create() const;
  6595. /** Creates a new directory for this filename.
  6596. This will try to create the file as a directory, and fill also create
  6597. any parent directories it needs in order to complete the operation.
  6598. @returns true if the directory has been created successfully, (or if it
  6599. already existed beforehand).
  6600. @see create
  6601. */
  6602. bool createDirectory() const;
  6603. /** Deletes a file.
  6604. If this file is actually a directory, it may not be deleted correctly if it
  6605. contains files. See deleteRecursively() as a better way of deleting directories.
  6606. @returns true if the file has been successfully deleted (or if it didn't exist to
  6607. begin with).
  6608. @see deleteRecursively
  6609. */
  6610. bool deleteFile() const;
  6611. /** Deletes a file or directory and all its subdirectories.
  6612. If this file is a directory, this will try to delete it and all its subfolders. If
  6613. it's just a file, it will just try to delete the file.
  6614. @returns true if the file and all its subfolders have been successfully deleted
  6615. (or if it didn't exist to begin with).
  6616. @see deleteFile
  6617. */
  6618. bool deleteRecursively() const;
  6619. /** Moves this file or folder to the trash.
  6620. @returns true if the operation succeeded. It could fail if the trash is full, or
  6621. if the file is write-protected, so you should check the return value
  6622. and act appropriately.
  6623. */
  6624. bool moveToTrash() const;
  6625. /** Moves or renames a file.
  6626. Tries to move a file to a different location.
  6627. If the target file already exists, this will attempt to delete it first, and
  6628. will fail if this can't be done.
  6629. Note that the destination file isn't the directory to put it in, it's the actual
  6630. filename that you want the new file to have.
  6631. @returns true if the operation succeeds
  6632. */
  6633. bool moveFileTo (const File& targetLocation) const;
  6634. /** Copies a file.
  6635. Tries to copy a file to a different location.
  6636. If the target file already exists, this will attempt to delete it first, and
  6637. will fail if this can't be done.
  6638. @returns true if the operation succeeds
  6639. */
  6640. bool copyFileTo (const File& targetLocation) const;
  6641. /** Copies a directory.
  6642. Tries to copy an entire directory, recursively.
  6643. If this file isn't a directory or if any target files can't be created, this
  6644. will return false.
  6645. @param newDirectory the directory that this one should be copied to. Note that this
  6646. is the name of the actual directory to create, not the directory
  6647. into which the new one should be placed, so there must be enough
  6648. write privileges to create it if it doesn't exist. Any files inside
  6649. it will be overwritten by similarly named ones that are copied.
  6650. */
  6651. bool copyDirectoryTo (const File& newDirectory) const;
  6652. /** Used in file searching, to specify whether to return files, directories, or both.
  6653. */
  6654. enum TypesOfFileToFind
  6655. {
  6656. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  6657. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  6658. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  6659. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  6660. };
  6661. /** Searches inside a directory for files matching a wildcard pattern.
  6662. Assuming that this file is a directory, this method will search it
  6663. for either files or subdirectories whose names match a filename pattern.
  6664. @param results an array to which File objects will be added for the
  6665. files that the search comes up with
  6666. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  6667. return files, directories, or both. If the ignoreHiddenFiles flag
  6668. is also added to this value, hidden files won't be returned
  6669. @param searchRecursively if true, all subdirectories will be recursed into to do
  6670. an exhaustive search
  6671. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  6672. @returns the number of results that have been found
  6673. @see getNumberOfChildFiles, DirectoryIterator
  6674. */
  6675. int findChildFiles (Array<File>& results,
  6676. int whatToLookFor,
  6677. bool searchRecursively,
  6678. const String& wildCardPattern = "*") const;
  6679. /** Searches inside a directory and counts how many files match a wildcard pattern.
  6680. Assuming that this file is a directory, this method will search it
  6681. for either files or subdirectories whose names match a filename pattern,
  6682. and will return the number of matches found.
  6683. This isn't a recursive call, and will only search this directory, not
  6684. its children.
  6685. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  6686. count files, directories, or both. If the ignoreHiddenFiles flag
  6687. is also added to this value, hidden files won't be counted
  6688. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  6689. @returns the number of matches found
  6690. @see findChildFiles, DirectoryIterator
  6691. */
  6692. int getNumberOfChildFiles (int whatToLookFor,
  6693. const String& wildCardPattern = "*") const;
  6694. /** Returns true if this file is a directory that contains one or more subdirectories.
  6695. @see isDirectory, findChildFiles
  6696. */
  6697. bool containsSubDirectories() const;
  6698. /** Creates a stream to read from this file.
  6699. @returns a stream that will read from this file (initially positioned at the
  6700. start of the file), or 0 if the file can't be opened for some reason
  6701. @see createOutputStream, loadFileAsData
  6702. */
  6703. FileInputStream* createInputStream() const;
  6704. /** Creates a stream to write to this file.
  6705. If the file exists, the stream that is returned will be positioned ready for
  6706. writing at the end of the file, so you might want to use deleteFile() first
  6707. to write to an empty file.
  6708. @returns a stream that will write to this file (initially positioned at the
  6709. end of the file), or 0 if the file can't be opened for some reason
  6710. @see createInputStream, appendData, appendText
  6711. */
  6712. FileOutputStream* createOutputStream (int bufferSize = 0x8000) const;
  6713. /** Loads a file's contents into memory as a block of binary data.
  6714. Of course, trying to load a very large file into memory will blow up, so
  6715. it's better to check first.
  6716. @param result the data block to which the file's contents should be appended - note
  6717. that if the memory block might already contain some data, you
  6718. might want to clear it first
  6719. @returns true if the file could all be read into memory
  6720. */
  6721. bool loadFileAsData (MemoryBlock& result) const;
  6722. /** Reads a file into memory as a string.
  6723. Attempts to load the entire file as a zero-terminated string.
  6724. This makes use of InputStream::readEntireStreamAsString, which should
  6725. automatically cope with unicode/acsii file formats.
  6726. */
  6727. const String loadFileAsString() const;
  6728. /** Appends a block of binary data to the end of the file.
  6729. This will try to write the given buffer to the end of the file.
  6730. @returns false if it can't write to the file for some reason
  6731. */
  6732. bool appendData (const void* dataToAppend,
  6733. int numberOfBytes) const;
  6734. /** Replaces this file's contents with a given block of data.
  6735. This will delete the file and replace it with the given data.
  6736. A nice feature of this method is that it's safe - instead of deleting
  6737. the file first and then re-writing it, it creates a new temporary file,
  6738. writes the data to that, and then moves the new file to replace the existing
  6739. file. This means that if the power gets pulled out or something crashes,
  6740. you're a lot less likely to end up with an empty file..
  6741. Returns true if the operation succeeds, or false if it fails.
  6742. @see appendText
  6743. */
  6744. bool replaceWithData (const void* dataToWrite,
  6745. int numberOfBytes) const;
  6746. /** Appends a string to the end of the file.
  6747. This will try to append a text string to the file, as either 16-bit unicode
  6748. or 8-bit characters in the default system encoding.
  6749. It can also write the 'ff fe' unicode header bytes before the text to indicate
  6750. the endianness of the file.
  6751. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  6752. @see replaceWithText
  6753. */
  6754. bool appendText (const String& textToAppend,
  6755. bool asUnicode = false,
  6756. bool writeUnicodeHeaderBytes = false) const;
  6757. /** Replaces this file's contents with a given text string.
  6758. This will delete the file and replace it with the given text.
  6759. A nice feature of this method is that it's safe - instead of deleting
  6760. the file first and then re-writing it, it creates a new temporary file,
  6761. writes the text to that, and then moves the new file to replace the existing
  6762. file. This means that if the power gets pulled out or something crashes,
  6763. you're a lot less likely to end up with an empty file..
  6764. For an explanation of the parameters here, see the appendText() method.
  6765. Returns true if the operation succeeds, or false if it fails.
  6766. @see appendText
  6767. */
  6768. bool replaceWithText (const String& textToWrite,
  6769. bool asUnicode = false,
  6770. bool writeUnicodeHeaderBytes = false) const;
  6771. /** Attempts to scan the contents of this file and compare it to another file, returning
  6772. true if this is possible and they match byte-for-byte.
  6773. */
  6774. bool hasIdenticalContentTo (const File& other) const;
  6775. /** Creates a set of files to represent each file root.
  6776. e.g. on Windows this will create files for "c:\", "d:\" etc according
  6777. to which ones are available. On the Mac/Linux, this will probably
  6778. just add a single entry for "/".
  6779. */
  6780. static void findFileSystemRoots (Array<File>& results);
  6781. /** Finds the name of the drive on which this file lives.
  6782. @returns the volume label of the drive, or an empty string if this isn't possible
  6783. */
  6784. const String getVolumeLabel() const;
  6785. /** Returns the serial number of the volume on which this file lives.
  6786. @returns the serial number, or zero if there's a problem doing this
  6787. */
  6788. int getVolumeSerialNumber() const;
  6789. /** Returns the number of bytes free on the drive that this file lives on.
  6790. @returns the number of bytes free, or 0 if there's a problem finding this out
  6791. @see getVolumeTotalSize
  6792. */
  6793. int64 getBytesFreeOnVolume() const;
  6794. /** Returns the total size of the drive that contains this file.
  6795. @returns the total number of bytes that the volume can hold
  6796. @see getBytesFreeOnVolume
  6797. */
  6798. int64 getVolumeTotalSize() const;
  6799. /** Returns true if this file is on a CD or DVD drive. */
  6800. bool isOnCDRomDrive() const;
  6801. /** Returns true if this file is on a hard disk.
  6802. This will fail if it's a network drive, but will still be true for
  6803. removable hard-disks.
  6804. */
  6805. bool isOnHardDisk() const;
  6806. /** Returns true if this file is on a removable disk drive.
  6807. This might be a usb-drive, a CD-rom, or maybe a network drive.
  6808. */
  6809. bool isOnRemovableDrive() const;
  6810. /** Launches the file as a process.
  6811. - if the file is executable, this will run it.
  6812. - if it's a document of some kind, it will launch the document with its
  6813. default viewer application.
  6814. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  6815. @see revealToUser
  6816. */
  6817. bool startAsProcess (const String& parameters = String::empty) const;
  6818. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  6819. @see startAsProcess
  6820. */
  6821. void revealToUser() const;
  6822. /** A set of types of location that can be passed to the getSpecialLocation() method.
  6823. */
  6824. enum SpecialLocationType
  6825. {
  6826. /** The user's home folder. This is the same as using File ("~"). */
  6827. userHomeDirectory,
  6828. /** The user's default documents folder. On Windows, this might be the user's
  6829. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  6830. doesn't tend to have one of these, so it might just return their home folder.
  6831. */
  6832. userDocumentsDirectory,
  6833. /** The folder that contains the user's desktop objects. */
  6834. userDesktopDirectory,
  6835. /** The folder in which applications store their persistent user-specific settings.
  6836. On Windows, this might be "\Documents and Settings\username\Application Data".
  6837. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  6838. always create your own sub-folder to put them in, to avoid making a mess.
  6839. */
  6840. userApplicationDataDirectory,
  6841. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  6842. of the computer, rather than just the current user.
  6843. On the Mac it'll be "/Library", on Windows, it could be something like
  6844. "\Documents and Settings\All Users\Application Data".
  6845. Depending on the setup, this folder may be read-only.
  6846. */
  6847. commonApplicationDataDirectory,
  6848. /** The folder that should be used for temporary files.
  6849. Always delete them when you're finished, to keep the user's computer tidy!
  6850. */
  6851. tempDirectory,
  6852. /** Returns this application's executable file.
  6853. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  6854. host app.
  6855. On the mac this will return the unix binary, not the package folder - see
  6856. currentApplicationFile for that.
  6857. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  6858. file link, invokedExecutableFile will return the name of the link.
  6859. */
  6860. currentExecutableFile,
  6861. /** Returns this application's location.
  6862. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  6863. host app.
  6864. On the mac this will return the package folder (if it's in one), not the unix binary
  6865. that's inside it - compare with currentExecutableFile.
  6866. */
  6867. currentApplicationFile,
  6868. /** Returns the file that was invoked to launch this executable.
  6869. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  6870. will return the name of the link that was used, whereas currentExecutableFile will return
  6871. the actual location of the target executable.
  6872. */
  6873. invokedExecutableFile,
  6874. /** The directory in which applications normally get installed.
  6875. So on windows, this would be something like "c:\program files", on the
  6876. Mac "/Applications", or "/usr" on linux.
  6877. */
  6878. globalApplicationsDirectory,
  6879. /** The most likely place where a user might store their music files.
  6880. */
  6881. userMusicDirectory,
  6882. /** The most likely place where a user might store their movie files.
  6883. */
  6884. userMoviesDirectory,
  6885. };
  6886. /** Finds the location of a special type of file or directory, such as a home folder or
  6887. documents folder.
  6888. @see SpecialLocationType
  6889. */
  6890. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  6891. /** Returns a temporary file in the system's temp directory.
  6892. This will try to return the name of a non-existent temp file.
  6893. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  6894. */
  6895. static const File createTempFile (const String& fileNameEnding);
  6896. /** Returns the current working directory.
  6897. @see setAsCurrentWorkingDirectory
  6898. */
  6899. static const File getCurrentWorkingDirectory();
  6900. /** Sets the current working directory to be this file.
  6901. For this to work the file must point to a valid directory.
  6902. @returns true if the current directory has been changed.
  6903. @see getCurrentWorkingDirectory
  6904. */
  6905. bool setAsCurrentWorkingDirectory() const;
  6906. /** The system-specific file separator character.
  6907. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  6908. */
  6909. static const juce_wchar separator;
  6910. /** The system-specific file separator character, as a string.
  6911. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  6912. */
  6913. static const String separatorString;
  6914. /** Removes illegal characters from a filename.
  6915. This will return a copy of the given string after removing characters
  6916. that are not allowed in a legal filename, and possibly shortening the
  6917. string if it's too long.
  6918. Because this will remove slashes, don't use it on an absolute pathname.
  6919. @see createLegalPathName
  6920. */
  6921. static const String createLegalFileName (const String& fileNameToFix);
  6922. /** Removes illegal characters from a pathname.
  6923. Similar to createLegalFileName(), but this won't remove slashes, so can
  6924. be used on a complete pathname.
  6925. @see createLegalFileName
  6926. */
  6927. static const String createLegalPathName (const String& pathNameToFix);
  6928. /** Indicates whether filenames are case-sensitive on the current operating system.
  6929. */
  6930. static bool areFileNamesCaseSensitive();
  6931. /** Returns true if the string seems to be a fully-specified absolute path.
  6932. */
  6933. static bool isAbsolutePath (const String& path);
  6934. /** Creates a file that simply contains this string, without doing the sanity-checking
  6935. that the normal constructors do.
  6936. Best to avoid this unless you really know what you're doing.
  6937. */
  6938. static const File createFileWithoutCheckingPath (const String& path);
  6939. /** Adds a separator character to the end of a path if it doesn't already have one. */
  6940. static const String addTrailingSeparator (const String& path);
  6941. juce_UseDebuggingNewOperator
  6942. private:
  6943. String fullPath;
  6944. // internal way of contructing a file without checking the path
  6945. friend class DirectoryIterator;
  6946. File (const String&, int);
  6947. const String getPathUpToLastSlash() const;
  6948. void createDirectoryInternal (const String& fileName) const;
  6949. bool copyInternal (const File& dest) const;
  6950. bool moveInternal (const File& dest) const;
  6951. bool setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const;
  6952. void getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const;
  6953. bool setFileReadOnlyInternal (bool shouldBeReadOnly) const;
  6954. static const String parseAbsolutePath (const String& path);
  6955. static bool fileTypeMatches (int whatToLookFor, bool isDir, bool isHidden);
  6956. };
  6957. #endif // __JUCE_FILE_JUCEHEADER__
  6958. /*** End of inlined file: juce_File.h ***/
  6959. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  6960. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6961. will be the name of a pointer to each child element.
  6962. E.g. @code
  6963. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6964. forEachXmlChildElement (*myParentXml, child)
  6965. {
  6966. if (child->hasTagName ("FOO"))
  6967. doSomethingWithXmlElement (child);
  6968. }
  6969. @endcode
  6970. @see forEachXmlChildElementWithTagName
  6971. */
  6972. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  6973. \
  6974. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  6975. childElementVariableName != 0; \
  6976. childElementVariableName = childElementVariableName->getNextElement())
  6977. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  6978. which have a specified tag.
  6979. This does the same job as the forEachXmlChildElement macro, but only for those
  6980. elements that have a particular tag name.
  6981. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6982. will be the name of a pointer to each child element. The requiredTagName is the
  6983. tag name to match.
  6984. E.g. @code
  6985. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6986. forEachXmlChildElementWithTagName (*myParentXml, child, "MYTAG")
  6987. {
  6988. // the child object is now guaranteed to be a <MYTAG> element..
  6989. doSomethingWithMYTAGElement (child);
  6990. }
  6991. @endcode
  6992. @see forEachXmlChildElement
  6993. */
  6994. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  6995. \
  6996. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  6997. childElementVariableName != 0; \
  6998. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  6999. /** Used to build a tree of elements representing an XML document.
  7000. An XML document can be parsed into a tree of XmlElements, each of which
  7001. represents an XML tag structure, and which may itself contain other
  7002. nested elements.
  7003. An XmlElement can also be converted back into a text document, and has
  7004. lots of useful methods for manipulating its attributes and sub-elements,
  7005. so XmlElements can actually be used as a handy general-purpose data
  7006. structure.
  7007. Here's an example of parsing some elements: @code
  7008. // check we're looking at the right kind of document..
  7009. if (myElement->hasTagName ("ANIMALS"))
  7010. {
  7011. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  7012. forEachXmlChildElement (*myElement, e)
  7013. {
  7014. if (e->hasTagName ("GIRAFFE"))
  7015. {
  7016. // found a giraffe, so use some of its attributes..
  7017. String giraffeName = e->getStringAttribute ("name");
  7018. int giraffeAge = e->getIntAttribute ("age");
  7019. bool isFriendly = e->getBoolAttribute ("friendly");
  7020. }
  7021. }
  7022. }
  7023. @endcode
  7024. And here's an example of how to create an XML document from scratch: @code
  7025. // create an outer node called "ANIMALS"
  7026. XmlElement animalsList ("ANIMALS");
  7027. for (int i = 0; i < numAnimals; ++i)
  7028. {
  7029. // create an inner element..
  7030. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  7031. giraffe->setAttribute ("name", "nigel");
  7032. giraffe->setAttribute ("age", 10);
  7033. giraffe->setAttribute ("friendly", true);
  7034. // ..and add our new element to the parent node
  7035. animalsList.addChildElement (giraffe);
  7036. }
  7037. // now we can turn the whole thing into a text document..
  7038. String myXmlDoc = animalsList.createDocument (String::empty);
  7039. @endcode
  7040. @see XmlDocument
  7041. */
  7042. class JUCE_API XmlElement
  7043. {
  7044. public:
  7045. /** Creates an XmlElement with this tag name. */
  7046. explicit XmlElement (const String& tagName) throw();
  7047. /** Creates a (deep) copy of another element. */
  7048. XmlElement (const XmlElement& other);
  7049. /** Creates a (deep) copy of another element. */
  7050. XmlElement& operator= (const XmlElement& other);
  7051. /** Deleting an XmlElement will also delete all its child elements. */
  7052. ~XmlElement() throw();
  7053. /** Compares two XmlElements to see if they contain the same text and attiributes.
  7054. The elements are only considered equivalent if they contain the same attiributes
  7055. with the same values, and have the same sub-nodes.
  7056. @param other the other element to compare to
  7057. @param ignoreOrderOfAttributes if true, this means that two elements with the
  7058. same attributes in a different order will be
  7059. considered the same; if false, the attributes must
  7060. be in the same order as well
  7061. */
  7062. bool isEquivalentTo (const XmlElement* other,
  7063. bool ignoreOrderOfAttributes) const throw();
  7064. /** Returns an XML text document that represents this element.
  7065. The string returned can be parsed to recreate the same XmlElement that
  7066. was used to create it.
  7067. @param dtdToUse the DTD to add to the document
  7068. @param allOnOneLine if true, this means that the document will not contain any
  7069. linefeeds, so it'll be smaller but not very easy to read.
  7070. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  7071. document
  7072. @param encodingType the character encoding format string to put into the xml
  7073. header
  7074. @param lineWrapLength the line length that will be used before items get placed on
  7075. a new line. This isn't an absolute maximum length, it just
  7076. determines how lists of attributes get broken up
  7077. @see writeToStream, writeToFile
  7078. */
  7079. const String createDocument (const String& dtdToUse,
  7080. bool allOnOneLine = false,
  7081. bool includeXmlHeader = true,
  7082. const String& encodingType = "UTF-8",
  7083. int lineWrapLength = 60) const;
  7084. /** Writes the document to a stream as UTF-8.
  7085. @param output the stream to write to
  7086. @param dtdToUse the DTD to add to the document
  7087. @param allOnOneLine if true, this means that the document will not contain any
  7088. linefeeds, so it'll be smaller but not very easy to read.
  7089. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  7090. document
  7091. @param encodingType the character encoding format string to put into the xml
  7092. header
  7093. @param lineWrapLength the line length that will be used before items get placed on
  7094. a new line. This isn't an absolute maximum length, it just
  7095. determines how lists of attributes get broken up
  7096. @see writeToFile, createDocument
  7097. */
  7098. void writeToStream (OutputStream& output,
  7099. const String& dtdToUse,
  7100. bool allOnOneLine = false,
  7101. bool includeXmlHeader = true,
  7102. const String& encodingType = "UTF-8",
  7103. int lineWrapLength = 60) const;
  7104. /** Writes the element to a file as an XML document.
  7105. To improve safety in case something goes wrong while writing the file, this
  7106. will actually write the document to a new temporary file in the same
  7107. directory as the destination file, and if this succeeds, it will rename this
  7108. new file as the destination file (overwriting any existing file that was there).
  7109. @param destinationFile the file to write to. If this already exists, it will be
  7110. overwritten.
  7111. @param dtdToUse the DTD to add to the document
  7112. @param encodingType the character encoding format string to put into the xml
  7113. header
  7114. @param lineWrapLength the line length that will be used before items get placed on
  7115. a new line. This isn't an absolute maximum length, it just
  7116. determines how lists of attributes get broken up
  7117. @returns true if the file is written successfully; false if something goes wrong
  7118. in the process
  7119. @see createDocument
  7120. */
  7121. bool writeToFile (const File& destinationFile,
  7122. const String& dtdToUse,
  7123. const String& encodingType = "UTF-8",
  7124. int lineWrapLength = 60) const;
  7125. /** Returns this element's tag type name.
  7126. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  7127. "MOOSE".
  7128. @see hasTagName
  7129. */
  7130. inline const String& getTagName() const throw() { return tagName; }
  7131. /** Tests whether this element has a particular tag name.
  7132. @param possibleTagName the tag name you're comparing it with
  7133. @see getTagName
  7134. */
  7135. bool hasTagName (const String& possibleTagName) const throw();
  7136. /** Returns the number of XML attributes this element contains.
  7137. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  7138. return 2.
  7139. */
  7140. int getNumAttributes() const throw();
  7141. /** Returns the name of one of the elements attributes.
  7142. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7143. getAttributeName(1) would return "antlers".
  7144. @see getAttributeValue, getStringAttribute
  7145. */
  7146. const String& getAttributeName (int attributeIndex) const throw();
  7147. /** Returns the value of one of the elements attributes.
  7148. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7149. getAttributeName(1) would return "2".
  7150. @see getAttributeName, getStringAttribute
  7151. */
  7152. const String& getAttributeValue (int attributeIndex) const throw();
  7153. // Attribute-handling methods..
  7154. /** Checks whether the element contains an attribute with a certain name. */
  7155. bool hasAttribute (const String& attributeName) const throw();
  7156. /** Returns the value of a named attribute.
  7157. @param attributeName the name of the attribute to look up
  7158. */
  7159. const String& getStringAttribute (const String& attributeName) const throw();
  7160. /** Returns the value of a named attribute.
  7161. @param attributeName the name of the attribute to look up
  7162. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7163. with this name
  7164. */
  7165. const String getStringAttribute (const String& attributeName,
  7166. const String& defaultReturnValue) const;
  7167. /** Compares the value of a named attribute with a value passed-in.
  7168. @param attributeName the name of the attribute to look up
  7169. @param stringToCompareAgainst the value to compare it with
  7170. @param ignoreCase whether the comparison should be case-insensitive
  7171. @returns true if the value of the attribute is the same as the string passed-in;
  7172. false if it's different (or if no such attribute exists)
  7173. */
  7174. bool compareAttribute (const String& attributeName,
  7175. const String& stringToCompareAgainst,
  7176. bool ignoreCase = false) const throw();
  7177. /** Returns the value of a named attribute as an integer.
  7178. This will try to find the attribute and convert it to an integer (using
  7179. the String::getIntValue() method).
  7180. @param attributeName the name of the attribute to look up
  7181. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7182. with this name
  7183. @see setAttribute
  7184. */
  7185. int getIntAttribute (const String& attributeName,
  7186. int defaultReturnValue = 0) const;
  7187. /** Returns the value of a named attribute as floating-point.
  7188. This will try to find the attribute and convert it to an integer (using
  7189. the String::getDoubleValue() method).
  7190. @param attributeName the name of the attribute to look up
  7191. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7192. with this name
  7193. @see setAttribute
  7194. */
  7195. double getDoubleAttribute (const String& attributeName,
  7196. double defaultReturnValue = 0.0) const;
  7197. /** Returns the value of a named attribute as a boolean.
  7198. This will try to find the attribute and interpret it as a boolean. To do this,
  7199. it'll return true if the value is "1", "true", "y", etc, or false for other
  7200. values.
  7201. @param attributeName the name of the attribute to look up
  7202. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7203. with this name
  7204. */
  7205. bool getBoolAttribute (const String& attributeName,
  7206. bool defaultReturnValue = false) const;
  7207. /** Adds a named attribute to the element.
  7208. If the element already contains an attribute with this name, it's value will
  7209. be updated to the new value. If there's no such attribute yet, a new one will
  7210. be added.
  7211. Note that there are other setAttribute() methods that take integers,
  7212. doubles, etc. to make it easy to store numbers.
  7213. @param attributeName the name of the attribute to set
  7214. @param newValue the value to set it to
  7215. @see removeAttribute
  7216. */
  7217. void setAttribute (const String& attributeName,
  7218. const String& newValue);
  7219. /** Adds a named attribute to the element, setting it to an integer value.
  7220. If the element already contains an attribute with this name, it's value will
  7221. be updated to the new value. If there's no such attribute yet, a new one will
  7222. be added.
  7223. Note that there are other setAttribute() methods that take integers,
  7224. doubles, etc. to make it easy to store numbers.
  7225. @param attributeName the name of the attribute to set
  7226. @param newValue the value to set it to
  7227. */
  7228. void setAttribute (const String& attributeName,
  7229. int newValue);
  7230. /** Adds a named attribute to the element, setting it to a floating-point value.
  7231. If the element already contains an attribute with this name, it's value will
  7232. be updated to the new value. If there's no such attribute yet, a new one will
  7233. be added.
  7234. Note that there are other setAttribute() methods that take integers,
  7235. doubles, etc. to make it easy to store numbers.
  7236. @param attributeName the name of the attribute to set
  7237. @param newValue the value to set it to
  7238. */
  7239. void setAttribute (const String& attributeName,
  7240. double newValue);
  7241. /** Removes a named attribute from the element.
  7242. @param attributeName the name of the attribute to remove
  7243. @see removeAllAttributes
  7244. */
  7245. void removeAttribute (const String& attributeName) throw();
  7246. /** Removes all attributes from this element.
  7247. */
  7248. void removeAllAttributes() throw();
  7249. // Child element methods..
  7250. /** Returns the first of this element's sub-elements.
  7251. see getNextElement() for an example of how to iterate the sub-elements.
  7252. @see forEachXmlChildElement
  7253. */
  7254. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  7255. /** Returns the next of this element's siblings.
  7256. This can be used for iterating an element's sub-elements, e.g.
  7257. @code
  7258. XmlElement* child = myXmlDocument->getFirstChildElement();
  7259. while (child != 0)
  7260. {
  7261. ...do stuff with this child..
  7262. child = child->getNextElement();
  7263. }
  7264. @endcode
  7265. Note that when iterating the child elements, some of them might be
  7266. text elements as well as XML tags - use isTextElement() to work this
  7267. out.
  7268. Also, it's much easier and neater to use this method indirectly via the
  7269. forEachXmlChildElement macro.
  7270. @returns the sibling element that follows this one, or zero if this is the last
  7271. element in its parent
  7272. @see getNextElement, isTextElement, forEachXmlChildElement
  7273. */
  7274. inline XmlElement* getNextElement() const throw() { return nextElement; }
  7275. /** Returns the next of this element's siblings which has the specified tag
  7276. name.
  7277. This is like getNextElement(), but will scan through the list until it
  7278. finds an element with the given tag name.
  7279. @see getNextElement, forEachXmlChildElementWithTagName
  7280. */
  7281. XmlElement* getNextElementWithTagName (const String& requiredTagName) const;
  7282. /** Returns the number of sub-elements in this element.
  7283. @see getChildElement
  7284. */
  7285. int getNumChildElements() const throw();
  7286. /** Returns the sub-element at a certain index.
  7287. It's not very efficient to iterate the sub-elements by index - see
  7288. getNextElement() for an example of how best to iterate.
  7289. @returns the n'th child of this element, or 0 if the index is out-of-range
  7290. @see getNextElement, isTextElement, getChildByName
  7291. */
  7292. XmlElement* getChildElement (int index) const throw();
  7293. /** Returns the first sub-element with a given tag-name.
  7294. @param tagNameToLookFor the tag name of the element you want to find
  7295. @returns the first element with this tag name, or 0 if none is found
  7296. @see getNextElement, isTextElement, getChildElement
  7297. */
  7298. XmlElement* getChildByName (const String& tagNameToLookFor) const throw();
  7299. /** Appends an element to this element's list of children.
  7300. Child elements are deleted automatically when their parent is deleted, so
  7301. make sure the object that you pass in will not be deleted by anything else,
  7302. and make sure it's not already the child of another element.
  7303. @see getFirstChildElement, getNextElement, getNumChildElements,
  7304. getChildElement, removeChildElement
  7305. */
  7306. void addChildElement (XmlElement* const newChildElement) throw();
  7307. /** Inserts an element into this element's list of children.
  7308. Child elements are deleted automatically when their parent is deleted, so
  7309. make sure the object that you pass in will not be deleted by anything else,
  7310. and make sure it's not already the child of another element.
  7311. @param newChildNode the element to add
  7312. @param indexToInsertAt the index at which to insert the new element - if this is
  7313. below zero, it will be added to the end of the list
  7314. @see addChildElement, insertChildElement
  7315. */
  7316. void insertChildElement (XmlElement* newChildNode,
  7317. int indexToInsertAt) throw();
  7318. /** Creates a new element with the given name and returns it, after adding it
  7319. as a child element.
  7320. This is a handy method that means that instead of writing this:
  7321. @code
  7322. XmlElement* newElement = new XmlElement ("foobar");
  7323. myParentElement->addChildElement (newElement);
  7324. @endcode
  7325. ..you could just write this:
  7326. @code
  7327. XmlElement* newElement = myParentElement->createNewChildElement ("foobar");
  7328. @endcode
  7329. */
  7330. XmlElement* createNewChildElement (const String& tagName);
  7331. /** Replaces one of this element's children with another node.
  7332. If the current element passed-in isn't actually a child of this element,
  7333. this will return false and the new one won't be added. Otherwise, the
  7334. existing element will be deleted, replaced with the new one, and it
  7335. will return true.
  7336. */
  7337. bool replaceChildElement (XmlElement* currentChildElement,
  7338. XmlElement* newChildNode) throw();
  7339. /** Removes a child element.
  7340. @param childToRemove the child to look for and remove
  7341. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  7342. just remove it
  7343. */
  7344. void removeChildElement (XmlElement* childToRemove,
  7345. bool shouldDeleteTheChild) throw();
  7346. /** Deletes all the child elements in the element.
  7347. @see removeChildElement, deleteAllChildElementsWithTagName
  7348. */
  7349. void deleteAllChildElements() throw();
  7350. /** Deletes all the child elements with a given tag name.
  7351. @see removeChildElement
  7352. */
  7353. void deleteAllChildElementsWithTagName (const String& tagName) throw();
  7354. /** Returns true if the given element is a child of this one. */
  7355. bool containsChildElement (const XmlElement* const possibleChild) const throw();
  7356. /** Recursively searches all sub-elements to find one that contains the specified
  7357. child element.
  7358. */
  7359. XmlElement* findParentElementOf (const XmlElement* elementToLookFor) throw();
  7360. /** Sorts the child elements using a comparator.
  7361. This will use a comparator object to sort the elements into order. The object
  7362. passed must have a method of the form:
  7363. @code
  7364. int compareElements (const XmlElement* first, const XmlElement* second);
  7365. @endcode
  7366. ..and this method must return:
  7367. - a value of < 0 if the first comes before the second
  7368. - a value of 0 if the two objects are equivalent
  7369. - a value of > 0 if the second comes before the first
  7370. To improve performance, the compareElements() method can be declared as static or const.
  7371. @param comparator the comparator to use for comparing elements.
  7372. @param retainOrderOfEquivalentItems if this is true, then items
  7373. which the comparator says are equivalent will be
  7374. kept in the order in which they currently appear
  7375. in the array. This is slower to perform, but may
  7376. be important in some cases. If it's false, a faster
  7377. algorithm is used, but equivalent elements may be
  7378. rearranged.
  7379. */
  7380. template <class ElementComparator>
  7381. void sortChildElements (ElementComparator& comparator,
  7382. bool retainOrderOfEquivalentItems = false)
  7383. {
  7384. const int num = getNumChildElements();
  7385. if (num > 1)
  7386. {
  7387. HeapBlock <XmlElement*> elems (num);
  7388. getChildElementsAsArray (elems);
  7389. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  7390. reorderChildElements (elems, num);
  7391. }
  7392. }
  7393. /** Returns true if this element is a section of text.
  7394. Elements can either be an XML tag element or a secton of text, so this
  7395. is used to find out what kind of element this one is.
  7396. @see getAllText, addTextElement, deleteAllTextElements
  7397. */
  7398. bool isTextElement() const throw();
  7399. /** Returns the text for a text element.
  7400. Note that if you have an element like this:
  7401. @code<xyz>hello</xyz>@endcode
  7402. then calling getText on the "xyz" element won't return "hello", because that is
  7403. actually stored in a special text sub-element inside the xyz element. To get the
  7404. "hello" string, you could either call getText on the (unnamed) sub-element, or
  7405. use getAllSubText() to do this automatically.
  7406. @see isTextElement, getAllSubText, getChildElementAllSubText
  7407. */
  7408. const String& getText() const throw();
  7409. /** Sets the text in a text element.
  7410. Note that this is only a valid call if this element is a text element. If it's
  7411. not, then no action will be performed.
  7412. */
  7413. void setText (const String& newText);
  7414. /** Returns all the text from this element's child nodes.
  7415. This iterates all the child elements and when it finds text elements,
  7416. it concatenates their text into a big string which it returns.
  7417. E.g. @code<xyz> hello <x></x> there </xyz>@endcode
  7418. if you called getAllSubText on the "xyz" element, it'd return "hello there".
  7419. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  7420. */
  7421. const String getAllSubText() const;
  7422. /** Returns all the sub-text of a named child element.
  7423. If there is a child element with the given tag name, this will return
  7424. all of its sub-text (by calling getAllSubText() on it). If there is
  7425. no such child element, this will return the default string passed-in.
  7426. @see getAllSubText
  7427. */
  7428. const String getChildElementAllSubText (const String& childTagName,
  7429. const String& defaultReturnValue) const;
  7430. /** Appends a section of text to this element.
  7431. @see isTextElement, getText, getAllSubText
  7432. */
  7433. void addTextElement (const String& text);
  7434. /** Removes all the text elements from this element.
  7435. @see isTextElement, getText, getAllSubText, addTextElement
  7436. */
  7437. void deleteAllTextElements() throw();
  7438. /** Creates a text element that can be added to a parent element.
  7439. */
  7440. static XmlElement* createTextElement (const String& text);
  7441. juce_UseDebuggingNewOperator
  7442. private:
  7443. friend class XmlDocument;
  7444. String tagName;
  7445. XmlElement* firstChildElement;
  7446. XmlElement* nextElement;
  7447. struct XmlAttributeNode
  7448. {
  7449. XmlAttributeNode (const XmlAttributeNode& other) throw();
  7450. XmlAttributeNode (const String& name, const String& value) throw();
  7451. String name, value;
  7452. XmlAttributeNode* next;
  7453. private:
  7454. XmlAttributeNode& operator= (const XmlAttributeNode&);
  7455. };
  7456. XmlAttributeNode* attributes;
  7457. XmlElement (int) throw();
  7458. void copyChildrenAndAttributesFrom (const XmlElement& other);
  7459. void writeElementAsText (OutputStream& out, int indentationLevel, int lineWrapLength) const;
  7460. void getChildElementsAsArray (XmlElement**) const throw();
  7461. void reorderChildElements (XmlElement** const, const int) throw();
  7462. };
  7463. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  7464. /*** End of inlined file: juce_XmlElement.h ***/
  7465. /**
  7466. A set of named property values, which can be strings, integers, floating point, etc.
  7467. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  7468. to load and save types other than strings.
  7469. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  7470. messages and saves/loads the list from a file.
  7471. */
  7472. class JUCE_API PropertySet
  7473. {
  7474. public:
  7475. /** Creates an empty PropertySet.
  7476. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  7477. case-insensitive way
  7478. */
  7479. PropertySet (const bool ignoreCaseOfKeyNames = false) throw();
  7480. /** Creates a copy of another PropertySet.
  7481. */
  7482. PropertySet (const PropertySet& other) throw();
  7483. /** Copies another PropertySet over this one.
  7484. */
  7485. PropertySet& operator= (const PropertySet& other) throw();
  7486. /** Destructor. */
  7487. virtual ~PropertySet();
  7488. /** Returns one of the properties as a string.
  7489. If the value isn't found in this set, then this will look for it in a fallback
  7490. property set (if you've specified one with the setFallbackPropertySet() method),
  7491. and if it can't find one there, it'll return the default value passed-in.
  7492. @param keyName the name of the property to retrieve
  7493. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7494. */
  7495. const String getValue (const String& keyName,
  7496. const String& defaultReturnValue = String::empty) const throw();
  7497. /** Returns one of the properties as an integer.
  7498. If the value isn't found in this set, then this will look for it in a fallback
  7499. property set (if you've specified one with the setFallbackPropertySet() method),
  7500. and if it can't find one there, it'll return the default value passed-in.
  7501. @param keyName the name of the property to retrieve
  7502. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7503. */
  7504. int getIntValue (const String& keyName,
  7505. const int defaultReturnValue = 0) const throw();
  7506. /** Returns one of the properties as an double.
  7507. If the value isn't found in this set, then this will look for it in a fallback
  7508. property set (if you've specified one with the setFallbackPropertySet() method),
  7509. and if it can't find one there, it'll return the default value passed-in.
  7510. @param keyName the name of the property to retrieve
  7511. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7512. */
  7513. double getDoubleValue (const String& keyName,
  7514. const double defaultReturnValue = 0.0) const throw();
  7515. /** Returns one of the properties as an boolean.
  7516. The result will be true if the string found for this key name can be parsed as a non-zero
  7517. integer.
  7518. If the value isn't found in this set, then this will look for it in a fallback
  7519. property set (if you've specified one with the setFallbackPropertySet() method),
  7520. and if it can't find one there, it'll return the default value passed-in.
  7521. @param keyName the name of the property to retrieve
  7522. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7523. */
  7524. bool getBoolValue (const String& keyName,
  7525. const bool defaultReturnValue = false) const throw();
  7526. /** Returns one of the properties as an XML element.
  7527. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  7528. key isn't found, or if the entry contains an string that isn't valid XML.
  7529. If the value isn't found in this set, then this will look for it in a fallback
  7530. property set (if you've specified one with the setFallbackPropertySet() method),
  7531. and if it can't find one there, it'll return the default value passed-in.
  7532. @param keyName the name of the property to retrieve
  7533. */
  7534. XmlElement* getXmlValue (const String& keyName) const;
  7535. /** Sets a named property as a string.
  7536. @param keyName the name of the property to set. (This mustn't be an empty string)
  7537. @param value the new value to set it to
  7538. */
  7539. void setValue (const String& keyName, const String& value) throw();
  7540. /** Sets a named property to an integer.
  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 int value) throw();
  7545. /** Sets a named property to a double.
  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 double value) throw();
  7550. /** Sets a named property to a boolean.
  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 bool value) throw();
  7555. /** Sets a named property to an XML element.
  7556. @param keyName the name of the property to set. (This mustn't be an empty string)
  7557. @param xml the new element to set it to. If this is zero, the value will be set to
  7558. an empty string
  7559. @see getXmlValue
  7560. */
  7561. void setValue (const String& keyName, const XmlElement* const xml);
  7562. /** Deletes a property.
  7563. @param keyName the name of the property to delete. (This mustn't be an empty string)
  7564. */
  7565. void removeValue (const String& keyName) throw();
  7566. /** Returns true if the properies include the given key. */
  7567. bool containsKey (const String& keyName) const throw();
  7568. /** Removes all values. */
  7569. void clear();
  7570. /** Returns the keys/value pair array containing all the properties. */
  7571. StringPairArray& getAllProperties() throw() { return properties; }
  7572. /** Returns the lock used when reading or writing to this set */
  7573. const CriticalSection& getLock() const throw() { return lock; }
  7574. /** Returns an XML element which encapsulates all the items in this property set.
  7575. The string parameter is the tag name that should be used for the node.
  7576. @see restoreFromXml
  7577. */
  7578. XmlElement* createXml (const String& nodeName) const throw();
  7579. /** Reloads a set of properties that were previously stored as XML.
  7580. The node passed in must have been created by the createXml() method.
  7581. @see createXml
  7582. */
  7583. void restoreFromXml (const XmlElement& xml) throw();
  7584. /** Sets up a second PopertySet that will be used to look up any values that aren't
  7585. set in this one.
  7586. If you set this up to be a pointer to a second property set, then whenever one
  7587. of the getValue() methods fails to find an entry in this set, it will look up that
  7588. value in the fallback set, and if it finds it, it will return that.
  7589. Make sure that you don't delete the fallback set while it's still being used by
  7590. another set! To remove the fallback set, just call this method with a null pointer.
  7591. @see getFallbackPropertySet
  7592. */
  7593. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  7594. /** Returns the fallback property set.
  7595. @see setFallbackPropertySet
  7596. */
  7597. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  7598. juce_UseDebuggingNewOperator
  7599. protected:
  7600. /** Subclasses can override this to be told when one of the properies has been changed.
  7601. */
  7602. virtual void propertyChanged();
  7603. private:
  7604. StringPairArray properties;
  7605. PropertySet* fallbackProperties;
  7606. CriticalSection lock;
  7607. bool ignoreCaseOfKeys;
  7608. };
  7609. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  7610. /*** End of inlined file: juce_PropertySet.h ***/
  7611. #endif
  7612. #ifndef __JUCE_RANGE_JUCEHEADER__
  7613. /*** Start of inlined file: juce_Range.h ***/
  7614. #ifndef __JUCE_RANGE_JUCEHEADER__
  7615. #define __JUCE_RANGE_JUCEHEADER__
  7616. /** A general-purpose range object, that simply represents any linear range with
  7617. a start and end point.
  7618. The templated parameter is expected to be a primitive integer or floating point
  7619. type, though class types could also be used if they behave in a number-like way.
  7620. */
  7621. template <typename ValueType>
  7622. class Range
  7623. {
  7624. public:
  7625. /** Constructs an empty range. */
  7626. Range() throw()
  7627. : start (ValueType()), end (ValueType())
  7628. {
  7629. }
  7630. /** Constructs a range with given start and end values. */
  7631. Range (const ValueType start_, const ValueType end_) throw()
  7632. : start (start_), end (jmax (start_, end_))
  7633. {
  7634. }
  7635. /** Constructs a copy of another range. */
  7636. Range (const Range& other) throw()
  7637. : start (other.start), end (other.end)
  7638. {
  7639. }
  7640. /** Copies another range object. */
  7641. Range& operator= (const Range& other) throw()
  7642. {
  7643. start = other.start;
  7644. end = other.end;
  7645. return *this;
  7646. }
  7647. /** Destructor. */
  7648. ~Range() throw()
  7649. {
  7650. }
  7651. /** Returns the range that lies between two positions (in either order). */
  7652. static const Range between (const ValueType position1, const ValueType position2) throw()
  7653. {
  7654. return (position1 < position2) ? Range (position1, position2)
  7655. : Range (position2, position1);
  7656. }
  7657. /** Returns a range with the specified start position and a length of zero. */
  7658. static const Range emptyRange (const ValueType start) throw()
  7659. {
  7660. return Range (start, start);
  7661. }
  7662. /** Returns the start of the range. */
  7663. inline ValueType getStart() const throw() { return start; }
  7664. /** Returns the length of the range. */
  7665. inline ValueType getLength() const throw() { return end - start; }
  7666. /** Returns the end of the range. */
  7667. inline ValueType getEnd() const throw() { return end; }
  7668. /** Returns true if the range has a length of zero. */
  7669. inline bool isEmpty() const throw() { return start == end; }
  7670. /** Changes the start position of the range, leaving the end position unchanged.
  7671. If the new start position is higher than the current end of the range, the end point
  7672. will be pushed along to equal it, leaving an empty range at the new position.
  7673. */
  7674. void setStart (const ValueType newStart) throw()
  7675. {
  7676. start = newStart;
  7677. if (end < newStart)
  7678. end = newStart;
  7679. }
  7680. /** Returns a range with the same end as this one, but a different start.
  7681. If the new start position is higher than the current end of the range, the end point
  7682. will be pushed along to equal it, returning an empty range at the new position.
  7683. */
  7684. const Range withStart (const ValueType newStart) const throw()
  7685. {
  7686. return Range (newStart, jmax (newStart, end));
  7687. }
  7688. /** Returns a range with the same length as this one, but moved to have the given start position. */
  7689. const Range movedToStartAt (const ValueType newStart) const throw()
  7690. {
  7691. return Range (newStart, newStart + getLength());
  7692. }
  7693. /** Changes the end position of the range, leaving the start unchanged.
  7694. If the new end position is below the current start of the range, the start point
  7695. will be pushed back to equal the new end point.
  7696. */
  7697. void setEnd (const ValueType newEnd) throw()
  7698. {
  7699. end = newEnd;
  7700. if (newEnd < start)
  7701. start = newEnd;
  7702. }
  7703. /** Returns a range with the same start position as this one, but a different end.
  7704. If the new end position is below the current start of the range, the start point
  7705. will be pushed back to equal the new end point.
  7706. */
  7707. const Range withEnd (const ValueType newEnd) const throw()
  7708. {
  7709. return Range (jmin (start, newEnd), newEnd);
  7710. }
  7711. /** Returns a range with the same length as this one, but moved to have the given start position. */
  7712. const Range movedToEndAt (const ValueType newEnd) const throw()
  7713. {
  7714. return Range (newEnd - getLength(), newEnd);
  7715. }
  7716. /** Changes the length of the range.
  7717. Lengths less than zero are treated as zero.
  7718. */
  7719. void setLength (const ValueType newLength) throw()
  7720. {
  7721. end = start + jmax (ValueType(), newLength);
  7722. }
  7723. /** Returns a range with the same start as this one, but a different length.
  7724. Lengths less than zero are treated as zero.
  7725. */
  7726. const Range withLength (const ValueType newLength) const throw()
  7727. {
  7728. return Range (start, start + newLength);
  7729. }
  7730. /** Adds an amount to the start and end of the range. */
  7731. inline const Range& operator+= (const ValueType amountToAdd) throw()
  7732. {
  7733. start += amountToAdd;
  7734. end += amountToAdd;
  7735. return *this;
  7736. }
  7737. /** Subtracts an amount from the start and end of the range. */
  7738. inline const Range& operator-= (const ValueType amountToSubtract) throw()
  7739. {
  7740. start -= amountToSubtract;
  7741. end -= amountToSubtract;
  7742. return *this;
  7743. }
  7744. /** Returns a range that is equal to this one with an amount added to its
  7745. start and end.
  7746. */
  7747. const Range operator+ (const ValueType amountToAdd) const throw()
  7748. {
  7749. return Range (start + amountToAdd, end + amountToAdd);
  7750. }
  7751. /** Returns a range that is equal to this one with the specified amount
  7752. subtracted from its start and end. */
  7753. const Range operator- (const ValueType amountToSubtract) const throw()
  7754. {
  7755. return Range (start - amountToSubtract, end - amountToSubtract);
  7756. }
  7757. bool operator== (const Range& other) const throw() { return start == other.start && end == other.end; }
  7758. bool operator!= (const Range& other) const throw() { return start != other.start || end != other.end; }
  7759. /** Returns true if the given position lies inside this range. */
  7760. bool contains (const ValueType position) const throw()
  7761. {
  7762. return start <= position && position < end;
  7763. }
  7764. /** Returns the nearest value to the one supplied, which lies within the range. */
  7765. ValueType clipValue (const ValueType value) const throw()
  7766. {
  7767. return jlimit (start, end, value);
  7768. }
  7769. /** Returns true if the given range lies entirely inside this range. */
  7770. bool contains (const Range& other) const throw()
  7771. {
  7772. return start <= other.start && end >= other.end;
  7773. }
  7774. /** Returns true if the given range intersects this one. */
  7775. bool intersects (const Range& other) const throw()
  7776. {
  7777. return other.start < end && start < other.end;
  7778. }
  7779. /** Returns the range that is the intersection of the two ranges, or an empty range
  7780. with an undefined start position if they don't overlap. */
  7781. const Range getIntersectionWith (const Range& other) const throw()
  7782. {
  7783. return Range (jmax (start, other.start),
  7784. jmin (end, other.end));
  7785. }
  7786. /** Returns the smallest range that contains both this one and the other one. */
  7787. const Range getUnionWith (const Range& other) const throw()
  7788. {
  7789. return Range (jmin (start, other.start),
  7790. jmax (end, other.end));
  7791. }
  7792. /** Returns a given range, after moving it forwards or backwards to fit it
  7793. within this range.
  7794. If the supplied range has a greater length than this one, the return value
  7795. will be this range.
  7796. Otherwise, if the supplied range is smaller than this one, the return value
  7797. will be the new range, shifted forwards or backwards so that it doesn't extend
  7798. beyond this one, but keeping its original length.
  7799. */
  7800. const Range constrainRange (const Range& rangeToConstrain) const throw()
  7801. {
  7802. const ValueType otherLen = rangeToConstrain.getLength();
  7803. return getLength() <= otherLen
  7804. ? *this
  7805. : rangeToConstrain.movedToStartAt (jlimit (start, end - otherLen, rangeToConstrain.getStart()));
  7806. }
  7807. juce_UseDebuggingNewOperator
  7808. private:
  7809. ValueType start, end;
  7810. };
  7811. #endif // __JUCE_RANGE_JUCEHEADER__
  7812. /*** End of inlined file: juce_Range.h ***/
  7813. #endif
  7814. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7815. /*** Start of inlined file: juce_ReferenceCountedArray.h ***/
  7816. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7817. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7818. /**
  7819. Holds a list of objects derived from ReferenceCountedObject.
  7820. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  7821. and takes care of incrementing and decrementing their ref counts when they
  7822. are added and removed from the array.
  7823. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7824. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7825. @see Array, OwnedArray, StringArray
  7826. */
  7827. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7828. class ReferenceCountedArray
  7829. {
  7830. public:
  7831. /** Creates an empty array.
  7832. @see ReferenceCountedObject, Array, OwnedArray
  7833. */
  7834. ReferenceCountedArray() throw()
  7835. : numUsed (0)
  7836. {
  7837. }
  7838. /** Creates a copy of another array */
  7839. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7840. {
  7841. const ScopedLockType lock (other.getLock());
  7842. numUsed = other.numUsed;
  7843. data.setAllocatedSize (numUsed);
  7844. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  7845. for (int i = numUsed; --i >= 0;)
  7846. if (data.elements[i] != 0)
  7847. data.elements[i]->incReferenceCount();
  7848. }
  7849. /** Copies another array into this one.
  7850. Any existing objects in this array will first be released.
  7851. */
  7852. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7853. {
  7854. if (this != &other)
  7855. {
  7856. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse> otherCopy (other);
  7857. swapWithArray (otherCopy);
  7858. }
  7859. return *this;
  7860. }
  7861. /** Destructor.
  7862. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  7863. */
  7864. ~ReferenceCountedArray()
  7865. {
  7866. clear();
  7867. }
  7868. /** Removes all objects from the array.
  7869. Any objects in the array that are not referenced from elsewhere will be deleted.
  7870. */
  7871. void clear()
  7872. {
  7873. const ScopedLockType lock (getLock());
  7874. while (numUsed > 0)
  7875. if (data.elements [--numUsed] != 0)
  7876. data.elements [numUsed]->decReferenceCount();
  7877. jassert (numUsed == 0);
  7878. data.setAllocatedSize (0);
  7879. }
  7880. /** Returns the current number of objects in the array. */
  7881. inline int size() const throw()
  7882. {
  7883. return numUsed;
  7884. }
  7885. /** Returns a pointer to the object at this index in the array.
  7886. If the index is out-of-range, this will return a null pointer, (and
  7887. it could be null anyway, because it's ok for the array to hold null
  7888. pointers as well as objects).
  7889. @see getUnchecked
  7890. */
  7891. inline const ReferenceCountedObjectPtr<ObjectClass> operator[] (const int index) const throw()
  7892. {
  7893. const ScopedLockType lock (getLock());
  7894. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  7895. : static_cast <ObjectClass*> (0);
  7896. }
  7897. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7898. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7899. it can be used when you're sure the index if always going to be legal.
  7900. */
  7901. inline const ReferenceCountedObjectPtr<ObjectClass> getUnchecked (const int index) const throw()
  7902. {
  7903. const ScopedLockType lock (getLock());
  7904. jassert (((unsigned int) index) < (unsigned int) numUsed);
  7905. return data.elements [index];
  7906. }
  7907. /** Returns a pointer to the first object in the array.
  7908. This will return a null pointer if the array's empty.
  7909. @see getLast
  7910. */
  7911. inline const ReferenceCountedObjectPtr<ObjectClass> getFirst() const throw()
  7912. {
  7913. const ScopedLockType lock (getLock());
  7914. return numUsed > 0 ? data.elements [0]
  7915. : static_cast <ObjectClass*> (0);
  7916. }
  7917. /** Returns a pointer to the last object in the array.
  7918. This will return a null pointer if the array's empty.
  7919. @see getFirst
  7920. */
  7921. inline const ReferenceCountedObjectPtr<ObjectClass> getLast() const throw()
  7922. {
  7923. const ScopedLockType lock (getLock());
  7924. return numUsed > 0 ? data.elements [numUsed - 1]
  7925. : static_cast <ObjectClass*> (0);
  7926. }
  7927. /** Finds the index of the first occurrence of an object in the array.
  7928. @param objectToLookFor the object to look for
  7929. @returns the index at which the object was found, or -1 if it's not found
  7930. */
  7931. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7932. {
  7933. const ScopedLockType lock (getLock());
  7934. ObjectClass** e = data.elements.getData();
  7935. ObjectClass** const end = e + numUsed;
  7936. while (e != end)
  7937. {
  7938. if (objectToLookFor == *e)
  7939. return static_cast <int> (e - data.elements.getData());
  7940. ++e;
  7941. }
  7942. return -1;
  7943. }
  7944. /** Returns true if the array contains a specified object.
  7945. @param objectToLookFor the object to look for
  7946. @returns true if the object is in the array
  7947. */
  7948. bool contains (const ObjectClass* const objectToLookFor) const throw()
  7949. {
  7950. const ScopedLockType lock (getLock());
  7951. ObjectClass** e = data.elements.getData();
  7952. ObjectClass** const end = e + numUsed;
  7953. while (e != end)
  7954. {
  7955. if (objectToLookFor == *e)
  7956. return true;
  7957. ++e;
  7958. }
  7959. return false;
  7960. }
  7961. /** Appends a new object to the end of the array.
  7962. This will increase the new object's reference count.
  7963. @param newObject the new object to add to the array
  7964. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  7965. */
  7966. void add (ObjectClass* const newObject) throw()
  7967. {
  7968. const ScopedLockType lock (getLock());
  7969. data.ensureAllocatedSize (numUsed + 1);
  7970. data.elements [numUsed++] = newObject;
  7971. if (newObject != 0)
  7972. newObject->incReferenceCount();
  7973. }
  7974. /** Inserts a new object into the array at the given index.
  7975. If the index is less than 0 or greater than the size of the array, the
  7976. element will be added to the end of the array.
  7977. Otherwise, it will be inserted into the array, moving all the later elements
  7978. along to make room.
  7979. This will increase the new object's reference count.
  7980. @param indexToInsertAt the index at which the new element should be inserted
  7981. @param newObject the new object to add to the array
  7982. @see add, addSorted, addIfNotAlreadyThere, set
  7983. */
  7984. void insert (int indexToInsertAt,
  7985. ObjectClass* const newObject) throw()
  7986. {
  7987. if (indexToInsertAt >= 0)
  7988. {
  7989. const ScopedLockType lock (getLock());
  7990. if (indexToInsertAt > numUsed)
  7991. indexToInsertAt = numUsed;
  7992. data.ensureAllocatedSize (numUsed + 1);
  7993. ObjectClass** const e = data.elements + indexToInsertAt;
  7994. const int numToMove = numUsed - indexToInsertAt;
  7995. if (numToMove > 0)
  7996. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7997. *e = newObject;
  7998. if (newObject != 0)
  7999. newObject->incReferenceCount();
  8000. ++numUsed;
  8001. }
  8002. else
  8003. {
  8004. add (newObject);
  8005. }
  8006. }
  8007. /** Appends a new object at the end of the array as long as the array doesn't
  8008. already contain it.
  8009. If the array already contains a matching object, nothing will be done.
  8010. @param newObject the new object to add to the array
  8011. */
  8012. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  8013. {
  8014. const ScopedLockType lock (getLock());
  8015. if (! contains (newObject))
  8016. add (newObject);
  8017. }
  8018. /** Replaces an object in the array with a different one.
  8019. If the index is less than zero, this method does nothing.
  8020. If the index is beyond the end of the array, the new object is added to the end of the array.
  8021. The object being added has its reference count increased, and if it's replacing
  8022. another object, then that one has its reference count decreased, and may be deleted.
  8023. @param indexToChange the index whose value you want to change
  8024. @param newObject the new value to set for this index.
  8025. @see add, insert, remove
  8026. */
  8027. void set (const int indexToChange,
  8028. ObjectClass* const newObject)
  8029. {
  8030. if (indexToChange >= 0)
  8031. {
  8032. const ScopedLockType lock (getLock());
  8033. if (newObject != 0)
  8034. newObject->incReferenceCount();
  8035. if (indexToChange < numUsed)
  8036. {
  8037. if (data.elements [indexToChange] != 0)
  8038. data.elements [indexToChange]->decReferenceCount();
  8039. data.elements [indexToChange] = newObject;
  8040. }
  8041. else
  8042. {
  8043. data.ensureAllocatedSize (numUsed + 1);
  8044. data.elements [numUsed++] = newObject;
  8045. }
  8046. }
  8047. }
  8048. /** Adds elements from another array to the end of this array.
  8049. @param arrayToAddFrom the array from which to copy the elements
  8050. @param startIndex the first element of the other array to start copying from
  8051. @param numElementsToAdd how many elements to add from the other array. If this
  8052. value is negative or greater than the number of available elements,
  8053. all available elements will be copied.
  8054. @see add
  8055. */
  8056. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  8057. int startIndex = 0,
  8058. int numElementsToAdd = -1) throw()
  8059. {
  8060. arrayToAddFrom.lockArray();
  8061. const ScopedLockType lock (getLock());
  8062. if (startIndex < 0)
  8063. {
  8064. jassertfalse;
  8065. startIndex = 0;
  8066. }
  8067. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  8068. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  8069. if (numElementsToAdd > 0)
  8070. {
  8071. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  8072. while (--numElementsToAdd >= 0)
  8073. add (arrayToAddFrom.getUnchecked (startIndex++));
  8074. }
  8075. arrayToAddFrom.unlockArray();
  8076. }
  8077. /** Inserts a new object into the array assuming that the array is sorted.
  8078. This will use a comparator to find the position at which the new object
  8079. should go. If the array isn't sorted, the behaviour of this
  8080. method will be unpredictable.
  8081. @param comparator the comparator object to use to compare the elements - see the
  8082. sort() method for details about this object's form
  8083. @param newObject the new object to insert to the array
  8084. @see add, sort
  8085. */
  8086. template <class ElementComparator>
  8087. void addSorted (ElementComparator& comparator,
  8088. ObjectClass* newObject) throw()
  8089. {
  8090. const ScopedLockType lock (getLock());
  8091. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  8092. }
  8093. /** Inserts or replaces an object in the array, assuming it is sorted.
  8094. This is similar to addSorted, but if a matching element already exists, then it will be
  8095. replaced by the new one, rather than the new one being added as well.
  8096. */
  8097. template <class ElementComparator>
  8098. void addOrReplaceSorted (ElementComparator& comparator,
  8099. ObjectClass* newObject) throw()
  8100. {
  8101. const ScopedLockType lock (getLock());
  8102. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  8103. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  8104. set (index - 1, newObject); // replace an existing object that matches
  8105. else
  8106. insert (index, newObject); // no match, so insert the new one
  8107. }
  8108. /** Removes an object from the array.
  8109. This will remove the object at a given index and move back all the
  8110. subsequent objects to close the gap.
  8111. If the index passed in is out-of-range, nothing will happen.
  8112. The object that is removed will have its reference count decreased,
  8113. and may be deleted if not referenced from elsewhere.
  8114. @param indexToRemove the index of the element to remove
  8115. @see removeObject, removeRange
  8116. */
  8117. void remove (const int indexToRemove)
  8118. {
  8119. const ScopedLockType lock (getLock());
  8120. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8121. {
  8122. ObjectClass** const e = data.elements + indexToRemove;
  8123. if (*e != 0)
  8124. (*e)->decReferenceCount();
  8125. --numUsed;
  8126. const int numberToShift = numUsed - indexToRemove;
  8127. if (numberToShift > 0)
  8128. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  8129. if ((numUsed << 1) < data.numAllocated)
  8130. minimiseStorageOverheads();
  8131. }
  8132. }
  8133. /** Removes the first occurrence of a specified object from the array.
  8134. If the item isn't found, no action is taken. If it is found, it is
  8135. removed and has its reference count decreased.
  8136. @param objectToRemove the object to try to remove
  8137. @see remove, removeRange
  8138. */
  8139. void removeObject (ObjectClass* const objectToRemove)
  8140. {
  8141. const ScopedLockType lock (getLock());
  8142. remove (indexOf (objectToRemove));
  8143. }
  8144. /** Removes a range of objects from the array.
  8145. This will remove a set of objects, starting from the given index,
  8146. and move any subsequent elements down to close the gap.
  8147. If the range extends beyond the bounds of the array, it will
  8148. be safely clipped to the size of the array.
  8149. The objects that are removed will have their reference counts decreased,
  8150. and may be deleted if not referenced from elsewhere.
  8151. @param startIndex the index of the first object to remove
  8152. @param numberToRemove how many objects should be removed
  8153. @see remove, removeObject
  8154. */
  8155. void removeRange (const int startIndex,
  8156. const int numberToRemove)
  8157. {
  8158. const ScopedLockType lock (getLock());
  8159. const int start = jlimit (0, numUsed, startIndex);
  8160. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  8161. if (end > start)
  8162. {
  8163. int i;
  8164. for (i = start; i < end; ++i)
  8165. {
  8166. if (data.elements[i] != 0)
  8167. {
  8168. data.elements[i]->decReferenceCount();
  8169. data.elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  8170. }
  8171. }
  8172. const int rangeSize = end - start;
  8173. ObjectClass** e = data.elements + start;
  8174. i = numUsed - end;
  8175. numUsed -= rangeSize;
  8176. while (--i >= 0)
  8177. {
  8178. *e = e [rangeSize];
  8179. ++e;
  8180. }
  8181. if ((numUsed << 1) < data.numAllocated)
  8182. minimiseStorageOverheads();
  8183. }
  8184. }
  8185. /** Removes the last n objects from the array.
  8186. The objects that are removed will have their reference counts decreased,
  8187. and may be deleted if not referenced from elsewhere.
  8188. @param howManyToRemove how many objects to remove from the end of the array
  8189. @see remove, removeObject, removeRange
  8190. */
  8191. void removeLast (int howManyToRemove = 1)
  8192. {
  8193. const ScopedLockType lock (getLock());
  8194. if (howManyToRemove > numUsed)
  8195. howManyToRemove = numUsed;
  8196. while (--howManyToRemove >= 0)
  8197. remove (numUsed - 1);
  8198. }
  8199. /** Swaps a pair of objects in the array.
  8200. If either of the indexes passed in is out-of-range, nothing will happen,
  8201. otherwise the two objects at these positions will be exchanged.
  8202. */
  8203. void swap (const int index1,
  8204. const int index2) throw()
  8205. {
  8206. const ScopedLockType lock (getLock());
  8207. if (((unsigned int) index1) < (unsigned int) numUsed
  8208. && ((unsigned int) index2) < (unsigned int) numUsed)
  8209. {
  8210. swapVariables (data.elements [index1],
  8211. data.elements [index2]);
  8212. }
  8213. }
  8214. /** Moves one of the objects to a different position.
  8215. This will move the object to a specified index, shuffling along
  8216. any intervening elements as required.
  8217. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8218. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8219. @param currentIndex the index of the object to be moved. If this isn't a
  8220. valid index, then nothing will be done
  8221. @param newIndex the index at which you'd like this object to end up. If this
  8222. is less than zero, it will be moved to the end of the array
  8223. */
  8224. void move (const int currentIndex,
  8225. int newIndex) throw()
  8226. {
  8227. if (currentIndex != newIndex)
  8228. {
  8229. const ScopedLockType lock (getLock());
  8230. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  8231. {
  8232. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  8233. newIndex = numUsed - 1;
  8234. ObjectClass* const value = data.elements [currentIndex];
  8235. if (newIndex > currentIndex)
  8236. {
  8237. memmove (data.elements + currentIndex,
  8238. data.elements + currentIndex + 1,
  8239. (newIndex - currentIndex) * sizeof (ObjectClass*));
  8240. }
  8241. else
  8242. {
  8243. memmove (data.elements + newIndex + 1,
  8244. data.elements + newIndex,
  8245. (currentIndex - newIndex) * sizeof (ObjectClass*));
  8246. }
  8247. data.elements [newIndex] = value;
  8248. }
  8249. }
  8250. }
  8251. /** This swaps the contents of this array with those of another array.
  8252. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  8253. because it just swaps their internal pointers.
  8254. */
  8255. void swapWithArray (ReferenceCountedArray& otherArray) throw()
  8256. {
  8257. const ScopedLockType lock1 (getLock());
  8258. const ScopedLockType lock2 (otherArray.getLock());
  8259. data.swapWith (otherArray.data);
  8260. swapVariables (numUsed, otherArray.numUsed);
  8261. }
  8262. /** Compares this array to another one.
  8263. @returns true only if the other array contains the same objects in the same order
  8264. */
  8265. bool operator== (const ReferenceCountedArray& other) const throw()
  8266. {
  8267. const ScopedLockType lock2 (other.getLock());
  8268. const ScopedLockType lock1 (getLock());
  8269. if (numUsed != other.numUsed)
  8270. return false;
  8271. for (int i = numUsed; --i >= 0;)
  8272. if (data.elements [i] != other.data.elements [i])
  8273. return false;
  8274. return true;
  8275. }
  8276. /** Compares this array to another one.
  8277. @see operator==
  8278. */
  8279. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  8280. {
  8281. return ! operator== (other);
  8282. }
  8283. /** Sorts the elements in the array.
  8284. This will use a comparator object to sort the elements into order. The object
  8285. passed must have a method of the form:
  8286. @code
  8287. int compareElements (ElementType first, ElementType second);
  8288. @endcode
  8289. ..and this method must return:
  8290. - a value of < 0 if the first comes before the second
  8291. - a value of 0 if the two objects are equivalent
  8292. - a value of > 0 if the second comes before the first
  8293. To improve performance, the compareElements() method can be declared as static or const.
  8294. @param comparator the comparator to use for comparing elements.
  8295. @param retainOrderOfEquivalentItems if this is true, then items
  8296. which the comparator says are equivalent will be
  8297. kept in the order in which they currently appear
  8298. in the array. This is slower to perform, but may
  8299. be important in some cases. If it's false, a faster
  8300. algorithm is used, but equivalent elements may be
  8301. rearranged.
  8302. @see sortArray
  8303. */
  8304. template <class ElementComparator>
  8305. void sort (ElementComparator& comparator,
  8306. const bool retainOrderOfEquivalentItems = false) const throw()
  8307. {
  8308. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8309. // avoids getting warning messages about the parameter being unused
  8310. const ScopedLockType lock (getLock());
  8311. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  8312. }
  8313. /** Reduces the amount of storage being used by the array.
  8314. Arrays typically allocate slightly more storage than they need, and after
  8315. removing elements, they may have quite a lot of unused space allocated.
  8316. This method will reduce the amount of allocated storage to a minimum.
  8317. */
  8318. void minimiseStorageOverheads() throw()
  8319. {
  8320. const ScopedLockType lock (getLock());
  8321. data.shrinkToNoMoreThan (numUsed);
  8322. }
  8323. /** Returns the CriticalSection that locks this array.
  8324. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8325. an object of ScopedLockType as an RAII lock for it.
  8326. */
  8327. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  8328. /** Returns the type of scoped lock to use for locking this array */
  8329. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8330. juce_UseDebuggingNewOperator
  8331. private:
  8332. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  8333. int numUsed;
  8334. };
  8335. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  8336. /*** End of inlined file: juce_ReferenceCountedArray.h ***/
  8337. #endif
  8338. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  8339. #endif
  8340. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8341. #endif
  8342. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8343. /*** Start of inlined file: juce_SortedSet.h ***/
  8344. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8345. #define __JUCE_SORTEDSET_JUCEHEADER__
  8346. #if JUCE_MSVC
  8347. #pragma warning (push)
  8348. #pragma warning (disable: 4512)
  8349. #endif
  8350. /**
  8351. Holds a set of unique primitive objects, such as ints or doubles.
  8352. A set can only hold one item with a given value, so if for example it's a
  8353. set of integers, attempting to add the same integer twice will do nothing
  8354. the second time.
  8355. Internally, the list of items is kept sorted (which means that whatever
  8356. kind of primitive type is used must support the ==, <, >, <= and >= operators
  8357. to determine the order), and searching the set for known values is very fast
  8358. because it uses a binary-chop method.
  8359. Note that if you're using a class or struct as the element type, it must be
  8360. capable of being copied or moved with a straightforward memcpy, rather than
  8361. needing construction and destruction code.
  8362. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  8363. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  8364. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  8365. */
  8366. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8367. class SortedSet
  8368. {
  8369. public:
  8370. /** Creates an empty set. */
  8371. SortedSet() throw()
  8372. : numUsed (0)
  8373. {
  8374. }
  8375. /** Creates a copy of another set.
  8376. @param other the set to copy
  8377. */
  8378. SortedSet (const SortedSet& other) throw()
  8379. {
  8380. const ScopedLockType lock (other.getLock());
  8381. numUsed = other.numUsed;
  8382. data.setAllocatedSize (other.numUsed);
  8383. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  8384. }
  8385. /** Destructor. */
  8386. ~SortedSet() throw()
  8387. {
  8388. }
  8389. /** Copies another set over this one.
  8390. @param other the set to copy
  8391. */
  8392. SortedSet& operator= (const SortedSet& other) throw()
  8393. {
  8394. if (this != &other)
  8395. {
  8396. const ScopedLockType lock1 (other.getLock());
  8397. const ScopedLockType lock2 (getLock());
  8398. data.ensureAllocatedSize (other.size());
  8399. numUsed = other.numUsed;
  8400. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  8401. minimiseStorageOverheads();
  8402. }
  8403. return *this;
  8404. }
  8405. /** Compares this set to another one.
  8406. Two sets are considered equal if they both contain the same set of
  8407. elements.
  8408. @param other the other set to compare with
  8409. */
  8410. bool operator== (const SortedSet<ElementType>& other) const throw()
  8411. {
  8412. const ScopedLockType lock (getLock());
  8413. if (numUsed != other.numUsed)
  8414. return false;
  8415. for (int i = numUsed; --i >= 0;)
  8416. if (data.elements[i] != other.data.elements[i])
  8417. return false;
  8418. return true;
  8419. }
  8420. /** Compares this set to another one.
  8421. Two sets are considered equal if they both contain the same set of
  8422. elements.
  8423. @param other the other set to compare with
  8424. */
  8425. bool operator!= (const SortedSet<ElementType>& other) const throw()
  8426. {
  8427. return ! operator== (other);
  8428. }
  8429. /** Removes all elements from the set.
  8430. This will remove all the elements, and free any storage that the set is
  8431. using. To clear it without freeing the storage, use the clearQuick()
  8432. method instead.
  8433. @see clearQuick
  8434. */
  8435. void clear() throw()
  8436. {
  8437. const ScopedLockType lock (getLock());
  8438. data.setAllocatedSize (0);
  8439. numUsed = 0;
  8440. }
  8441. /** Removes all elements from the set without freeing the array's allocated storage.
  8442. @see clear
  8443. */
  8444. void clearQuick() throw()
  8445. {
  8446. const ScopedLockType lock (getLock());
  8447. numUsed = 0;
  8448. }
  8449. /** Returns the current number of elements in the set.
  8450. */
  8451. inline int size() const throw()
  8452. {
  8453. return numUsed;
  8454. }
  8455. /** Returns one of the elements in the set.
  8456. If the index passed in is beyond the range of valid elements, this
  8457. will return zero.
  8458. If you're certain that the index will always be a valid element, you
  8459. can call getUnchecked() instead, which is faster.
  8460. @param index the index of the element being requested (0 is the first element in the set)
  8461. @see getUnchecked, getFirst, getLast
  8462. */
  8463. inline ElementType operator[] (const int index) const throw()
  8464. {
  8465. const ScopedLockType lock (getLock());
  8466. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  8467. : ElementType();
  8468. }
  8469. /** Returns one of the elements in the set, without checking the index passed in.
  8470. Unlike the operator[] method, this will try to return an element without
  8471. checking that the index is within the bounds of the set, so should only
  8472. be used when you're confident that it will always be a valid index.
  8473. @param index the index of the element being requested (0 is the first element in the set)
  8474. @see operator[], getFirst, getLast
  8475. */
  8476. inline ElementType getUnchecked (const int index) const throw()
  8477. {
  8478. const ScopedLockType lock (getLock());
  8479. jassert (((unsigned int) index) < (unsigned int) numUsed);
  8480. return data.elements [index];
  8481. }
  8482. /** Returns the first element in the set, or 0 if the set is empty.
  8483. @see operator[], getUnchecked, getLast
  8484. */
  8485. inline ElementType getFirst() const throw()
  8486. {
  8487. const ScopedLockType lock (getLock());
  8488. return numUsed > 0 ? data.elements [0] : ElementType();
  8489. }
  8490. /** Returns the last element in the set, or 0 if the set is empty.
  8491. @see operator[], getUnchecked, getFirst
  8492. */
  8493. inline ElementType getLast() const throw()
  8494. {
  8495. const ScopedLockType lock (getLock());
  8496. return numUsed > 0 ? data.elements [numUsed - 1] : ElementType();
  8497. }
  8498. /** Finds the index of the first element which matches the value passed in.
  8499. This will search the set for the given object, and return the index
  8500. of its first occurrence. If the object isn't found, the method will return -1.
  8501. @param elementToLookFor the value or object to look for
  8502. @returns the index of the object, or -1 if it's not found
  8503. */
  8504. int indexOf (const ElementType elementToLookFor) const throw()
  8505. {
  8506. const ScopedLockType lock (getLock());
  8507. int start = 0;
  8508. int end = numUsed;
  8509. for (;;)
  8510. {
  8511. if (start >= end)
  8512. {
  8513. return -1;
  8514. }
  8515. else if (elementToLookFor == data.elements [start])
  8516. {
  8517. return start;
  8518. }
  8519. else
  8520. {
  8521. const int halfway = (start + end) >> 1;
  8522. if (halfway == start)
  8523. return -1;
  8524. else if (elementToLookFor >= data.elements [halfway])
  8525. start = halfway;
  8526. else
  8527. end = halfway;
  8528. }
  8529. }
  8530. }
  8531. /** Returns true if the set contains at least one occurrence of an object.
  8532. @param elementToLookFor the value or object to look for
  8533. @returns true if the item is found
  8534. */
  8535. bool contains (const ElementType elementToLookFor) const throw()
  8536. {
  8537. const ScopedLockType lock (getLock());
  8538. int start = 0;
  8539. int end = numUsed;
  8540. for (;;)
  8541. {
  8542. if (start >= end)
  8543. {
  8544. return false;
  8545. }
  8546. else if (elementToLookFor == data.elements [start])
  8547. {
  8548. return true;
  8549. }
  8550. else
  8551. {
  8552. const int halfway = (start + end) >> 1;
  8553. if (halfway == start)
  8554. return false;
  8555. else if (elementToLookFor >= data.elements [halfway])
  8556. start = halfway;
  8557. else
  8558. end = halfway;
  8559. }
  8560. }
  8561. }
  8562. /** Adds a new element to the set, (as long as it's not already in there).
  8563. @param newElement the new object to add to the set
  8564. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  8565. */
  8566. void add (const ElementType newElement) throw()
  8567. {
  8568. const ScopedLockType lock (getLock());
  8569. int start = 0;
  8570. int end = numUsed;
  8571. for (;;)
  8572. {
  8573. if (start >= end)
  8574. {
  8575. jassert (start <= end);
  8576. insertInternal (start, newElement);
  8577. break;
  8578. }
  8579. else if (newElement == data.elements [start])
  8580. {
  8581. break;
  8582. }
  8583. else
  8584. {
  8585. const int halfway = (start + end) >> 1;
  8586. if (halfway == start)
  8587. {
  8588. if (newElement >= data.elements [halfway])
  8589. insertInternal (start + 1, newElement);
  8590. else
  8591. insertInternal (start, newElement);
  8592. break;
  8593. }
  8594. else if (newElement >= data.elements [halfway])
  8595. start = halfway;
  8596. else
  8597. end = halfway;
  8598. }
  8599. }
  8600. }
  8601. /** Adds elements from an array to this set.
  8602. @param elementsToAdd the array of elements to add
  8603. @param numElementsToAdd how many elements are in this other array
  8604. @see add
  8605. */
  8606. void addArray (const ElementType* elementsToAdd,
  8607. int numElementsToAdd) throw()
  8608. {
  8609. const ScopedLockType lock (getLock());
  8610. while (--numElementsToAdd >= 0)
  8611. add (*elementsToAdd++);
  8612. }
  8613. /** Adds elements from another set to this one.
  8614. @param setToAddFrom the set from which to copy the elements
  8615. @param startIndex the first element of the other set to start copying from
  8616. @param numElementsToAdd how many elements to add from the other set. If this
  8617. value is negative or greater than the number of available elements,
  8618. all available elements will be copied.
  8619. @see add
  8620. */
  8621. template <class OtherSetType>
  8622. void addSet (const OtherSetType& setToAddFrom,
  8623. int startIndex = 0,
  8624. int numElementsToAdd = -1) throw()
  8625. {
  8626. const typename OtherSetType::ScopedLockType lock1 (setToAddFrom.getLock());
  8627. const ScopedLockType lock2 (getLock());
  8628. jassert (this != &setToAddFrom);
  8629. if (this != &setToAddFrom)
  8630. {
  8631. if (startIndex < 0)
  8632. {
  8633. jassertfalse;
  8634. startIndex = 0;
  8635. }
  8636. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  8637. numElementsToAdd = setToAddFrom.size() - startIndex;
  8638. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  8639. }
  8640. }
  8641. /** Removes an element from the set.
  8642. This will remove the element at a given index.
  8643. If the index passed in is out-of-range, nothing will happen.
  8644. @param indexToRemove the index of the element to remove
  8645. @returns the element that has been removed
  8646. @see removeValue, removeRange
  8647. */
  8648. ElementType remove (const int indexToRemove) throw()
  8649. {
  8650. const ScopedLockType lock (getLock());
  8651. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8652. {
  8653. --numUsed;
  8654. ElementType* const e = data.elements + indexToRemove;
  8655. ElementType const removed = *e;
  8656. const int numberToShift = numUsed - indexToRemove;
  8657. if (numberToShift > 0)
  8658. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  8659. if ((numUsed << 1) < data.numAllocated)
  8660. minimiseStorageOverheads();
  8661. return removed;
  8662. }
  8663. return 0;
  8664. }
  8665. /** Removes an item from the set.
  8666. This will remove the given element from the set, if it's there.
  8667. @param valueToRemove the object to try to remove
  8668. @see remove, removeRange
  8669. */
  8670. void removeValue (const ElementType valueToRemove) throw()
  8671. {
  8672. const ScopedLockType lock (getLock());
  8673. remove (indexOf (valueToRemove));
  8674. }
  8675. /** Removes any elements which are also in another set.
  8676. @param otherSet the other set in which to look for elements to remove
  8677. @see removeValuesNotIn, remove, removeValue, removeRange
  8678. */
  8679. template <class OtherSetType>
  8680. void removeValuesIn (const OtherSetType& otherSet) throw()
  8681. {
  8682. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  8683. const ScopedLockType lock2 (getLock());
  8684. if (this == &otherSet)
  8685. {
  8686. clear();
  8687. }
  8688. else
  8689. {
  8690. if (otherSet.size() > 0)
  8691. {
  8692. for (int i = numUsed; --i >= 0;)
  8693. if (otherSet.contains (data.elements [i]))
  8694. remove (i);
  8695. }
  8696. }
  8697. }
  8698. /** Removes any elements which are not found in another set.
  8699. Only elements which occur in this other set will be retained.
  8700. @param otherSet the set in which to look for elements NOT to remove
  8701. @see removeValuesIn, remove, removeValue, removeRange
  8702. */
  8703. template <class OtherSetType>
  8704. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  8705. {
  8706. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  8707. const ScopedLockType lock2 (getLock());
  8708. if (this != &otherSet)
  8709. {
  8710. if (otherSet.size() <= 0)
  8711. {
  8712. clear();
  8713. }
  8714. else
  8715. {
  8716. for (int i = numUsed; --i >= 0;)
  8717. if (! otherSet.contains (data.elements [i]))
  8718. remove (i);
  8719. }
  8720. }
  8721. }
  8722. /** Reduces the amount of storage being used by the set.
  8723. Sets typically allocate slightly more storage than they need, and after
  8724. removing elements, they may have quite a lot of unused space allocated.
  8725. This method will reduce the amount of allocated storage to a minimum.
  8726. */
  8727. void minimiseStorageOverheads() throw()
  8728. {
  8729. const ScopedLockType lock (getLock());
  8730. data.shrinkToNoMoreThan (numUsed);
  8731. }
  8732. /** Returns the CriticalSection that locks this array.
  8733. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8734. an object of ScopedLockType as an RAII lock for it.
  8735. */
  8736. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  8737. /** Returns the type of scoped lock to use for locking this array */
  8738. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8739. juce_UseDebuggingNewOperator
  8740. private:
  8741. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  8742. int numUsed;
  8743. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  8744. {
  8745. data.ensureAllocatedSize (numUsed + 1);
  8746. ElementType* const insertPos = data.elements + indexToInsertAt;
  8747. const int numberToMove = numUsed - indexToInsertAt;
  8748. if (numberToMove > 0)
  8749. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  8750. *insertPos = newElement;
  8751. ++numUsed;
  8752. }
  8753. };
  8754. #if JUCE_MSVC
  8755. #pragma warning (pop)
  8756. #endif
  8757. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  8758. /*** End of inlined file: juce_SortedSet.h ***/
  8759. #endif
  8760. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8761. /*** Start of inlined file: juce_SparseSet.h ***/
  8762. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8763. #define __JUCE_SPARSESET_JUCEHEADER__
  8764. /**
  8765. Holds a set of primitive values, storing them as a set of ranges.
  8766. This container acts like an array, but can efficiently hold large continguous
  8767. ranges of values. It's quite a specialised class, mostly useful for things
  8768. like keeping the set of selected rows in a listbox.
  8769. The type used as a template paramter must be an integer type, such as int, short,
  8770. int64, etc.
  8771. */
  8772. template <class Type>
  8773. class SparseSet
  8774. {
  8775. public:
  8776. /** Creates a new empty set. */
  8777. SparseSet()
  8778. {
  8779. }
  8780. /** Creates a copy of another SparseSet. */
  8781. SparseSet (const SparseSet<Type>& other)
  8782. : values (other.values)
  8783. {
  8784. }
  8785. /** Destructor. */
  8786. ~SparseSet()
  8787. {
  8788. }
  8789. /** Clears the set. */
  8790. void clear()
  8791. {
  8792. values.clear();
  8793. }
  8794. /** Checks whether the set is empty.
  8795. This is much quicker than using (size() == 0).
  8796. */
  8797. bool isEmpty() const throw()
  8798. {
  8799. return values.size() == 0;
  8800. }
  8801. /** Returns the number of values in the set.
  8802. Because of the way the data is stored, this method can take longer if there
  8803. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  8804. are any items.
  8805. */
  8806. Type size() const
  8807. {
  8808. Type total (0);
  8809. for (int i = 0; i < values.size(); i += 2)
  8810. total += values.getUnchecked (i + 1) - values.getUnchecked (i);
  8811. return total;
  8812. }
  8813. /** Returns one of the values in the set.
  8814. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  8815. @returns the value at this index, or 0 if it's out-of-range
  8816. */
  8817. Type operator[] (Type index) const
  8818. {
  8819. for (int i = 0; i < values.size(); i += 2)
  8820. {
  8821. const Type start (values.getUnchecked (i));
  8822. const Type len (values.getUnchecked (i + 1) - start);
  8823. if (index < len)
  8824. return start + index;
  8825. index -= len;
  8826. }
  8827. return Type (0);
  8828. }
  8829. /** Checks whether a particular value is in the set. */
  8830. bool contains (const Type valueToLookFor) const
  8831. {
  8832. for (int i = 0; i < values.size(); ++i)
  8833. if (valueToLookFor < values.getUnchecked(i))
  8834. return (i & 1) != 0;
  8835. return false;
  8836. }
  8837. /** Returns the number of contiguous blocks of values.
  8838. @see getRange
  8839. */
  8840. int getNumRanges() const throw()
  8841. {
  8842. return values.size() >> 1;
  8843. }
  8844. /** Returns one of the contiguous ranges of values stored.
  8845. @param rangeIndex the index of the range to look up, between 0
  8846. and (getNumRanges() - 1)
  8847. @see getTotalRange
  8848. */
  8849. const Range<Type> getRange (const int rangeIndex) const
  8850. {
  8851. if (((unsigned int) rangeIndex) < (unsigned int) getNumRanges())
  8852. return Range<Type> (values.getUnchecked (rangeIndex << 1),
  8853. values.getUnchecked ((rangeIndex << 1) + 1));
  8854. else
  8855. return Range<Type>();
  8856. }
  8857. /** Returns the range between the lowest and highest values in the set.
  8858. @see getRange
  8859. */
  8860. const Range<Type> getTotalRange() const
  8861. {
  8862. if (values.size() > 0)
  8863. {
  8864. jassert ((values.size() & 1) == 0);
  8865. return Range<Type> (values.getUnchecked (0),
  8866. values.getUnchecked (values.size() - 1));
  8867. }
  8868. return Range<Type>();
  8869. }
  8870. /** Adds a range of contiguous values to the set.
  8871. e.g. addRange (Range \<int\> (10, 14)) will add (10, 11, 12, 13) to the set.
  8872. */
  8873. void addRange (const Range<Type>& range)
  8874. {
  8875. jassert (range.getLength() >= 0);
  8876. if (range.getLength() > 0)
  8877. {
  8878. removeRange (range);
  8879. values.addUsingDefaultSort (range.getStart());
  8880. values.addUsingDefaultSort (range.getEnd());
  8881. simplify();
  8882. }
  8883. }
  8884. /** Removes a range of values from the set.
  8885. e.g. removeRange (Range\<int\> (10, 14)) will remove (10, 11, 12, 13) from the set.
  8886. */
  8887. void removeRange (const Range<Type>& rangeToRemove)
  8888. {
  8889. jassert (rangeToRemove.getLength() >= 0);
  8890. if (rangeToRemove.getLength() > 0
  8891. && values.size() > 0
  8892. && rangeToRemove.getStart() < values.getUnchecked (values.size() - 1)
  8893. && values.getUnchecked(0) < rangeToRemove.getEnd())
  8894. {
  8895. const bool onAtStart = contains (rangeToRemove.getStart() - 1);
  8896. const Type lastValue (jmin (rangeToRemove.getEnd(), values.getLast()));
  8897. const bool onAtEnd = contains (lastValue);
  8898. for (int i = values.size(); --i >= 0;)
  8899. {
  8900. if (values.getUnchecked(i) <= lastValue)
  8901. {
  8902. while (values.getUnchecked(i) >= rangeToRemove.getStart())
  8903. {
  8904. values.remove (i);
  8905. if (--i < 0)
  8906. break;
  8907. }
  8908. break;
  8909. }
  8910. }
  8911. if (onAtStart) values.addUsingDefaultSort (rangeToRemove.getStart());
  8912. if (onAtEnd) values.addUsingDefaultSort (lastValue);
  8913. simplify();
  8914. }
  8915. }
  8916. /** Does an XOR of the values in a given range. */
  8917. void invertRange (const Range<Type>& range)
  8918. {
  8919. SparseSet newItems;
  8920. newItems.addRange (range);
  8921. int i;
  8922. for (i = getNumRanges(); --i >= 0;)
  8923. newItems.removeRange (getRange (i));
  8924. removeRange (range);
  8925. for (i = newItems.getNumRanges(); --i >= 0;)
  8926. addRange (newItems.getRange(i));
  8927. }
  8928. /** Checks whether any part of a given range overlaps any part of this set. */
  8929. bool overlapsRange (const Range<Type>& range)
  8930. {
  8931. if (range.getLength() > 0)
  8932. {
  8933. for (int i = getNumRanges(); --i >= 0;)
  8934. {
  8935. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  8936. return false;
  8937. if (values.getUnchecked (i << 1) < range.getEnd())
  8938. return true;
  8939. }
  8940. }
  8941. return false;
  8942. }
  8943. /** Checks whether the whole of a given range is contained within this one. */
  8944. bool containsRange (const Range<Type>& range)
  8945. {
  8946. if (range.getLength() > 0)
  8947. {
  8948. for (int i = getNumRanges(); --i >= 0;)
  8949. {
  8950. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  8951. return false;
  8952. if (values.getUnchecked (i << 1) <= range.getStart()
  8953. && range.getEnd() <= values.getUnchecked ((i << 1) + 1))
  8954. return true;
  8955. }
  8956. }
  8957. return false;
  8958. }
  8959. bool operator== (const SparseSet<Type>& other) throw()
  8960. {
  8961. return values == other.values;
  8962. }
  8963. bool operator!= (const SparseSet<Type>& other) throw()
  8964. {
  8965. return values != other.values;
  8966. }
  8967. juce_UseDebuggingNewOperator
  8968. private:
  8969. // alternating start/end values of ranges of values that are present.
  8970. Array<Type, DummyCriticalSection> values;
  8971. void simplify()
  8972. {
  8973. jassert ((values.size() & 1) == 0);
  8974. for (int i = values.size(); --i > 0;)
  8975. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  8976. values.removeRange (--i, 2);
  8977. }
  8978. };
  8979. #endif // __JUCE_SPARSESET_JUCEHEADER__
  8980. /*** End of inlined file: juce_SparseSet.h ***/
  8981. #endif
  8982. #ifndef __JUCE_VALUE_JUCEHEADER__
  8983. /*** Start of inlined file: juce_Value.h ***/
  8984. #ifndef __JUCE_VALUE_JUCEHEADER__
  8985. #define __JUCE_VALUE_JUCEHEADER__
  8986. /*** Start of inlined file: juce_AsyncUpdater.h ***/
  8987. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  8988. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  8989. /*** Start of inlined file: juce_MessageListener.h ***/
  8990. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  8991. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  8992. /*** Start of inlined file: juce_Message.h ***/
  8993. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  8994. #define __JUCE_MESSAGE_JUCEHEADER__
  8995. class MessageListener;
  8996. class MessageManager;
  8997. /** The base class for objects that can be delivered to a MessageListener.
  8998. The simplest Message object contains a few integer and pointer parameters
  8999. that the user can set, and this is enough for a lot of purposes. For passing more
  9000. complex data, subclasses of Message can also be used.
  9001. @see MessageListener, MessageManager, ActionListener, ChangeListener
  9002. */
  9003. class JUCE_API Message
  9004. {
  9005. public:
  9006. /** Creates an uninitialised message.
  9007. The class's variables will also be left uninitialised.
  9008. */
  9009. Message() throw();
  9010. /** Creates a message object, filling in the member variables.
  9011. The corresponding public member variables will be set from the parameters
  9012. passed in.
  9013. */
  9014. Message (int intParameter1,
  9015. int intParameter2,
  9016. int intParameter3,
  9017. void* pointerParameter) throw();
  9018. /** Destructor. */
  9019. virtual ~Message() throw();
  9020. // These values can be used for carrying simple data that the application needs to
  9021. // pass around. For more complex messages, just create a subclass.
  9022. int intParameter1; /**< user-defined integer value. */
  9023. int intParameter2; /**< user-defined integer value. */
  9024. int intParameter3; /**< user-defined integer value. */
  9025. void* pointerParameter; /**< user-defined pointer value. */
  9026. juce_UseDebuggingNewOperator
  9027. private:
  9028. friend class MessageListener;
  9029. friend class MessageManager;
  9030. MessageListener* messageRecipient;
  9031. Message (const Message&);
  9032. Message& operator= (const Message&);
  9033. };
  9034. #endif // __JUCE_MESSAGE_JUCEHEADER__
  9035. /*** End of inlined file: juce_Message.h ***/
  9036. /**
  9037. MessageListener subclasses can post and receive Message objects.
  9038. @see Message, MessageManager, ActionListener, ChangeListener
  9039. */
  9040. class JUCE_API MessageListener
  9041. {
  9042. protected:
  9043. /** Creates a MessageListener. */
  9044. MessageListener() throw();
  9045. public:
  9046. /** Destructor.
  9047. When a MessageListener is deleted, it removes itself from a global list
  9048. of registered listeners, so that the isValidMessageListener() method
  9049. will no longer return true.
  9050. */
  9051. virtual ~MessageListener();
  9052. /** This is the callback method that receives incoming messages.
  9053. This is called by the MessageManager from its dispatch loop.
  9054. @see postMessage
  9055. */
  9056. virtual void handleMessage (const Message& message) = 0;
  9057. /** Sends a message to the message queue, for asynchronous delivery to this listener
  9058. later on.
  9059. This method can be called safely by any thread.
  9060. @param message the message object to send - this will be deleted
  9061. automatically by the message queue, so don't keep any
  9062. references to it after calling this method.
  9063. @see handleMessage
  9064. */
  9065. void postMessage (Message* message) const throw();
  9066. /** Checks whether this MessageListener has been deleted.
  9067. Although not foolproof, this method is safe to call on dangling or null
  9068. pointers. A list of active MessageListeners is kept internally, so this
  9069. checks whether the object is on this list or not.
  9070. Note that it's possible to get a false-positive here, if an object is
  9071. deleted and another is subsequently created that happens to be at the
  9072. exact same memory location, but I can't think of a good way of avoiding
  9073. this.
  9074. */
  9075. bool isValidMessageListener() const throw();
  9076. };
  9077. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  9078. /*** End of inlined file: juce_MessageListener.h ***/
  9079. /**
  9080. Has a callback method that is triggered asynchronously.
  9081. This object allows an asynchronous callback function to be triggered, for
  9082. tasks such as coalescing multiple updates into a single callback later on.
  9083. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  9084. message thread calling handleAsyncUpdate() as soon as it can.
  9085. */
  9086. class JUCE_API AsyncUpdater
  9087. {
  9088. public:
  9089. /** Creates an AsyncUpdater object. */
  9090. AsyncUpdater() throw();
  9091. /** Destructor.
  9092. If there are any pending callbacks when the object is deleted, these are lost.
  9093. */
  9094. virtual ~AsyncUpdater();
  9095. /** Causes the callback to be triggered at a later time.
  9096. This method returns immediately, having made sure that a callback
  9097. to the handleAsyncUpdate() method will occur as soon as possible.
  9098. If an update callback is already pending but hasn't happened yet, calls
  9099. to this method will be ignored.
  9100. It's thread-safe to call this method from any number of threads without
  9101. needing to worry about locking.
  9102. */
  9103. void triggerAsyncUpdate() throw();
  9104. /** This will stop any pending updates from happening.
  9105. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  9106. callback happens, this will cancel the handleAsyncUpdate() callback.
  9107. */
  9108. void cancelPendingUpdate() throw();
  9109. /** If an update has been triggered and is pending, this will invoke it
  9110. synchronously.
  9111. Use this as a kind of "flush" operation - if an update is pending, the
  9112. handleAsyncUpdate() method will be called immediately; if no update is
  9113. pending, then nothing will be done.
  9114. */
  9115. void handleUpdateNowIfNeeded();
  9116. /** Called back to do whatever your class needs to do.
  9117. This method is called by the message thread at the next convenient time
  9118. after the triggerAsyncUpdate() method has been called.
  9119. */
  9120. virtual void handleAsyncUpdate() = 0;
  9121. private:
  9122. class AsyncUpdaterInternal : public MessageListener
  9123. {
  9124. public:
  9125. AsyncUpdaterInternal() throw() {}
  9126. ~AsyncUpdaterInternal() {}
  9127. void handleMessage (const Message&);
  9128. AsyncUpdater* owner;
  9129. private:
  9130. AsyncUpdaterInternal (const AsyncUpdaterInternal&);
  9131. AsyncUpdaterInternal& operator= (const AsyncUpdaterInternal&);
  9132. };
  9133. AsyncUpdaterInternal internalAsyncHandler;
  9134. bool asyncMessagePending;
  9135. };
  9136. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  9137. /*** End of inlined file: juce_AsyncUpdater.h ***/
  9138. /*** Start of inlined file: juce_ListenerList.h ***/
  9139. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  9140. #define __JUCE_LISTENERLIST_JUCEHEADER__
  9141. /**
  9142. Holds a set of objects and can invoke a member function callback on each object
  9143. in the set with a single call.
  9144. Use a ListenerList to manage a set of objects which need a callback, and you
  9145. can invoke a member function by simply calling call() or callChecked().
  9146. E.g.
  9147. @code
  9148. class MyListenerType
  9149. {
  9150. public:
  9151. void myCallbackMethod (int foo, bool bar);
  9152. };
  9153. ListenerList <MyListenerType> listeners;
  9154. listeners.add (someCallbackObjects...);
  9155. // This will invoke myCallbackMethod (1234, true) on each of the objects
  9156. // in the list...
  9157. listeners.call (&MyListenerType::myCallbackMethod, 1234, true);
  9158. @endcode
  9159. If you add or remove listeners from the list during one of the callbacks - i.e. while
  9160. it's in the middle of iterating the listeners, then it's guaranteed that no listeners
  9161. will be mistakenly called after they've been removed, but it may mean that some of the
  9162. listeners could be called more than once, or not at all, depending on the list's order.
  9163. Sometimes, there's a chance that invoking one of the callbacks might result in the
  9164. list itself being deleted while it's still iterating - to survive this situation, you can
  9165. use callChecked() instead of call(), passing it a local object to act as a "BailOutChecker".
  9166. The BailOutChecker must implement a method of the form "bool shouldBailOut()", and
  9167. the list will check this after each callback to determine whether it should abort the
  9168. operation. For an example of a bail-out checker, see the Component::BailOutChecker class,
  9169. which can be used to check when a Component has been deleted. See also
  9170. ListenerList::DummyBailOutChecker, which is a dummy checker that always returns false.
  9171. */
  9172. template <class ListenerClass,
  9173. class ArrayType = Array <ListenerClass*> >
  9174. class ListenerList
  9175. {
  9176. // Horrible macros required to support VC6/7..
  9177. #if defined (_MSC_VER) && _MSC_VER <= 1400
  9178. #define LL_TEMPLATE(a) typename P##a, typename Q##a
  9179. #define LL_PARAM(a) Q##a& param##a
  9180. #else
  9181. #define LL_TEMPLATE(a) typename P##a
  9182. #define LL_PARAM(a) PARAMETER_TYPE(P##a) param##a
  9183. #endif
  9184. public:
  9185. /** Creates an empty list. */
  9186. ListenerList()
  9187. {
  9188. }
  9189. /** Destructor. */
  9190. ~ListenerList()
  9191. {
  9192. }
  9193. /** Adds a listener to the list.
  9194. A listener can only be added once, so if the listener is already in the list,
  9195. this method has no effect.
  9196. @see remove
  9197. */
  9198. void add (ListenerClass* const listenerToAdd)
  9199. {
  9200. // Listeners can't be null pointers!
  9201. jassert (listenerToAdd != 0);
  9202. if (listenerToAdd != 0)
  9203. listeners.addIfNotAlreadyThere (listenerToAdd);
  9204. }
  9205. /** Removes a listener from the list.
  9206. If the listener wasn't in the list, this has no effect.
  9207. */
  9208. void remove (ListenerClass* const listenerToRemove)
  9209. {
  9210. // Listeners can't be null pointers!
  9211. jassert (listenerToRemove != 0);
  9212. listeners.removeValue (listenerToRemove);
  9213. }
  9214. /** Returns the number of registered listeners. */
  9215. int size() const throw()
  9216. {
  9217. return listeners.size();
  9218. }
  9219. /** Returns true if any listeners are registered. */
  9220. bool isEmpty() const throw()
  9221. {
  9222. return listeners.size() == 0;
  9223. }
  9224. /** Returns true if the specified listener has been added to the list. */
  9225. bool contains (ListenerClass* const listener) const throw()
  9226. {
  9227. return listeners.contains (listener);
  9228. }
  9229. /** Calls a member function on each listener in the list, with no parameters. */
  9230. void call (void (ListenerClass::*callbackFunction) ())
  9231. {
  9232. callChecked (static_cast <const DummyBailOutChecker&> (DummyBailOutChecker()), callbackFunction);
  9233. }
  9234. /** Calls a member function on each listener in the list, with no parameters and a bail-out-checker.
  9235. See the class description for info about writing a bail-out checker. */
  9236. template <class BailOutCheckerType>
  9237. void callChecked (const BailOutCheckerType& bailOutChecker,
  9238. void (ListenerClass::*callbackFunction) ())
  9239. {
  9240. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9241. (iter.getListener()->*callbackFunction) ();
  9242. }
  9243. /** Calls a member function on each listener in the list, with 1 parameter. */
  9244. template <LL_TEMPLATE(1)>
  9245. void call (void (ListenerClass::*callbackFunction) (P1), LL_PARAM(1))
  9246. {
  9247. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9248. (iter.getListener()->*callbackFunction) (param1);
  9249. }
  9250. /** Calls a member function on each listener in the list, with one parameter and a bail-out-checker.
  9251. See the class description for info about writing a bail-out checker. */
  9252. template <class BailOutCheckerType, LL_TEMPLATE(1)>
  9253. void callChecked (const BailOutCheckerType& bailOutChecker,
  9254. void (ListenerClass::*callbackFunction) (P1),
  9255. LL_PARAM(1))
  9256. {
  9257. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9258. (iter.getListener()->*callbackFunction) (param1);
  9259. }
  9260. /** Calls a member function on each listener in the list, with 2 parameters. */
  9261. template <LL_TEMPLATE(1), LL_TEMPLATE(2)>
  9262. void call (void (ListenerClass::*callbackFunction) (P1, P2),
  9263. LL_PARAM(1), LL_PARAM(2))
  9264. {
  9265. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9266. (iter.getListener()->*callbackFunction) (param1, param2);
  9267. }
  9268. /** Calls a member function on each listener in the list, with 2 parameters and a bail-out-checker.
  9269. See the class description for info about writing a bail-out checker. */
  9270. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2)>
  9271. void callChecked (const BailOutCheckerType& bailOutChecker,
  9272. void (ListenerClass::*callbackFunction) (P1, P2),
  9273. LL_PARAM(1), LL_PARAM(2))
  9274. {
  9275. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9276. (iter.getListener()->*callbackFunction) (param1, param2);
  9277. }
  9278. /** Calls a member function on each listener in the list, with 3 parameters. */
  9279. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  9280. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3),
  9281. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  9282. {
  9283. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9284. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  9285. }
  9286. /** Calls a member function on each listener in the list, with 3 parameters and a bail-out-checker.
  9287. See the class description for info about writing a bail-out checker. */
  9288. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  9289. void callChecked (const BailOutCheckerType& bailOutChecker,
  9290. void (ListenerClass::*callbackFunction) (P1, P2, P3),
  9291. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  9292. {
  9293. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9294. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  9295. }
  9296. /** Calls a member function on each listener in the list, with 4 parameters. */
  9297. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  9298. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  9299. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  9300. {
  9301. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9302. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  9303. }
  9304. /** Calls a member function on each listener in the list, with 4 parameters and a bail-out-checker.
  9305. See the class description for info about writing a bail-out checker. */
  9306. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  9307. void callChecked (const BailOutCheckerType& bailOutChecker,
  9308. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  9309. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  9310. {
  9311. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9312. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  9313. }
  9314. /** Calls a member function on each listener in the list, with 5 parameters. */
  9315. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  9316. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  9317. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  9318. {
  9319. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9320. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  9321. }
  9322. /** Calls a member function on each listener in the list, with 5 parameters and a bail-out-checker.
  9323. See the class description for info about writing a bail-out checker. */
  9324. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  9325. void callChecked (const BailOutCheckerType& bailOutChecker,
  9326. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  9327. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  9328. {
  9329. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9330. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  9331. }
  9332. /** A dummy bail-out checker that always returns false.
  9333. See the ListenerList notes for more info about bail-out checkers.
  9334. */
  9335. class DummyBailOutChecker
  9336. {
  9337. public:
  9338. inline bool shouldBailOut() const throw() { return false; }
  9339. };
  9340. /** Iterates the listeners in a ListenerList. */
  9341. template <class BailOutCheckerType, class ListType>
  9342. class Iterator
  9343. {
  9344. public:
  9345. Iterator (const ListType& list_, const BailOutCheckerType& bailOutChecker_)
  9346. : list (list_), bailOutChecker (bailOutChecker_), index (list_.size())
  9347. {}
  9348. ~Iterator() {}
  9349. bool next()
  9350. {
  9351. if (index <= 0 || bailOutChecker.shouldBailOut())
  9352. return false;
  9353. const int listSize = list.size();
  9354. if (--index < listSize)
  9355. return true;
  9356. index = listSize - 1;
  9357. return index >= 0;
  9358. }
  9359. typename ListType::ListenerType* getListener() const throw()
  9360. {
  9361. return list.getListeners().getUnchecked (index);
  9362. }
  9363. private:
  9364. const ListType& list;
  9365. const BailOutCheckerType& bailOutChecker;
  9366. int index;
  9367. Iterator (const Iterator&);
  9368. Iterator& operator= (const Iterator&);
  9369. };
  9370. typedef ListenerList<ListenerClass, ArrayType> ThisType;
  9371. typedef ListenerClass ListenerType;
  9372. const ArrayType& getListeners() const throw() { return listeners; }
  9373. private:
  9374. ArrayType listeners;
  9375. ListenerList (const ListenerList&);
  9376. ListenerList& operator= (const ListenerList&);
  9377. #undef LL_TEMPLATE
  9378. #undef LL_PARAM
  9379. };
  9380. #endif // __JUCE_LISTENERLIST_JUCEHEADER__
  9381. /*** End of inlined file: juce_ListenerList.h ***/
  9382. /**
  9383. Represents a shared variant value.
  9384. A Value object contains a reference to a var object, and can get and set its value.
  9385. Listeners can be attached to be told when the value is changed.
  9386. The Value class is a wrapper around a shared, reference-counted underlying data
  9387. object - this means that multiple Value objects can all refer to the same piece of
  9388. data, allowing all of them to be notified when any of them changes it.
  9389. When you create a Value with its default constructor, it acts as a wrapper around a
  9390. simple var object, but by creating a Value that refers to a custom subclass of ValueSource,
  9391. you can map the Value onto any kind of underlying data.
  9392. */
  9393. class JUCE_API Value
  9394. {
  9395. public:
  9396. /** Creates an empty Value, containing a void var. */
  9397. Value();
  9398. /** Creates a Value that refers to the same value as another one.
  9399. Note that this doesn't make a copy of the other value - both this and the other
  9400. Value will share the same underlying value, so that when either one alters it, both
  9401. will see it change.
  9402. */
  9403. Value (const Value& other);
  9404. /** Creates a Value that is set to the specified value. */
  9405. explicit Value (const var& initialValue);
  9406. /** Destructor. */
  9407. ~Value();
  9408. /** Returns the current value. */
  9409. const var getValue() const;
  9410. /** Returns the current value. */
  9411. operator const var() const;
  9412. /** Returns the value as a string.
  9413. This is alternative to writing things like "myValue.getValue().toString()".
  9414. */
  9415. const String toString() const;
  9416. /** Sets the current value.
  9417. You can also use operator= to set the value.
  9418. If there are any listeners registered, they will be notified of the
  9419. change asynchronously.
  9420. */
  9421. void setValue (const var& newValue);
  9422. /** Sets the current value.
  9423. This is the same as calling setValue().
  9424. If there are any listeners registered, they will be notified of the
  9425. change asynchronously.
  9426. */
  9427. Value& operator= (const var& newValue);
  9428. /** Makes this object refer to the same underlying ValueSource as another one.
  9429. Once this object has been connected to another one, changing either one
  9430. will update the other.
  9431. Existing listeners will still be registered after you call this method, and
  9432. they'll continue to receive messages when the new value changes.
  9433. */
  9434. void referTo (const Value& valueToReferTo);
  9435. /** Returns true if this value and the other one are references to the same value.
  9436. */
  9437. bool refersToSameSourceAs (const Value& other) const;
  9438. /** Compares two values.
  9439. This is a compare-by-value comparison, so is effectively the same as
  9440. saying (this->getValue() == other.getValue()).
  9441. */
  9442. bool operator== (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. /** Receives callbacks when a Value object changes.
  9449. @see Value::addListener
  9450. */
  9451. class JUCE_API Listener
  9452. {
  9453. public:
  9454. Listener() {}
  9455. virtual ~Listener() {}
  9456. /** Called when a Value object is changed.
  9457. Note that the Value object passed as a parameter may not be exactly the same
  9458. object that you registered the listener with - it might be a copy that refers
  9459. to the same underlying ValueSource. To find out, you can call Value::refersToSameSourceAs().
  9460. */
  9461. virtual void valueChanged (Value& value) = 0;
  9462. };
  9463. /** Adds a listener to receive callbacks when the value changes.
  9464. The listener is added to this specific Value object, and not to the shared
  9465. object that it refers to. When this object is deleted, all the listeners will
  9466. be lost, even if other references to the same Value still exist. So when you're
  9467. adding a listener, make sure that you add it to a ValueTree instance that will last
  9468. for as long as you need the listener. In general, you'd never want to add a listener
  9469. to a local stack-based ValueTree, but more likely to one that's a member variable.
  9470. @see removeListener
  9471. */
  9472. void addListener (Listener* listener);
  9473. /** Removes a listener that was previously added with addListener(). */
  9474. void removeListener (Listener* listener);
  9475. /**
  9476. Used internally by the Value class as the base class for its shared value objects.
  9477. The Value class is essentially a reference-counted pointer to a shared instance
  9478. of a ValueSource object. If you're feeling adventurous, you can create your own custom
  9479. ValueSource classes to allow Value objects to represent your own custom data items.
  9480. */
  9481. class JUCE_API ValueSource : public ReferenceCountedObject,
  9482. public AsyncUpdater
  9483. {
  9484. public:
  9485. ValueSource();
  9486. virtual ~ValueSource();
  9487. /** Returns the current value of this object. */
  9488. virtual const var getValue() const = 0;
  9489. /** Changes the current value.
  9490. This must also trigger a change message if the value actually changes.
  9491. */
  9492. virtual void setValue (const var& newValue) = 0;
  9493. /** Delivers a change message to all the listeners that are registered with
  9494. this value.
  9495. If dispatchSynchronously is true, the method will call all the listeners
  9496. before returning; otherwise it'll dispatch a message and make the call later.
  9497. */
  9498. void sendChangeMessage (bool dispatchSynchronously);
  9499. juce_UseDebuggingNewOperator
  9500. protected:
  9501. friend class Value;
  9502. SortedSet <Value*> valuesWithListeners;
  9503. void handleAsyncUpdate();
  9504. ValueSource (const ValueSource&);
  9505. ValueSource& operator= (const ValueSource&);
  9506. };
  9507. /** Creates a Value object that uses this valueSource object as its underlying data. */
  9508. explicit Value (ValueSource* valueSource);
  9509. /** Returns the ValueSource that this value is referring to. */
  9510. ValueSource& getValueSource() throw() { return *value; }
  9511. juce_UseDebuggingNewOperator
  9512. private:
  9513. friend class ValueSource;
  9514. ReferenceCountedObjectPtr <ValueSource> value;
  9515. ListenerList <Listener> listeners;
  9516. void callListeners();
  9517. // This is disallowed to avoid confusion about whether it should
  9518. // do a by-value or by-reference copy.
  9519. Value& operator= (const Value& other);
  9520. };
  9521. /** Writes a Value to an OutputStream as a UTF8 string. */
  9522. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value);
  9523. #endif // __JUCE_VALUE_JUCEHEADER__
  9524. /*** End of inlined file: juce_Value.h ***/
  9525. #endif
  9526. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  9527. /*** Start of inlined file: juce_ValueTree.h ***/
  9528. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  9529. #define __JUCE_VALUETREE_JUCEHEADER__
  9530. /*** Start of inlined file: juce_UndoManager.h ***/
  9531. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  9532. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  9533. /*** Start of inlined file: juce_ChangeBroadcaster.h ***/
  9534. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9535. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9536. /*** Start of inlined file: juce_ChangeListenerList.h ***/
  9537. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9538. #define __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9539. /*** Start of inlined file: juce_ChangeListener.h ***/
  9540. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  9541. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  9542. /**
  9543. Receives callbacks about changes to some kind of object.
  9544. Many objects use a ChangeListenerList to keep a set of listeners which they
  9545. will inform when something changes. A subclass of ChangeListener
  9546. is used to receive these callbacks.
  9547. Note that the major difference between an ActionListener and a ChangeListener
  9548. is that for a ChangeListener, multiple changes will be coalesced into fewer
  9549. callbacks, but ActionListeners perform one callback for every event posted.
  9550. @see ChangeListenerList, ChangeBroadcaster, ActionListener
  9551. */
  9552. class JUCE_API ChangeListener
  9553. {
  9554. public:
  9555. /** Destructor. */
  9556. virtual ~ChangeListener() {}
  9557. /** Overridden by your subclass to receive the callback.
  9558. @param objectThatHasChanged the value that was passed to the
  9559. ChangeListenerList::sendChangeMessage() method
  9560. */
  9561. virtual void changeListenerCallback (void* objectThatHasChanged) = 0;
  9562. };
  9563. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  9564. /*** End of inlined file: juce_ChangeListener.h ***/
  9565. /*** Start of inlined file: juce_ScopedLock.h ***/
  9566. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  9567. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  9568. /**
  9569. Automatically locks and unlocks a CriticalSection object.
  9570. Use one of these as a local variable to control access to a CriticalSection.
  9571. e.g. @code
  9572. CriticalSection myCriticalSection;
  9573. for (;;)
  9574. {
  9575. const ScopedLock myScopedLock (myCriticalSection);
  9576. // myCriticalSection is now locked
  9577. ...do some stuff...
  9578. // myCriticalSection gets unlocked here.
  9579. }
  9580. @endcode
  9581. @see CriticalSection, ScopedUnlock
  9582. */
  9583. class JUCE_API ScopedLock
  9584. {
  9585. public:
  9586. /** Creates a ScopedLock.
  9587. As soon as it is created, this will lock the CriticalSection, and
  9588. when the ScopedLock object is deleted, the CriticalSection will
  9589. be unlocked.
  9590. Make sure this object is created and deleted by the same thread,
  9591. otherwise there are no guarantees what will happen! Best just to use it
  9592. as a local stack object, rather than creating one with the new() operator.
  9593. */
  9594. inline explicit ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  9595. /** Destructor.
  9596. The CriticalSection will be unlocked when the destructor is called.
  9597. Make sure this object is created and deleted by the same thread,
  9598. otherwise there are no guarantees what will happen!
  9599. */
  9600. inline ~ScopedLock() throw() { lock_.exit(); }
  9601. private:
  9602. const CriticalSection& lock_;
  9603. ScopedLock (const ScopedLock&);
  9604. ScopedLock& operator= (const ScopedLock&);
  9605. };
  9606. /**
  9607. Automatically unlocks and re-locks a CriticalSection object.
  9608. This is the reverse of a ScopedLock object - instead of locking the critical
  9609. section for the lifetime of this object, it unlocks it.
  9610. Make sure you don't try to unlock critical sections that aren't actually locked!
  9611. e.g. @code
  9612. CriticalSection myCriticalSection;
  9613. for (;;)
  9614. {
  9615. const ScopedLock myScopedLock (myCriticalSection);
  9616. // myCriticalSection is now locked
  9617. ... do some stuff with it locked ..
  9618. while (xyz)
  9619. {
  9620. ... do some stuff with it locked ..
  9621. const ScopedUnlock unlocker (myCriticalSection);
  9622. // myCriticalSection is now unlocked for the remainder of this block,
  9623. // and re-locked at the end.
  9624. ...do some stuff with it unlocked ...
  9625. }
  9626. // myCriticalSection gets unlocked here.
  9627. }
  9628. @endcode
  9629. @see CriticalSection, ScopedLock
  9630. */
  9631. class ScopedUnlock
  9632. {
  9633. public:
  9634. /** Creates a ScopedUnlock.
  9635. As soon as it is created, this will unlock the CriticalSection, and
  9636. when the ScopedLock object is deleted, the CriticalSection will
  9637. be re-locked.
  9638. Make sure this object is created and deleted by the same thread,
  9639. otherwise there are no guarantees what will happen! Best just to use it
  9640. as a local stack object, rather than creating one with the new() operator.
  9641. */
  9642. inline explicit ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  9643. /** Destructor.
  9644. The CriticalSection will be unlocked when the destructor is called.
  9645. Make sure this object is created and deleted by the same thread,
  9646. otherwise there are no guarantees what will happen!
  9647. */
  9648. inline ~ScopedUnlock() throw() { lock_.enter(); }
  9649. private:
  9650. const CriticalSection& lock_;
  9651. ScopedUnlock (const ScopedLock&);
  9652. ScopedUnlock& operator= (const ScopedUnlock&);
  9653. };
  9654. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  9655. /*** End of inlined file: juce_ScopedLock.h ***/
  9656. /**
  9657. A set of ChangeListeners.
  9658. Listeners can be added and removed from the list, and change messages can be
  9659. broadcast to all the listeners.
  9660. @see ChangeListener, ChangeBroadcaster
  9661. */
  9662. class JUCE_API ChangeListenerList : public MessageListener
  9663. {
  9664. public:
  9665. /** Creates an empty list. */
  9666. ChangeListenerList() throw();
  9667. /** Destructor. */
  9668. ~ChangeListenerList() throw();
  9669. /** Adds a listener to the list.
  9670. (Trying to add a listener that's already on the list will have no effect).
  9671. */
  9672. void addChangeListener (ChangeListener* listener) throw();
  9673. /** Removes a listener from the list.
  9674. If the listener isn't on the list, this won't have any effect.
  9675. */
  9676. void removeChangeListener (ChangeListener* listener) throw();
  9677. /** Removes all listeners from the list. */
  9678. void removeAllChangeListeners() throw();
  9679. /** Posts an asynchronous change message to all the listeners.
  9680. If a message has already been sent and hasn't yet been delivered, this
  9681. method won't send another - in this way it coalesces multiple frequent
  9682. changes into fewer actual callbacks to the ChangeListeners. Contrast this
  9683. with the ActionListener, which posts a new event for every call to its
  9684. sendActionMessage() method.
  9685. Only listeners which are on the list when the change event is delivered
  9686. will receive the event - and this may include listeners that weren't on
  9687. the list when the change message was sent.
  9688. @param objectThatHasChanged this pointer is passed to the
  9689. ChangeListener::changeListenerCallback() method,
  9690. and can be any value the application needs
  9691. @see sendSynchronousChangeMessage
  9692. */
  9693. void sendChangeMessage (void* objectThatHasChanged) throw();
  9694. /** This will synchronously callback all the ChangeListeners.
  9695. Use this if you need to synchronously force a call to all the
  9696. listeners' ChangeListener::changeListenerCallback() methods.
  9697. */
  9698. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  9699. /** If a change message has been sent but not yet dispatched, this will
  9700. use sendSynchronousChangeMessage() to make the callback immediately.
  9701. */
  9702. void dispatchPendingMessages();
  9703. /** @internal */
  9704. void handleMessage (const Message&);
  9705. juce_UseDebuggingNewOperator
  9706. private:
  9707. SortedSet <void*> listeners;
  9708. CriticalSection lock;
  9709. void* lastChangedObject;
  9710. bool messagePending;
  9711. ChangeListenerList (const ChangeListenerList&);
  9712. ChangeListenerList& operator= (const ChangeListenerList&);
  9713. };
  9714. #endif // __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9715. /*** End of inlined file: juce_ChangeListenerList.h ***/
  9716. /** Manages a list of ChangeListeners, and can send them messages.
  9717. To quickly add methods to your class that can add/remove change
  9718. listeners and broadcast to them, you can derive from this.
  9719. @see ChangeListenerList, ChangeListener
  9720. */
  9721. class JUCE_API ChangeBroadcaster
  9722. {
  9723. public:
  9724. /** Creates an ChangeBroadcaster. */
  9725. ChangeBroadcaster() throw();
  9726. /** Destructor. */
  9727. virtual ~ChangeBroadcaster();
  9728. /** Adds a listener to the list.
  9729. (Trying to add a listener that's already on the list will have no effect).
  9730. */
  9731. void addChangeListener (ChangeListener* listener) throw();
  9732. /** Removes a listener from the list.
  9733. If the listener isn't on the list, this won't have any effect.
  9734. */
  9735. void removeChangeListener (ChangeListener* listener) throw();
  9736. /** Removes all listeners from the list. */
  9737. void removeAllChangeListeners() throw();
  9738. /** Broadcasts a change message to all the registered listeners.
  9739. The message will be delivered asynchronously by the event thread, so this
  9740. method will not directly call any of the listeners. For a synchronous
  9741. message, use sendSynchronousChangeMessage().
  9742. @see ChangeListenerList::sendActionMessage
  9743. */
  9744. void sendChangeMessage (void* objectThatHasChanged) throw();
  9745. /** Sends a synchronous change message to all the registered listeners.
  9746. @see ChangeListenerList::sendSynchronousChangeMessage
  9747. */
  9748. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  9749. /** If a change message has been sent but not yet dispatched, this will
  9750. use sendSynchronousChangeMessage() to make the callback immediately.
  9751. */
  9752. void dispatchPendingMessages();
  9753. private:
  9754. ChangeListenerList changeListenerList;
  9755. ChangeBroadcaster (const ChangeBroadcaster&);
  9756. ChangeBroadcaster& operator= (const ChangeBroadcaster&);
  9757. };
  9758. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9759. /*** End of inlined file: juce_ChangeBroadcaster.h ***/
  9760. /*** Start of inlined file: juce_UndoableAction.h ***/
  9761. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  9762. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  9763. /**
  9764. Used by the UndoManager class to store an action which can be done
  9765. and undone.
  9766. @see UndoManager
  9767. */
  9768. class JUCE_API UndoableAction
  9769. {
  9770. protected:
  9771. /** Creates an action. */
  9772. UndoableAction() throw() {}
  9773. public:
  9774. /** Destructor. */
  9775. virtual ~UndoableAction() {}
  9776. /** Overridden by a subclass to perform the action.
  9777. This method is called by the UndoManager, and shouldn't be used directly by
  9778. applications.
  9779. Be careful not to make any calls in a perform() method that could call
  9780. recursively back into the UndoManager::perform() method
  9781. @returns true if the action could be performed.
  9782. @see UndoManager::perform
  9783. */
  9784. virtual bool perform() = 0;
  9785. /** Overridden by a subclass to undo the action.
  9786. This method is called by the UndoManager, and shouldn't be used directly by
  9787. applications.
  9788. Be careful not to make any calls in an undo() method that could call
  9789. recursively back into the UndoManager::perform() method
  9790. @returns true if the action could be undone without any errors.
  9791. @see UndoManager::perform
  9792. */
  9793. virtual bool undo() = 0;
  9794. /** Returns a value to indicate how much memory this object takes up.
  9795. Because the UndoManager keeps a list of UndoableActions, this is used
  9796. to work out how much space each one will take up, so that the UndoManager
  9797. can work out how many to keep.
  9798. The default value returned here is 10 - units are arbitrary and
  9799. don't have to be accurate.
  9800. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  9801. UndoManager::setMaxNumberOfStoredUnits
  9802. */
  9803. virtual int getSizeInUnits() { return 10; }
  9804. /** Allows multiple actions to be coalesced into a single action object, to reduce storage space.
  9805. If possible, this method should create and return a single action that does the same job as
  9806. this one followed by the supplied action.
  9807. If it's not possible to merge the two actions, the method should return zero.
  9808. */
  9809. virtual UndoableAction* createCoalescedAction (UndoableAction* nextAction) { (void) nextAction; return 0; }
  9810. };
  9811. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  9812. /*** End of inlined file: juce_UndoableAction.h ***/
  9813. /**
  9814. Manages a list of undo/redo commands.
  9815. An UndoManager object keeps a list of past actions and can use these actions
  9816. to move backwards and forwards through an undo history.
  9817. To use it, create subclasses of UndoableAction which perform all the
  9818. actions you need, then when you need to actually perform an action, create one
  9819. and pass it to the UndoManager's perform() method.
  9820. The manager also uses the concept of 'transactions' to group the actions
  9821. together - all actions performed between calls to beginNewTransaction() are
  9822. grouped together and are all undone/redone as a group.
  9823. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  9824. when actions are performed or undone.
  9825. @see UndoableAction
  9826. */
  9827. class JUCE_API UndoManager : public ChangeBroadcaster
  9828. {
  9829. public:
  9830. /** Creates an UndoManager.
  9831. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  9832. to indicate how much storage it takes up
  9833. (UndoableAction::getSizeInUnits()), so this
  9834. lets you specify the maximum total number of
  9835. units that the undomanager is allowed to
  9836. keep in memory before letting the older actions
  9837. drop off the end of the list.
  9838. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  9839. that will be kept, even if this involves exceeding
  9840. the amount of space specified in maxNumberOfUnitsToKeep
  9841. */
  9842. UndoManager (int maxNumberOfUnitsToKeep = 30000,
  9843. int minimumTransactionsToKeep = 30);
  9844. /** Destructor. */
  9845. ~UndoManager();
  9846. /** Deletes all stored actions in the list. */
  9847. void clearUndoHistory();
  9848. /** Returns the current amount of space to use for storing UndoableAction objects.
  9849. @see setMaxNumberOfStoredUnits
  9850. */
  9851. int getNumberOfUnitsTakenUpByStoredCommands() const;
  9852. /** Sets the amount of space that can be used for storing UndoableAction objects.
  9853. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  9854. to indicate how much storage it takes up
  9855. (UndoableAction::getSizeInUnits()), so this
  9856. lets you specify the maximum total number of
  9857. units that the undomanager is allowed to
  9858. keep in memory before letting the older actions
  9859. drop off the end of the list.
  9860. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  9861. that will be kept, even if this involves exceeding
  9862. the amount of space specified in maxNumberOfUnitsToKeep
  9863. @see getNumberOfUnitsTakenUpByStoredCommands
  9864. */
  9865. void setMaxNumberOfStoredUnits (int maxNumberOfUnitsToKeep,
  9866. int minimumTransactionsToKeep);
  9867. /** Performs an action and adds it to the undo history list.
  9868. @param action the action to perform - this will be deleted by the UndoManager
  9869. when no longer needed
  9870. @param actionName if this string is non-empty, the current transaction will be
  9871. given this name; if it's empty, the current transaction name will
  9872. be left unchanged. See setCurrentTransactionName()
  9873. @returns true if the command succeeds - see UndoableAction::perform
  9874. @see beginNewTransaction
  9875. */
  9876. bool perform (UndoableAction* action,
  9877. const String& actionName = String::empty);
  9878. /** Starts a new group of actions that together will be treated as a single transaction.
  9879. All actions that are passed to the perform() method between calls to this
  9880. method are grouped together and undone/redone together by a single call to
  9881. undo() or redo().
  9882. @param actionName a description of the transaction that is about to be
  9883. performed
  9884. */
  9885. void beginNewTransaction (const String& actionName = String::empty);
  9886. /** Changes the name stored for the current transaction.
  9887. Each transaction is given a name when the beginNewTransaction() method is
  9888. called, but this can be used to change that name without starting a new
  9889. transaction.
  9890. */
  9891. void setCurrentTransactionName (const String& newName);
  9892. /** Returns true if there's at least one action in the list to undo.
  9893. @see getUndoDescription, undo, canRedo
  9894. */
  9895. bool canUndo() const;
  9896. /** Returns the description of the transaction that would be next to get undone.
  9897. The description returned is the one that was passed into beginNewTransaction
  9898. before the set of actions was performed.
  9899. @see undo
  9900. */
  9901. const String getUndoDescription() const;
  9902. /** Tries to roll-back the last transaction.
  9903. @returns true if the transaction can be undone, and false if it fails, or
  9904. if there aren't any transactions to undo
  9905. */
  9906. bool undo();
  9907. /** Tries to roll-back any actions that were added to the current transaction.
  9908. This will perform an undo() only if there are some actions in the undo list
  9909. that were added after the last call to beginNewTransaction().
  9910. This is useful because it lets you call beginNewTransaction(), then
  9911. perform an operation which may or may not actually perform some actions, and
  9912. then call this method to get rid of any actions that might have been done
  9913. without it rolling back the previous transaction if nothing was actually
  9914. done.
  9915. @returns true if any actions were undone.
  9916. */
  9917. bool undoCurrentTransactionOnly();
  9918. /** Returns a list of the UndoableAction objects that have been performed during the
  9919. transaction that is currently open.
  9920. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  9921. were to be called now.
  9922. The first item in the list is the earliest action performed.
  9923. */
  9924. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  9925. /** Returns the number of UndoableAction objects that have been performed during the
  9926. transaction that is currently open.
  9927. @see getActionsInCurrentTransaction
  9928. */
  9929. int getNumActionsInCurrentTransaction() const;
  9930. /** Returns true if there's at least one action in the list to redo.
  9931. @see getRedoDescription, redo, canUndo
  9932. */
  9933. bool canRedo() const;
  9934. /** Returns the description of the transaction that would be next to get redone.
  9935. The description returned is the one that was passed into beginNewTransaction
  9936. before the set of actions was performed.
  9937. @see redo
  9938. */
  9939. const String getRedoDescription() const;
  9940. /** Tries to redo the last transaction that was undone.
  9941. @returns true if the transaction can be redone, and false if it fails, or
  9942. if there aren't any transactions to redo
  9943. */
  9944. bool redo();
  9945. juce_UseDebuggingNewOperator
  9946. private:
  9947. OwnedArray <OwnedArray <UndoableAction> > transactions;
  9948. StringArray transactionNames;
  9949. String currentTransactionName;
  9950. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  9951. bool newTransaction, reentrancyCheck;
  9952. // disallow copy constructor
  9953. UndoManager (const UndoManager&);
  9954. UndoManager& operator= (const UndoManager&);
  9955. };
  9956. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  9957. /*** End of inlined file: juce_UndoManager.h ***/
  9958. /**
  9959. A powerful tree structure that can be used to hold free-form data, and which can
  9960. handle its own undo and redo behaviour.
  9961. A ValueTree contains a list of named properties as var objects, and also holds
  9962. any number of sub-trees.
  9963. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  9964. they're simply a lightweight reference to a shared data container. Creating a copy
  9965. of another ValueTree simply creates a new reference to the same underlying object - to
  9966. make a separate, deep copy of a tree you should explicitly call createCopy().
  9967. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  9968. and much of the structure of a ValueTree is similar to an XmlElement tree.
  9969. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  9970. contain text elements, the conversion works well and makes a good serialisation
  9971. format. They can also be serialised to a binary format, which is very fast and compact.
  9972. All the methods that change data take an optional UndoManager, which will be used
  9973. to track any changes to the object. For this to work, you have to be careful to
  9974. consistently always use the same UndoManager for all operations to any node inside
  9975. the tree.
  9976. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  9977. one tree to another, be careful to always remove it first, before adding it. This
  9978. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  9979. assertions if you try to do anything dangerous, but there are still plenty of ways it
  9980. could go wrong.
  9981. Listeners can be added to a ValueTree to be told when properies change and when
  9982. nodes are added or removed.
  9983. @see var, XmlElement
  9984. */
  9985. class JUCE_API ValueTree
  9986. {
  9987. public:
  9988. /** Creates an empty, invalid ValueTree.
  9989. A ValueTree that is created with this constructor can't actually be used for anything,
  9990. it's just a default 'null' ValueTree that can be returned to indicate some sort of failure.
  9991. To create a real one, use the constructor that takes a string.
  9992. @see ValueTree::invalid
  9993. */
  9994. ValueTree() throw();
  9995. /** Creates an empty ValueTree with the given type name.
  9996. Like an XmlElement, each ValueTree node has a type, which you can access with
  9997. getType() and hasType().
  9998. */
  9999. explicit ValueTree (const Identifier& type);
  10000. /** Creates a reference to another ValueTree. */
  10001. ValueTree (const ValueTree& other);
  10002. /** Makes this object reference another node. */
  10003. ValueTree& operator= (const ValueTree& other);
  10004. /** Destructor. */
  10005. ~ValueTree();
  10006. /** Returns true if both this and the other tree node refer to the same underlying structure.
  10007. Note that this isn't a value comparison - two independently-created trees which
  10008. contain identical data are not considered equal.
  10009. */
  10010. bool operator== (const ValueTree& other) const throw();
  10011. /** Returns true if this and the other node refer to different underlying structures.
  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. /** Performs a deep comparison between the properties and children of two trees.
  10017. If all the properties and children of the two trees are the same (recursively), this
  10018. returns true.
  10019. The normal operator==() only checks whether two trees refer to the same shared data
  10020. structure, so use this method if you need to do a proper value comparison.
  10021. */
  10022. bool isEquivalentTo (const ValueTree& other) const;
  10023. /** Returns true if this node refers to some valid data.
  10024. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  10025. call to getChild().
  10026. */
  10027. bool isValid() const { return object != 0; }
  10028. /** Returns a deep copy of this tree and all its sub-nodes. */
  10029. ValueTree createCopy() const;
  10030. /** Returns the type of this node.
  10031. The type is specified when the ValueTree is created.
  10032. @see hasType
  10033. */
  10034. const Identifier getType() const;
  10035. /** Returns true if the node has this type.
  10036. The comparison is case-sensitive.
  10037. */
  10038. bool hasType (const Identifier& typeName) const;
  10039. /** Returns the value of a named property.
  10040. If no such property has been set, this will return a void variant.
  10041. You can also use operator[] to get a property.
  10042. @see var, setProperty, hasProperty
  10043. */
  10044. const var& getProperty (const Identifier& name) const;
  10045. /** Returns the value of a named property, or a user-specified default if the property doesn't exist.
  10046. If no such property has been set, this will return the value of defaultReturnValue.
  10047. You can also use operator[] and getProperty to get a property.
  10048. @see var, getProperty, setProperty, hasProperty
  10049. */
  10050. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  10051. /** Returns the value of a named property.
  10052. If no such property has been set, this will return a void variant. This is the same as
  10053. calling getProperty().
  10054. @see getProperty
  10055. */
  10056. const var& operator[] (const Identifier& name) const;
  10057. /** Changes a named property of the node.
  10058. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10059. so that this change can be undone.
  10060. @see var, getProperty, removeProperty
  10061. */
  10062. void setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager);
  10063. /** Returns true if the node contains a named property. */
  10064. bool hasProperty (const Identifier& name) const;
  10065. /** Removes a property from the node.
  10066. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10067. so that this change can be undone.
  10068. */
  10069. void removeProperty (const Identifier& name, UndoManager* undoManager);
  10070. /** Removes all properties 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 removeAllProperties (UndoManager* undoManager);
  10075. /** Returns the total number of properties that the node contains.
  10076. @see getProperty.
  10077. */
  10078. int getNumProperties() const;
  10079. /** Returns the identifier of the property with a given index.
  10080. @see getNumProperties
  10081. */
  10082. const Identifier getPropertyName (int index) const;
  10083. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  10084. The Value object will maintain a reference to this tree, and will use the undo manager when
  10085. it needs to change the value. Attaching a Value::Listener to the value object will provide
  10086. callbacks whenever the property changes.
  10087. */
  10088. Value getPropertyAsValue (const Identifier& name, UndoManager* undoManager) const;
  10089. /** Returns the number of child nodes belonging to this one.
  10090. @see getChild
  10091. */
  10092. int getNumChildren() const;
  10093. /** Returns one of this node's child nodes.
  10094. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  10095. whether a node is valid).
  10096. */
  10097. ValueTree getChild (int index) const;
  10098. /** Returns the first child node with the speficied type name.
  10099. If no such node is found, it'll return an invalid node. (See isValid() to find out
  10100. whether a node is valid).
  10101. @see getOrCreateChildWithName
  10102. */
  10103. ValueTree getChildWithName (const Identifier& type) const;
  10104. /** Returns the first child node with the speficied type name, creating and adding
  10105. a child with this name if there wasn't already one there.
  10106. The only time this will return an invalid object is when the object that you're calling
  10107. the method on is itself invalid.
  10108. @see getChildWithName
  10109. */
  10110. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  10111. /** Looks for the first child node that has the speficied property value.
  10112. This will scan the child nodes in order, until it finds one that has property that matches
  10113. the specified value.
  10114. If no such node is found, it'll return an invalid node. (See isValid() to find out
  10115. whether a node is valid).
  10116. */
  10117. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  10118. /** Adds a child to this node.
  10119. Make sure that the child is removed from any former parent node before calling this, or
  10120. you'll hit an assertion.
  10121. If the index is < 0 or greater than the current number of child nodes, the new node will
  10122. be added at the end of the list.
  10123. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10124. so that this change can be undone.
  10125. */
  10126. void addChild (const ValueTree& child, int index, UndoManager* undoManager);
  10127. /** Removes the specified child from this node's child-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 removeChild (const ValueTree& child, UndoManager* undoManager);
  10132. /** Removes a 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 (int childIndex, UndoManager* undoManager);
  10137. /** Removes all child-nodes from this node.
  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 removeAllChildren (UndoManager* undoManager);
  10142. /** Moves one of the children to a different index.
  10143. This will move the child to a specified index, shuffling along any intervening
  10144. items as required. So for example, if you have a list of { 0, 1, 2, 3, 4, 5 }, then
  10145. calling move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  10146. @param currentIndex the index of the item to be moved. If this isn't a
  10147. valid index, then nothing will be done
  10148. @param newIndex the index at which you'd like this item to end up. If this
  10149. is less than zero, the value will be moved to the end
  10150. of the list
  10151. @param undoManager the optional UndoManager to use to store this transaction
  10152. */
  10153. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager);
  10154. /** Returns true if this node is anywhere below the specified parent node.
  10155. This returns true if the node is a child-of-a-child, as well as a direct child.
  10156. */
  10157. bool isAChildOf (const ValueTree& possibleParent) const;
  10158. /** Returns the index of a child item in this parent.
  10159. If the child isn't found, this returns -1.
  10160. */
  10161. int indexOf (const ValueTree& child) const;
  10162. /** Returns the parent node that contains this one.
  10163. If the node has no parent, this will return an invalid node. (See isValid() to find out
  10164. whether a node is valid).
  10165. */
  10166. ValueTree getParent() const;
  10167. /** Creates an XmlElement that holds a complete image of this node and all its children.
  10168. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  10169. be used to recreate a similar node by calling fromXml()
  10170. @see fromXml
  10171. */
  10172. XmlElement* createXml() const;
  10173. /** Tries to recreate a node from its XML representation.
  10174. This isn't designed to cope with random XML data - for a sensible result, it should only
  10175. be fed XML that was created by the createXml() method.
  10176. */
  10177. static ValueTree fromXml (const XmlElement& xml);
  10178. /** Stores this tree (and all its children) in a binary format.
  10179. Once written, the data can be read back with readFromStream().
  10180. It's much faster to load/save your tree in binary form than as XML, but
  10181. obviously isn't human-readable.
  10182. */
  10183. void writeToStream (OutputStream& output);
  10184. /** Reloads a tree from a stream that was written with writeToStream(). */
  10185. static ValueTree readFromStream (InputStream& input);
  10186. /** Reloads a tree from a data block that was written with writeToStream(). */
  10187. static ValueTree readFromData (const void* data, size_t numBytes);
  10188. /** Listener class for events that happen to a ValueTree.
  10189. To get events from a ValueTree, make your class implement this interface, and use
  10190. ValueTree::addListener() and ValueTree::removeListener() to register it.
  10191. */
  10192. class JUCE_API Listener
  10193. {
  10194. public:
  10195. /** Destructor. */
  10196. virtual ~Listener() {}
  10197. /** This method is called when a property of this node (or of one of its sub-nodes) has
  10198. changed.
  10199. The tree parameter indicates which tree has had its property changed, and the property
  10200. parameter indicates the property.
  10201. Note that when you register a listener to a tree, it will receive this callback for
  10202. property changes in that tree, and also for any of its children, (recursively, at any depth).
  10203. If your tree has sub-trees but you only want to know about changes to the top level tree,
  10204. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  10205. */
  10206. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  10207. const Identifier& property) = 0;
  10208. /** This method is called when a child sub-tree is added or removed.
  10209. The tree parameter indicates the tree whose child was added or removed.
  10210. Note that when you register a listener to a tree, it will receive this callback for
  10211. child changes in that tree, and also in any of its children, (recursively, at any depth).
  10212. If your tree has sub-trees but you only want to know about changes to the top level tree,
  10213. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  10214. */
  10215. virtual void valueTreeChildrenChanged (ValueTree& treeWhoseChildHasChanged) = 0;
  10216. /** This method is called when a tree has been added or removed from a parent node.
  10217. This callback happens when the tree to which the listener was registered is added or
  10218. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  10219. the listener is registered, and not to any of its children.
  10220. */
  10221. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  10222. };
  10223. /** Adds a listener to receive callbacks when this node is changed.
  10224. The listener is added to this specific ValueTree object, and not to the shared
  10225. object that it refers to. When this object is deleted, all the listeners will
  10226. be lost, even if other references to the same ValueTree still exist. And if you
  10227. use the operator= to make this refer to a different ValueTree, any listeners will
  10228. begin listening to changes to the new tree instead of the old one.
  10229. When you're adding a listener, make sure that you add it to a ValueTree instance that
  10230. will last for as long as you need the listener. In general, you'd never want to add a
  10231. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  10232. @see removeListener
  10233. */
  10234. void addListener (Listener* listener);
  10235. /** Removes a listener that was previously added with addListener(). */
  10236. void removeListener (Listener* listener);
  10237. /** This method uses a comparator object to sort the tree's children into order.
  10238. The object provided must have a method of the form:
  10239. @code
  10240. int compareElements (const ValueTree& first, const ValueTree& second);
  10241. @endcode
  10242. ..and this method must return:
  10243. - a value of < 0 if the first comes before the second
  10244. - a value of 0 if the two objects are equivalent
  10245. - a value of > 0 if the second comes before the first
  10246. To improve performance, the compareElements() method can be declared as static or const.
  10247. @param comparator the comparator to use for comparing elements.
  10248. @param retainOrderOfEquivalentItems if this is true, then items
  10249. which the comparator says are equivalent will be
  10250. kept in the order in which they currently appear
  10251. in the array. This is slower to perform, but may
  10252. be important in some cases. If it's false, a faster
  10253. algorithm is used, but equivalent elements may be
  10254. rearranged.
  10255. */
  10256. template <typename ElementComparator>
  10257. void sort (ElementComparator& comparator, const bool retainOrderOfEquivalentItems = false)
  10258. {
  10259. if (object != 0)
  10260. {
  10261. ComparatorAdapter <ElementComparator> adapter (comparator);
  10262. object->children.sort (adapter, retainOrderOfEquivalentItems);
  10263. object->sendChildChangeMessage();
  10264. }
  10265. }
  10266. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  10267. This invalid object is equivalent to ValueTree created with its default constructor.
  10268. */
  10269. static const ValueTree invalid;
  10270. juce_UseDebuggingNewOperator
  10271. private:
  10272. class SetPropertyAction;
  10273. friend class SetPropertyAction;
  10274. class AddOrRemoveChildAction;
  10275. friend class AddOrRemoveChildAction;
  10276. class MoveChildAction;
  10277. friend class MoveChildAction;
  10278. class JUCE_API SharedObject : public ReferenceCountedObject
  10279. {
  10280. public:
  10281. explicit SharedObject (const Identifier& type);
  10282. SharedObject (const SharedObject& other);
  10283. ~SharedObject();
  10284. const Identifier type;
  10285. NamedValueSet properties;
  10286. ReferenceCountedArray <SharedObject> children;
  10287. SortedSet <ValueTree*> valueTreesWithListeners;
  10288. SharedObject* parent;
  10289. void sendPropertyChangeMessage (const Identifier& property);
  10290. void sendPropertyChangeMessage (ValueTree& tree, const Identifier& property);
  10291. void sendChildChangeMessage();
  10292. void sendChildChangeMessage (ValueTree& tree);
  10293. void sendParentChangeMessage();
  10294. const var& getProperty (const Identifier& name) const;
  10295. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  10296. void setProperty (const Identifier& name, const var& newValue, UndoManager*);
  10297. bool hasProperty (const Identifier& name) const;
  10298. void removeProperty (const Identifier& name, UndoManager*);
  10299. void removeAllProperties (UndoManager*);
  10300. bool isAChildOf (const SharedObject* possibleParent) const;
  10301. int indexOf (const ValueTree& child) const;
  10302. ValueTree getChildWithName (const Identifier& type) const;
  10303. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  10304. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  10305. void addChild (SharedObject* child, int index, UndoManager*);
  10306. void removeChild (int childIndex, UndoManager*);
  10307. void removeAllChildren (UndoManager*);
  10308. void moveChild (int currentIndex, int newIndex, UndoManager*);
  10309. bool isEquivalentTo (const SharedObject& other) const;
  10310. XmlElement* createXml() const;
  10311. juce_UseDebuggingNewOperator
  10312. private:
  10313. SharedObject& operator= (const SharedObject&);
  10314. };
  10315. template <typename ElementComparator>
  10316. class ComparatorAdapter
  10317. {
  10318. public:
  10319. ComparatorAdapter (ElementComparator& comparator_) throw() : comparator (comparator_) {}
  10320. int compareElements (SharedObject* const first, SharedObject* const second)
  10321. {
  10322. return comparator.compareElements (ValueTree (first), ValueTree (second));
  10323. }
  10324. private:
  10325. ElementComparator& comparator;
  10326. ComparatorAdapter (const ComparatorAdapter&);
  10327. ComparatorAdapter& operator= (const ComparatorAdapter&);
  10328. };
  10329. friend class SharedObject;
  10330. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  10331. SharedObjectPtr object;
  10332. ListenerList <Listener> listeners;
  10333. #if JUCE_MSVC && ! DOXYGEN
  10334. public: // (workaround for VC6)
  10335. #endif
  10336. explicit ValueTree (SharedObject*);
  10337. };
  10338. #endif // __JUCE_VALUETREE_JUCEHEADER__
  10339. /*** End of inlined file: juce_ValueTree.h ***/
  10340. #endif
  10341. #ifndef __JUCE_VARIANT_JUCEHEADER__
  10342. #endif
  10343. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  10344. #endif
  10345. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  10346. #endif
  10347. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  10348. /*** Start of inlined file: juce_FileLogger.h ***/
  10349. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  10350. #define __JUCE_FILELOGGER_JUCEHEADER__
  10351. /**
  10352. A simple implemenation of a Logger that writes to a file.
  10353. @see Logger
  10354. */
  10355. class JUCE_API FileLogger : public Logger
  10356. {
  10357. public:
  10358. /** Creates a FileLogger for a given file.
  10359. @param fileToWriteTo the file that to use - new messages will be appended
  10360. to the file. If the file doesn't exist, it will be created,
  10361. along with any parent directories that are needed.
  10362. @param welcomeMessage when opened, the logger will write a header to the log, along
  10363. with the current date and time, and this welcome message
  10364. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  10365. but is larger than this number of bytes, then the start of the
  10366. file will be truncated to keep the size down. This prevents a log
  10367. file getting ridiculously large over time. The file will be truncated
  10368. at a new-line boundary. If this value is less than zero, no size limit
  10369. will be imposed; if it's zero, the file will always be deleted. Note that
  10370. the size is only checked once when this object is created - any logging
  10371. that is done later will be appended without any checking
  10372. */
  10373. FileLogger (const File& fileToWriteTo,
  10374. const String& welcomeMessage,
  10375. const int maxInitialFileSizeBytes = 128 * 1024);
  10376. /** Destructor. */
  10377. ~FileLogger();
  10378. void logMessage (const String& message);
  10379. const File getLogFile() const { return logFile; }
  10380. /** Helper function to create a log file in the correct place for this platform.
  10381. On Windows this will return a logger with a path such as:
  10382. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  10383. On the Mac it'll create something like:
  10384. ~/Library/Logs/[logFileName]
  10385. The method might return 0 if the file can't be created for some reason.
  10386. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  10387. it's best to use the something like the name of your application here.
  10388. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  10389. call it "log.txt" because if it goes in a directory with logs
  10390. from other applications (as it will do on the Mac) then no-one
  10391. will know which one is yours!
  10392. @param welcomeMessage a message that will be written to the log when it's opened.
  10393. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  10394. */
  10395. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  10396. const String& logFileName,
  10397. const String& welcomeMessage,
  10398. const int maxInitialFileSizeBytes = 128 * 1024);
  10399. juce_UseDebuggingNewOperator
  10400. private:
  10401. File logFile;
  10402. CriticalSection logLock;
  10403. ScopedPointer <FileOutputStream> logStream;
  10404. void trimFileSize (int maxFileSizeBytes) const;
  10405. FileLogger (const FileLogger&);
  10406. FileLogger& operator= (const FileLogger&);
  10407. };
  10408. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  10409. /*** End of inlined file: juce_FileLogger.h ***/
  10410. #endif
  10411. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  10412. /*** Start of inlined file: juce_Initialisation.h ***/
  10413. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  10414. #define __JUCE_INITIALISATION_JUCEHEADER__
  10415. /** Initialises Juce's GUI classes.
  10416. If you're embedding Juce into an application that uses its own event-loop rather
  10417. than using the START_JUCE_APPLICATION macro, call this function before making any
  10418. Juce calls, to make sure things are initialised correctly.
  10419. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  10420. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  10421. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  10422. */
  10423. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  10424. /** Clears up any static data being used by Juce's GUI classes.
  10425. If you're embedding Juce into an application that uses its own event-loop rather
  10426. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  10427. code to clean up any juce objects that might be lying around.
  10428. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  10429. */
  10430. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  10431. /** Initialises the core parts of Juce.
  10432. If you're embedding Juce into either a command-line program, call this function
  10433. at the start of your main() function to make sure that Juce is initialised correctly.
  10434. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  10435. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  10436. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  10437. */
  10438. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI();
  10439. /** Clears up any static data being used by Juce's non-gui core classes.
  10440. If you're embedding Juce into either a command-line program, call this function
  10441. at the end of your main() function if you want to make sure any Juce objects are
  10442. cleaned up correctly.
  10443. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  10444. */
  10445. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI();
  10446. /** A utility object that helps you initialise and shutdown Juce correctly
  10447. using an RAII pattern.
  10448. When an instance of this class is created, it calls initialiseJuce_NonGUI(),
  10449. and when it's deleted, it calls shutdownJuce_NonGUI(), which lets you easily
  10450. make sure that these functions are matched correctly.
  10451. This class is particularly handy to use at the beginning of a console app's
  10452. main() function, because it'll take care of shutting down whenever you return
  10453. from the main() call.
  10454. @see ScopedJuceInitialiser_GUI
  10455. */
  10456. class ScopedJuceInitialiser_NonGUI
  10457. {
  10458. public:
  10459. /** The constructor simply calls initialiseJuce_NonGUI(). */
  10460. ScopedJuceInitialiser_NonGUI() { initialiseJuce_NonGUI(); }
  10461. /** The destructor simply calls shutdownJuce_NonGUI(). */
  10462. ~ScopedJuceInitialiser_NonGUI() { shutdownJuce_NonGUI(); }
  10463. };
  10464. /** A utility object that helps you initialise and shutdown Juce correctly
  10465. using an RAII pattern.
  10466. When an instance of this class is created, it calls initialiseJuce_GUI(),
  10467. and when it's deleted, it calls shutdownJuce_GUI(), which lets you easily
  10468. make sure that these functions are matched correctly.
  10469. This class is particularly handy to use at the beginning of a console app's
  10470. main() function, because it'll take care of shutting down whenever you return
  10471. from the main() call.
  10472. @see ScopedJuceInitialiser_NonGUI
  10473. */
  10474. class ScopedJuceInitialiser_GUI
  10475. {
  10476. public:
  10477. /** The constructor simply calls initialiseJuce_GUI(). */
  10478. ScopedJuceInitialiser_GUI() { initialiseJuce_GUI(); }
  10479. /** The destructor simply calls shutdownJuce_GUI(). */
  10480. ~ScopedJuceInitialiser_GUI() { shutdownJuce_GUI(); }
  10481. };
  10482. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  10483. /*** End of inlined file: juce_Initialisation.h ***/
  10484. #endif
  10485. #ifndef __JUCE_LOGGER_JUCEHEADER__
  10486. #endif
  10487. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  10488. #endif
  10489. #ifndef __JUCE_MEMORY_JUCEHEADER__
  10490. #endif
  10491. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10492. /*** Start of inlined file: juce_PerformanceCounter.h ***/
  10493. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10494. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10495. /** A timer for measuring performance of code and dumping the results to a file.
  10496. e.g. @code
  10497. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  10498. for (;;)
  10499. {
  10500. pc.start();
  10501. doSomethingFishy();
  10502. pc.stop();
  10503. }
  10504. @endcode
  10505. In this example, the time of each period between calling start/stop will be
  10506. measured and averaged over 50 runs, and the results printed to a file
  10507. every 50 times round the loop.
  10508. */
  10509. class JUCE_API PerformanceCounter
  10510. {
  10511. public:
  10512. /** Creates a PerformanceCounter object.
  10513. @param counterName the name used when printing out the statistics
  10514. @param runsPerPrintout the number of start/stop iterations before calling
  10515. printStatistics()
  10516. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  10517. the results are just written to the debugger output
  10518. */
  10519. PerformanceCounter (const String& counterName,
  10520. int runsPerPrintout = 100,
  10521. const File& loggingFile = File::nonexistent);
  10522. /** Destructor. */
  10523. ~PerformanceCounter();
  10524. /** Starts timing.
  10525. @see stop
  10526. */
  10527. void start();
  10528. /** Stops timing and prints out the results.
  10529. The number of iterations before doing a printout of the
  10530. results is set in the constructor.
  10531. @see start
  10532. */
  10533. void stop();
  10534. /** Dumps the current metrics to the debugger output and to a file.
  10535. As well as using Logger::outputDebugString to print the results,
  10536. this will write then to the file specified in the constructor (if
  10537. this was valid).
  10538. */
  10539. void printStatistics();
  10540. juce_UseDebuggingNewOperator
  10541. private:
  10542. String name;
  10543. int numRuns, runsPerPrint;
  10544. double totalTime;
  10545. int64 started;
  10546. File outputFile;
  10547. };
  10548. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10549. /*** End of inlined file: juce_PerformanceCounter.h ***/
  10550. #endif
  10551. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  10552. #endif
  10553. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10554. /*** Start of inlined file: juce_PlatformUtilities.h ***/
  10555. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10556. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10557. /**
  10558. A collection of miscellaneous platform-specific utilities.
  10559. */
  10560. class JUCE_API PlatformUtilities
  10561. {
  10562. public:
  10563. /** Plays the operating system's default alert 'beep' sound. */
  10564. static void beep();
  10565. /** Tries to launch the system's default reader for a given file or URL. */
  10566. static bool openDocument (const String& documentURL, const String& parameters);
  10567. /** Tries to launch the system's default email app to let the user create an email.
  10568. */
  10569. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  10570. const String& emailSubject,
  10571. const String& bodyText,
  10572. const StringArray& filesToAttach);
  10573. #if JUCE_MAC || JUCE_IPHONE || DOXYGEN
  10574. /** MAC ONLY - Turns a Core CF String into a juce one. */
  10575. static const String cfStringToJuceString (CFStringRef cfString);
  10576. /** MAC ONLY - Turns a juce string into a Core CF one. */
  10577. static CFStringRef juceStringToCFString (const String& s);
  10578. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  10579. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  10580. /** MAC ONLY - Turns an FSRef into a juce string path. */
  10581. static const String makePathFromFSRef (FSRef* file);
  10582. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  10583. their precomposed equivalents.
  10584. */
  10585. static const String convertToPrecomposedUnicode (const String& s);
  10586. /** MAC ONLY - Gets the type of a file from the file's resources. */
  10587. static OSType getTypeOfFile (const String& filename);
  10588. /** MAC ONLY - Returns true if this file is actually a bundle. */
  10589. static bool isBundle (const String& filename);
  10590. /** MAC ONLY - Adds an item to the dock */
  10591. static void addItemToDock (const File& file);
  10592. /** MAC ONLY - Returns the current OS version number.
  10593. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  10594. */
  10595. static int getOSXMinorVersionNumber();
  10596. #endif
  10597. #if JUCE_WINDOWS || DOXYGEN
  10598. // Some registry helper functions:
  10599. /** WIN32 ONLY - Returns a string from the registry.
  10600. The path is a string for the entire path of a value in the registry,
  10601. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  10602. */
  10603. static const String getRegistryValue (const String& regValuePath,
  10604. const String& defaultValue = String::empty);
  10605. /** WIN32 ONLY - Sets a registry value as a string.
  10606. This will take care of creating any groups needed to get to the given
  10607. registry value.
  10608. */
  10609. static void setRegistryValue (const String& regValuePath,
  10610. const String& value);
  10611. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  10612. static bool registryValueExists (const String& regValuePath);
  10613. /** WIN32 ONLY - Deletes a registry value. */
  10614. static void deleteRegistryValue (const String& regValuePath);
  10615. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  10616. static void deleteRegistryKey (const String& regKeyPath);
  10617. /** WIN32 ONLY - Creates a file association in the registry.
  10618. This lets you set the exe that should be launched by a given file extension.
  10619. @param fileExtension the file extension to associate, including the
  10620. initial dot, e.g. ".txt"
  10621. @param symbolicDescription a space-free short token to identify the file type
  10622. @param fullDescription a human-readable description of the file type
  10623. @param targetExecutable the executable that should be launched
  10624. @param iconResourceNumber the icon that gets displayed for the file type will be
  10625. found by looking up this resource number in the
  10626. executable. Pass 0 here to not use an icon
  10627. */
  10628. static void registerFileAssociation (const String& fileExtension,
  10629. const String& symbolicDescription,
  10630. const String& fullDescription,
  10631. const File& targetExecutable,
  10632. int iconResourceNumber);
  10633. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  10634. In a normal Juce application this will be set to the module handle
  10635. of the application executable.
  10636. If you're writing a DLL using Juce and plan to use any Juce messaging or
  10637. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  10638. to set the correct module handle in your DllMain() function, because
  10639. the win32 system relies on the correct instance handle when opening windows.
  10640. */
  10641. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  10642. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  10643. @see getCurrentModuleInstanceHandle()
  10644. */
  10645. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  10646. /** WIN32 ONLY - Gets the command-line params as a string.
  10647. This is needed to avoid unicode problems with the argc type params.
  10648. */
  10649. static const String JUCE_CALLTYPE getCurrentCommandLineParams();
  10650. #endif
  10651. /** Clears the floating point unit's flags.
  10652. Only has an effect under win32, currently.
  10653. */
  10654. static void fpuReset();
  10655. #if JUCE_LINUX || JUCE_WINDOWS
  10656. /** Loads a dynamically-linked library into the process's address space.
  10657. @param pathOrFilename the platform-dependent name and search path
  10658. @returns a handle which can be used by getProcedureEntryPoint(), or
  10659. zero if it fails.
  10660. @see freeDynamicLibrary, getProcedureEntryPoint
  10661. */
  10662. static void* loadDynamicLibrary (const String& pathOrFilename);
  10663. /** Frees a dynamically-linked library.
  10664. @param libraryHandle a handle created by loadDynamicLibrary
  10665. @see loadDynamicLibrary, getProcedureEntryPoint
  10666. */
  10667. static void freeDynamicLibrary (void* libraryHandle);
  10668. /** Finds a procedure call in a dynamically-linked library.
  10669. @param libraryHandle a library handle returned by loadDynamicLibrary
  10670. @param procedureName the name of the procedure call to try to load
  10671. @returns a pointer to the function if found, or 0 if it fails
  10672. @see loadDynamicLibrary
  10673. */
  10674. static void* getProcedureEntryPoint (void* libraryHandle,
  10675. const String& procedureName);
  10676. #endif
  10677. #if JUCE_LINUX || DOXYGEN
  10678. #endif
  10679. private:
  10680. PlatformUtilities();
  10681. PlatformUtilities (const PlatformUtilities&);
  10682. PlatformUtilities& operator= (const PlatformUtilities&);
  10683. };
  10684. #if JUCE_MAC || JUCE_IPHONE
  10685. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  10686. using RAII.
  10687. */
  10688. class ScopedAutoReleasePool
  10689. {
  10690. public:
  10691. ScopedAutoReleasePool();
  10692. ~ScopedAutoReleasePool();
  10693. private:
  10694. void* pool;
  10695. ScopedAutoReleasePool (const ScopedAutoReleasePool&);
  10696. ScopedAutoReleasePool& operator= (const ScopedAutoReleasePool&);
  10697. };
  10698. #endif
  10699. #if JUCE_LINUX
  10700. /** A handy class that uses XLockDisplay and XUnlockDisplay to lock the X server
  10701. using an RAII approach.
  10702. */
  10703. class ScopedXLock
  10704. {
  10705. public:
  10706. /** Creating a ScopedXLock object locks the X display.
  10707. This uses XLockDisplay() to grab the display that Juce is using.
  10708. */
  10709. ScopedXLock();
  10710. /** Deleting a ScopedXLock object unlocks the X display.
  10711. This calls XUnlockDisplay() to release the lock.
  10712. */
  10713. ~ScopedXLock();
  10714. };
  10715. #endif
  10716. #if JUCE_MAC
  10717. /**
  10718. A wrapper class for picking up events from an Apple IR remote control device.
  10719. To use it, just create a subclass of this class, implementing the buttonPressed()
  10720. callback, then call start() and stop() to start or stop receiving events.
  10721. */
  10722. class JUCE_API AppleRemoteDevice
  10723. {
  10724. public:
  10725. AppleRemoteDevice();
  10726. virtual ~AppleRemoteDevice();
  10727. /** The set of buttons that may be pressed.
  10728. @see buttonPressed
  10729. */
  10730. enum ButtonType
  10731. {
  10732. menuButton = 0, /**< The menu button (if it's held for a short time). */
  10733. playButton, /**< The play button. */
  10734. plusButton, /**< The plus or volume-up button. */
  10735. minusButton, /**< The minus or volume-down button. */
  10736. rightButton, /**< The right button (if it's held for a short time). */
  10737. leftButton, /**< The left button (if it's held for a short time). */
  10738. rightButton_Long, /**< The right button (if it's held for a long time). */
  10739. leftButton_Long, /**< The menu button (if it's held for a long time). */
  10740. menuButton_Long, /**< The menu button (if it's held for a long time). */
  10741. playButtonSleepMode,
  10742. switched
  10743. };
  10744. /** Override this method to receive the callback about a button press.
  10745. The callback will happen on the application's message thread.
  10746. Some buttons trigger matching up and down events, in which the isDown parameter
  10747. will be true and then false. Others only send a single event when the
  10748. button is pressed.
  10749. */
  10750. virtual void buttonPressed (const ButtonType buttonId, const bool isDown) = 0;
  10751. /** Starts the device running and responding to events.
  10752. Returns true if it managed to open the device.
  10753. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  10754. and will not be available to any other part of the system. If
  10755. false, it will be shared with other apps.
  10756. @see stop
  10757. */
  10758. bool start (const bool inExclusiveMode);
  10759. /** Stops the device running.
  10760. @see start
  10761. */
  10762. void stop();
  10763. /** Returns true if the device has been started successfully.
  10764. */
  10765. bool isActive() const;
  10766. /** Returns the ID number of the remote, if it has sent one.
  10767. */
  10768. int getRemoteId() const { return remoteId; }
  10769. juce_UseDebuggingNewOperator
  10770. /** @internal */
  10771. void handleCallbackInternal();
  10772. private:
  10773. void* device;
  10774. void* queue;
  10775. int remoteId;
  10776. bool open (const bool openInExclusiveMode);
  10777. AppleRemoteDevice (const AppleRemoteDevice&);
  10778. AppleRemoteDevice& operator= (const AppleRemoteDevice&);
  10779. };
  10780. #endif
  10781. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10782. /*** End of inlined file: juce_PlatformUtilities.h ***/
  10783. #endif
  10784. #ifndef __JUCE_RANDOM_JUCEHEADER__
  10785. /*** Start of inlined file: juce_Random.h ***/
  10786. #ifndef __JUCE_RANDOM_JUCEHEADER__
  10787. #define __JUCE_RANDOM_JUCEHEADER__
  10788. /**
  10789. A simple pseudo-random number generator.
  10790. */
  10791. class JUCE_API Random
  10792. {
  10793. public:
  10794. /** Creates a Random object based on a seed value.
  10795. For a given seed value, the subsequent numbers generated by this object
  10796. will be predictable, so a good idea is to set this value based
  10797. on the time, e.g.
  10798. new Random (Time::currentTimeMillis())
  10799. */
  10800. explicit Random (int64 seedValue) throw();
  10801. /** Destructor. */
  10802. ~Random() throw();
  10803. /** Returns the next random 32 bit integer.
  10804. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  10805. */
  10806. int nextInt() throw();
  10807. /** Returns the next random number, limited to a given range.
  10808. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  10809. */
  10810. int nextInt (int maxValue) throw();
  10811. /** Returns the next 64-bit random number.
  10812. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  10813. */
  10814. int64 nextInt64() throw();
  10815. /** Returns the next random floating-point number.
  10816. @returns a random value in the range 0 to 1.0
  10817. */
  10818. float nextFloat() throw();
  10819. /** Returns the next random floating-point number.
  10820. @returns a random value in the range 0 to 1.0
  10821. */
  10822. double nextDouble() throw();
  10823. /** Returns the next random boolean value.
  10824. */
  10825. bool nextBool() throw();
  10826. /** Returns a BigInteger containing a random number.
  10827. @returns a random value in the range 0 to (maximumValue - 1).
  10828. */
  10829. const BigInteger nextLargeNumber (const BigInteger& maximumValue);
  10830. /** Sets a range of bits in a BigInteger to random values. */
  10831. void fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits);
  10832. /** To avoid the overhead of having to create a new Random object whenever
  10833. you need a number, this is a shared application-wide object that
  10834. can be used.
  10835. It's not thread-safe though, so threads should use their own Random object.
  10836. */
  10837. static Random& getSystemRandom() throw();
  10838. /** Resets this Random object to a given seed value. */
  10839. void setSeed (int64 newSeed) throw();
  10840. /** Merges this object's seed with another value.
  10841. This sets the seed to be a value created by combining the current seed and this
  10842. new value.
  10843. */
  10844. void combineSeed (int64 seedValue) throw();
  10845. /** Reseeds this generator using a value generated from various semi-random system
  10846. properties like the current time, etc.
  10847. Because this function convolves the time with the last seed value, calling
  10848. it repeatedly will increase the randomness of the final result.
  10849. */
  10850. void setSeedRandomly();
  10851. juce_UseDebuggingNewOperator
  10852. private:
  10853. int64 seed;
  10854. };
  10855. #endif // __JUCE_RANDOM_JUCEHEADER__
  10856. /*** End of inlined file: juce_Random.h ***/
  10857. #endif
  10858. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  10859. #endif
  10860. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  10861. /*** Start of inlined file: juce_Singleton.h ***/
  10862. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  10863. #define __JUCE_SINGLETON_JUCEHEADER__
  10864. /**
  10865. Macro to declare member variables and methods for a singleton class.
  10866. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  10867. to the class's definition.
  10868. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  10869. implementation code.
  10870. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  10871. destructor, in case it is deleted by other means than deleteInstance()
  10872. Clients can then call the static method MyClass::getInstance() to get a pointer
  10873. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  10874. no instance currently exists.
  10875. e.g. @code
  10876. class MySingleton
  10877. {
  10878. public:
  10879. MySingleton()
  10880. {
  10881. }
  10882. ~MySingleton()
  10883. {
  10884. // this ensures that no dangling pointers are left when the
  10885. // singleton is deleted.
  10886. clearSingletonInstance();
  10887. }
  10888. juce_DeclareSingleton (MySingleton, false)
  10889. };
  10890. juce_ImplementSingleton (MySingleton)
  10891. // example of usage:
  10892. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  10893. ...
  10894. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  10895. @endcode
  10896. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  10897. than once during the process's lifetime - i.e. after you've created and deleted the
  10898. object, getInstance() will refuse to create another one. This can be useful to stop
  10899. objects being accidentally re-created during your app's shutdown code.
  10900. If you know that your object will only be created and deleted by a single thread, you
  10901. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  10902. of this one.
  10903. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  10904. */
  10905. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  10906. \
  10907. static classname* _singletonInstance; \
  10908. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  10909. \
  10910. static classname* getInstance() \
  10911. { \
  10912. if (_singletonInstance == 0) \
  10913. {\
  10914. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  10915. \
  10916. if (_singletonInstance == 0) \
  10917. { \
  10918. static bool alreadyInside = false; \
  10919. static bool createdOnceAlready = false; \
  10920. \
  10921. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  10922. jassert (! problem); \
  10923. if (! problem) \
  10924. { \
  10925. createdOnceAlready = true; \
  10926. alreadyInside = true; \
  10927. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  10928. alreadyInside = false; \
  10929. \
  10930. _singletonInstance = newObject; \
  10931. } \
  10932. } \
  10933. } \
  10934. \
  10935. return _singletonInstance; \
  10936. } \
  10937. \
  10938. static inline classname* getInstanceWithoutCreating() throw() \
  10939. { \
  10940. return _singletonInstance; \
  10941. } \
  10942. \
  10943. static void deleteInstance() \
  10944. { \
  10945. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  10946. if (_singletonInstance != 0) \
  10947. { \
  10948. classname* const old = _singletonInstance; \
  10949. _singletonInstance = 0; \
  10950. delete old; \
  10951. } \
  10952. } \
  10953. \
  10954. void clearSingletonInstance() throw() \
  10955. { \
  10956. if (_singletonInstance == this) \
  10957. _singletonInstance = 0; \
  10958. }
  10959. /** This is a counterpart to the juce_DeclareSingleton macro.
  10960. After adding the juce_DeclareSingleton to the class definition, this macro has
  10961. to be used in the cpp file.
  10962. */
  10963. #define juce_ImplementSingleton(classname) \
  10964. \
  10965. classname* classname::_singletonInstance = 0; \
  10966. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  10967. /**
  10968. Macro to declare member variables and methods for a singleton class.
  10969. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  10970. section to make access to it thread-safe. If you know that your object will
  10971. only ever be created or deleted by a single thread, then this is a
  10972. more efficient version to use.
  10973. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  10974. than once during the process's lifetime - i.e. after you've created and deleted the
  10975. object, getInstance() will refuse to create another one. This can be useful to stop
  10976. objects being accidentally re-created during your app's shutdown code.
  10977. See the documentation for juce_DeclareSingleton for more information about
  10978. how to use it, the only difference being that you have to use
  10979. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  10980. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  10981. */
  10982. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  10983. \
  10984. static classname* _singletonInstance; \
  10985. \
  10986. static classname* getInstance() \
  10987. { \
  10988. if (_singletonInstance == 0) \
  10989. { \
  10990. static bool alreadyInside = false; \
  10991. static bool createdOnceAlready = false; \
  10992. \
  10993. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  10994. jassert (! problem); \
  10995. if (! problem) \
  10996. { \
  10997. createdOnceAlready = true; \
  10998. alreadyInside = true; \
  10999. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  11000. alreadyInside = false; \
  11001. \
  11002. _singletonInstance = newObject; \
  11003. } \
  11004. } \
  11005. \
  11006. return _singletonInstance; \
  11007. } \
  11008. \
  11009. static inline classname* getInstanceWithoutCreating() throw() \
  11010. { \
  11011. return _singletonInstance; \
  11012. } \
  11013. \
  11014. static void deleteInstance() \
  11015. { \
  11016. if (_singletonInstance != 0) \
  11017. { \
  11018. classname* const old = _singletonInstance; \
  11019. _singletonInstance = 0; \
  11020. delete old; \
  11021. } \
  11022. } \
  11023. \
  11024. void clearSingletonInstance() throw() \
  11025. { \
  11026. if (_singletonInstance == this) \
  11027. _singletonInstance = 0; \
  11028. }
  11029. /**
  11030. Macro to declare member variables and methods for a singleton class.
  11031. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  11032. for recursion or repeated instantiation. It's intended for use as a lightweight
  11033. version of a singleton, where you're using it in very straightforward
  11034. circumstances and don't need the extra checking.
  11035. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  11036. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  11037. See the documentation for juce_DeclareSingleton for more information about
  11038. how to use it, the only difference being that you have to use
  11039. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  11040. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  11041. */
  11042. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  11043. \
  11044. static classname* _singletonInstance; \
  11045. \
  11046. static classname* getInstance() \
  11047. { \
  11048. if (_singletonInstance == 0) \
  11049. _singletonInstance = new classname(); \
  11050. \
  11051. return _singletonInstance; \
  11052. } \
  11053. \
  11054. static inline classname* getInstanceWithoutCreating() throw() \
  11055. { \
  11056. return _singletonInstance; \
  11057. } \
  11058. \
  11059. static void deleteInstance() \
  11060. { \
  11061. if (_singletonInstance != 0) \
  11062. { \
  11063. classname* const old = _singletonInstance; \
  11064. _singletonInstance = 0; \
  11065. delete old; \
  11066. } \
  11067. } \
  11068. \
  11069. void clearSingletonInstance() throw() \
  11070. { \
  11071. if (_singletonInstance == this) \
  11072. _singletonInstance = 0; \
  11073. }
  11074. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  11075. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  11076. to the class definition, this macro has to be used somewhere in the cpp file.
  11077. */
  11078. #define juce_ImplementSingleton_SingleThreaded(classname) \
  11079. \
  11080. classname* classname::_singletonInstance = 0;
  11081. #endif // __JUCE_SINGLETON_JUCEHEADER__
  11082. /*** End of inlined file: juce_Singleton.h ***/
  11083. #endif
  11084. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  11085. #endif
  11086. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  11087. /*** Start of inlined file: juce_SystemStats.h ***/
  11088. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  11089. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  11090. /**
  11091. Contains methods for finding out about the current hardware and OS configuration.
  11092. */
  11093. class JUCE_API SystemStats
  11094. {
  11095. public:
  11096. /** Returns the current version of JUCE,
  11097. (just in case you didn't already know at compile-time.)
  11098. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  11099. */
  11100. static const String getJUCEVersion();
  11101. /** The set of possible results of the getOperatingSystemType() method.
  11102. */
  11103. enum OperatingSystemType
  11104. {
  11105. UnknownOS = 0,
  11106. MacOSX = 0x1000,
  11107. Linux = 0x2000,
  11108. Win95 = 0x4001,
  11109. Win98 = 0x4002,
  11110. WinNT351 = 0x4103,
  11111. WinNT40 = 0x4104,
  11112. Win2000 = 0x4105,
  11113. WinXP = 0x4106,
  11114. WinVista = 0x4107,
  11115. Windows7 = 0x4108,
  11116. Windows = 0x4000, /**< To test whether any version of Windows is running,
  11117. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  11118. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  11119. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  11120. };
  11121. /** Returns the type of operating system we're running on.
  11122. @returns one of the values from the OperatingSystemType enum.
  11123. @see getOperatingSystemName
  11124. */
  11125. static OperatingSystemType getOperatingSystemType();
  11126. /** Returns the name of the type of operating system we're running on.
  11127. @returns a string describing the OS type.
  11128. @see getOperatingSystemType
  11129. */
  11130. static const String getOperatingSystemName();
  11131. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  11132. */
  11133. static bool isOperatingSystem64Bit();
  11134. /** Returns the current user's name, if available.
  11135. @see getFullUserName()
  11136. */
  11137. static const String getLogonName();
  11138. /** Returns the current user's full name, if available.
  11139. On some OSes, this may just return the same value as getLogonName().
  11140. @see getLogonName()
  11141. */
  11142. static const String getFullUserName();
  11143. // CPU and memory information..
  11144. /** Returns the approximate CPU speed.
  11145. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  11146. what year you're reading this...)
  11147. */
  11148. static int getCpuSpeedInMegaherz();
  11149. /** Returns a string to indicate the CPU vendor.
  11150. Might not be known on some systems.
  11151. */
  11152. static const String getCpuVendor();
  11153. /** Checks whether Intel MMX instructions are available. */
  11154. static bool hasMMX();
  11155. /** Checks whether Intel SSE instructions are available. */
  11156. static bool hasSSE();
  11157. /** Checks whether Intel SSE2 instructions are available. */
  11158. static bool hasSSE2();
  11159. /** Checks whether AMD 3DNOW instructions are available. */
  11160. static bool has3DNow();
  11161. /** Returns the number of CPUs.
  11162. */
  11163. static int getNumCpus();
  11164. /** Finds out how much RAM is in the machine.
  11165. @returns the approximate number of megabytes of memory, or zero if
  11166. something goes wrong when finding out.
  11167. */
  11168. static int getMemorySizeInMegabytes();
  11169. /** Returns the system page-size.
  11170. This is only used by programmers with beards.
  11171. */
  11172. static int getPageSize();
  11173. /** Returns a list of MAC addresses found on this machine.
  11174. @param addresses an array into which the MAC addresses should be copied
  11175. @param maxNum the number of elements in this array
  11176. @param littleEndian the endianness of the numbers to return. If this is true,
  11177. the least-significant byte of each number is the first byte
  11178. of the mac address. If false, the least significant byte is
  11179. the last number. Note that the default values of this parameter
  11180. are different on Mac/PC to avoid breaking old software that was
  11181. written before this parameter was added (when the two systems
  11182. defaulted to using different endiannesses). In newer
  11183. software you probably want to specify an explicit value
  11184. for this.
  11185. @returns the number of MAC addresses that were found
  11186. */
  11187. static int getMACAddresses (int64* addresses, int maxNum,
  11188. #if JUCE_MAC
  11189. bool littleEndian = true);
  11190. #else
  11191. bool littleEndian = false);
  11192. #endif
  11193. /** Returns a list of MAC addresses found on this machine.
  11194. @returns an array of strings containing the MAC addresses that were found
  11195. */
  11196. static const StringArray getMACAddressStrings();
  11197. // not-for-public-use platform-specific method gets called at startup to initialise things.
  11198. static void initialiseStats();
  11199. private:
  11200. SystemStats();
  11201. SystemStats (const SystemStats&);
  11202. SystemStats& operator= (const SystemStats&);
  11203. };
  11204. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  11205. /*** End of inlined file: juce_SystemStats.h ***/
  11206. #endif
  11207. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  11208. #endif
  11209. #ifndef __JUCE_TIME_JUCEHEADER__
  11210. #endif
  11211. #ifndef __JUCE_UUID_JUCEHEADER__
  11212. /*** Start of inlined file: juce_Uuid.h ***/
  11213. #ifndef __JUCE_UUID_JUCEHEADER__
  11214. #define __JUCE_UUID_JUCEHEADER__
  11215. /**
  11216. A universally unique 128-bit identifier.
  11217. This class generates very random unique numbers based on the system time
  11218. and MAC addresses if any are available. It's extremely unlikely that two identical
  11219. UUIDs would ever be created by chance.
  11220. The class includes methods for saving the ID as a string or as raw binary data.
  11221. */
  11222. class JUCE_API Uuid
  11223. {
  11224. public:
  11225. /** Creates a new unique ID. */
  11226. Uuid();
  11227. /** Destructor. */
  11228. ~Uuid() throw();
  11229. /** Creates a copy of another UUID. */
  11230. Uuid (const Uuid& other);
  11231. /** Copies another UUID. */
  11232. Uuid& operator= (const Uuid& other);
  11233. /** Returns true if the ID is zero. */
  11234. bool isNull() const throw();
  11235. /** Compares two UUIDs. */
  11236. bool operator== (const Uuid& other) const;
  11237. /** Compares two UUIDs. */
  11238. bool operator!= (const Uuid& other) const;
  11239. /** Returns a stringified version of this UUID.
  11240. A Uuid object can later be reconstructed from this string using operator= or
  11241. the constructor that takes a string parameter.
  11242. @returns a 32 character hex string.
  11243. */
  11244. const String toString() const;
  11245. /** Creates an ID from an encoded string version.
  11246. @see toString
  11247. */
  11248. Uuid (const String& uuidString);
  11249. /** Copies from a stringified UUID.
  11250. The string passed in should be one that was created with the toString() method.
  11251. */
  11252. Uuid& operator= (const String& uuidString);
  11253. /** Returns a pointer to the internal binary representation of the ID.
  11254. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  11255. the constructor or operator= method that takes an array of uint8s.
  11256. */
  11257. const uint8* getRawData() const throw() { return value.asBytes; }
  11258. /** Creates a UUID from a 16-byte array.
  11259. @see getRawData
  11260. */
  11261. Uuid (const uint8* const rawData);
  11262. /** Sets this UUID from 16-bytes of raw data. */
  11263. Uuid& operator= (const uint8* const rawData);
  11264. juce_UseDebuggingNewOperator
  11265. private:
  11266. union
  11267. {
  11268. uint8 asBytes [16];
  11269. int asInt[4];
  11270. int64 asInt64[2];
  11271. } value;
  11272. };
  11273. #endif // __JUCE_UUID_JUCEHEADER__
  11274. /*** End of inlined file: juce_Uuid.h ***/
  11275. #endif
  11276. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  11277. /*** Start of inlined file: juce_BlowFish.h ***/
  11278. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  11279. #define __JUCE_BLOWFISH_JUCEHEADER__
  11280. /**
  11281. BlowFish encryption class.
  11282. */
  11283. class JUCE_API BlowFish
  11284. {
  11285. public:
  11286. /** Creates an object that can encode/decode based on the specified key.
  11287. The key data can be up to 72 bytes long.
  11288. */
  11289. BlowFish (const void* keyData, int keyBytes);
  11290. /** Creates a copy of another blowfish object. */
  11291. BlowFish (const BlowFish& other);
  11292. /** Copies another blowfish object. */
  11293. BlowFish& operator= (const BlowFish& other);
  11294. /** Destructor. */
  11295. ~BlowFish();
  11296. /** Encrypts a pair of 32-bit integers. */
  11297. void encrypt (uint32& data1, uint32& data2) const throw();
  11298. /** Decrypts a pair of 32-bit integers. */
  11299. void decrypt (uint32& data1, uint32& data2) const throw();
  11300. juce_UseDebuggingNewOperator
  11301. private:
  11302. uint32 p[18];
  11303. HeapBlock <uint32> s[4];
  11304. uint32 F (uint32 x) const throw();
  11305. };
  11306. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  11307. /*** End of inlined file: juce_BlowFish.h ***/
  11308. #endif
  11309. #ifndef __JUCE_MD5_JUCEHEADER__
  11310. /*** Start of inlined file: juce_MD5.h ***/
  11311. #ifndef __JUCE_MD5_JUCEHEADER__
  11312. #define __JUCE_MD5_JUCEHEADER__
  11313. /**
  11314. MD5 checksum class.
  11315. Create one of these with a block of source data or a string, and it calculates the
  11316. MD5 checksum of that data.
  11317. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  11318. */
  11319. class JUCE_API MD5
  11320. {
  11321. public:
  11322. /** Creates a null MD5 object. */
  11323. MD5();
  11324. /** Creates a copy of another MD5. */
  11325. MD5 (const MD5& other);
  11326. /** Copies another MD5. */
  11327. MD5& operator= (const MD5& other);
  11328. /** Creates a checksum for a block of binary data. */
  11329. explicit MD5 (const MemoryBlock& data);
  11330. /** Creates a checksum for a block of binary data. */
  11331. MD5 (const void* data, const size_t numBytes);
  11332. /** Creates a checksum for a string.
  11333. Note that this operates on the string as a block of unicode characters, so the
  11334. result you get will differ from the value you'd get if the string was treated
  11335. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  11336. of this method with a checksum created by a different framework, which may have
  11337. used a different encoding.
  11338. */
  11339. explicit MD5 (const String& text);
  11340. /** Creates a checksum for the input from a stream.
  11341. This will read up to the given number of bytes from the stream, and produce the
  11342. checksum of that. If the number of bytes to read is negative, it'll read
  11343. until the stream is exhausted.
  11344. */
  11345. MD5 (InputStream& input, int64 numBytesToRead = -1);
  11346. /** Creates a checksum for a file. */
  11347. explicit MD5 (const File& file);
  11348. /** Destructor. */
  11349. ~MD5();
  11350. /** Returns the checksum as a 16-byte block of data. */
  11351. const MemoryBlock getRawChecksumData() const;
  11352. /** Returns the checksum as a 32-digit hex string. */
  11353. const String toHexString() const;
  11354. /** Compares this to another MD5. */
  11355. bool operator== (const MD5& other) const;
  11356. /** Compares this to another MD5. */
  11357. bool operator!= (const MD5& other) const;
  11358. juce_UseDebuggingNewOperator
  11359. private:
  11360. uint8 result [16];
  11361. struct ProcessContext
  11362. {
  11363. uint8 buffer [64];
  11364. uint32 state [4];
  11365. uint32 count [2];
  11366. ProcessContext();
  11367. void processBlock (const void* data, size_t dataSize);
  11368. void transform (const void* buffer);
  11369. void finish (void* const result);
  11370. };
  11371. void processStream (InputStream& input, int64 numBytesToRead);
  11372. };
  11373. #endif // __JUCE_MD5_JUCEHEADER__
  11374. /*** End of inlined file: juce_MD5.h ***/
  11375. #endif
  11376. #ifndef __JUCE_PRIMES_JUCEHEADER__
  11377. /*** Start of inlined file: juce_Primes.h ***/
  11378. #ifndef __JUCE_PRIMES_JUCEHEADER__
  11379. #define __JUCE_PRIMES_JUCEHEADER__
  11380. /**
  11381. Prime number creation class.
  11382. This class contains static methods for generating and testing prime numbers.
  11383. @see BigInteger
  11384. */
  11385. class JUCE_API Primes
  11386. {
  11387. public:
  11388. /** Creates a random prime number with a given bit-length.
  11389. The certainty parameter specifies how many iterations to use when testing
  11390. for primality. A safe value might be anything over about 20-30.
  11391. The randomSeeds parameter lets you optionally pass it a set of values with
  11392. which to seed the random number generation, improving the security of the
  11393. keys generated.
  11394. */
  11395. static const BigInteger createProbablePrime (int bitLength,
  11396. int certainty,
  11397. const int* randomSeeds = 0,
  11398. int numRandomSeeds = 0);
  11399. /** Tests a number to see if it's prime.
  11400. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  11401. whether the number is prime.
  11402. The certainty parameter specifies how many iterations to use when testing - a
  11403. safe value might be anything over about 20-30.
  11404. */
  11405. static bool isProbablyPrime (const BigInteger& number, int certainty);
  11406. private:
  11407. Primes();
  11408. Primes (const Primes&);
  11409. Primes& operator= (const Primes&);
  11410. };
  11411. #endif // __JUCE_PRIMES_JUCEHEADER__
  11412. /*** End of inlined file: juce_Primes.h ***/
  11413. #endif
  11414. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  11415. /*** Start of inlined file: juce_RSAKey.h ***/
  11416. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  11417. #define __JUCE_RSAKEY_JUCEHEADER__
  11418. /**
  11419. RSA public/private key-pair encryption class.
  11420. An object of this type makes up one half of a public/private RSA key pair. Use the
  11421. createKeyPair() method to create a matching pair for encoding/decoding.
  11422. */
  11423. class JUCE_API RSAKey
  11424. {
  11425. public:
  11426. /** Creates a null key object.
  11427. Initialise a pair of objects for use with the createKeyPair() method.
  11428. */
  11429. RSAKey();
  11430. /** Loads a key from an encoded string representation.
  11431. This reloads a key from a string created by the toString() method.
  11432. */
  11433. explicit RSAKey (const String& stringRepresentation);
  11434. /** Destructor. */
  11435. ~RSAKey();
  11436. bool operator== (const RSAKey& other) const throw();
  11437. bool operator!= (const RSAKey& other) const throw();
  11438. /** Turns the key into a string representation.
  11439. This can be reloaded using the constructor that takes a string.
  11440. */
  11441. const String toString() const;
  11442. /** Encodes or decodes a value.
  11443. Call this on the public key object to encode some data, then use the matching
  11444. private key object to decode it.
  11445. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  11446. initialised correctly.
  11447. NOTE: This method dumbly applies this key to this data. If you encode some data
  11448. and then try to decode it with a key that doesn't match, this method will still
  11449. happily do its job and return true, but the result won't be what you were expecting.
  11450. It's your responsibility to check that the result is what you wanted.
  11451. */
  11452. bool applyToValue (BigInteger& value) const;
  11453. /** Creates a public/private key-pair.
  11454. Each key will perform one-way encryption that can only be reversed by
  11455. using the other key.
  11456. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  11457. sizes are more secure, but this method will take longer to execute.
  11458. The randomSeeds parameter lets you optionally pass it a set of values with
  11459. which to seed the random number generation, improving the security of the
  11460. keys generated.
  11461. */
  11462. static void createKeyPair (RSAKey& publicKey,
  11463. RSAKey& privateKey,
  11464. int numBits,
  11465. const int* randomSeeds = 0,
  11466. int numRandomSeeds = 0);
  11467. juce_UseDebuggingNewOperator
  11468. protected:
  11469. BigInteger part1, part2;
  11470. };
  11471. #endif // __JUCE_RSAKEY_JUCEHEADER__
  11472. /*** End of inlined file: juce_RSAKey.h ***/
  11473. #endif
  11474. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11475. /*** Start of inlined file: juce_DirectoryIterator.h ***/
  11476. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11477. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11478. /**
  11479. Searches through a the files in a directory, returning each file that is found.
  11480. A DirectoryIterator will search through a directory and its subdirectories using
  11481. a wildcard filepattern match.
  11482. If you may be finding a large number of files, this is better than
  11483. using File::findChildFiles() because it doesn't block while it finds them
  11484. all, and this is more memory-efficient.
  11485. It can also guess how far it's got using a wildly inaccurate algorithm.
  11486. */
  11487. class JUCE_API DirectoryIterator
  11488. {
  11489. public:
  11490. /** Creates a DirectoryIterator for a given directory.
  11491. After creating one of these, call its next() method to get the
  11492. first file - e.g. @code
  11493. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  11494. while (iter.next())
  11495. {
  11496. File theFileItFound (iter.getFile());
  11497. ... etc
  11498. }
  11499. @endcode
  11500. @param directory the directory to search in
  11501. @param isRecursive whether all the subdirectories should also be searched
  11502. @param wildCard the file pattern to match
  11503. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  11504. whether to look for files, directories, or both.
  11505. */
  11506. DirectoryIterator (const File& directory,
  11507. bool isRecursive,
  11508. const String& wildCard = "*",
  11509. int whatToLookFor = File::findFiles);
  11510. /** Destructor. */
  11511. ~DirectoryIterator();
  11512. /** Moves the iterator along to the next file.
  11513. @returns true if a file was found (you can then use getFile() to see what it was) - or
  11514. false if there are no more matching files.
  11515. */
  11516. bool next();
  11517. /** Moves the iterator along to the next file, and returns various properties of that file.
  11518. If you need to find out details about the file, it's more efficient to call this method than
  11519. to call the normal next() method and then find out the details afterwards.
  11520. All the parameters are optional, so pass null pointers for any items that you're not
  11521. interested in.
  11522. @returns true if a file was found (you can then use getFile() to see what it was) - or
  11523. false if there are no more matching files. If it returns false, then none of the
  11524. parameters will be filled-in.
  11525. */
  11526. bool next (bool* isDirectory, bool* isHidden, int64* fileSize,
  11527. Time* modTime, Time* creationTime, bool* isReadOnly);
  11528. /** Returns the file that the iterator is currently pointing at.
  11529. The result of this call is only valid after a call to next() has returned true.
  11530. */
  11531. const File getFile() const;
  11532. /** Returns a guess of how far through the search the iterator has got.
  11533. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  11534. very accurate.
  11535. */
  11536. float getEstimatedProgress() const;
  11537. juce_UseDebuggingNewOperator
  11538. private:
  11539. friend class File;
  11540. class NativeIterator
  11541. {
  11542. public:
  11543. NativeIterator (const File& directory, const String& wildCard);
  11544. ~NativeIterator();
  11545. bool next (String& filenameFound,
  11546. bool* isDirectory, bool* isHidden, int64* fileSize,
  11547. Time* modTime, Time* creationTime, bool* isReadOnly);
  11548. class Pimpl;
  11549. juce_UseDebuggingNewOperator
  11550. private:
  11551. friend class DirectoryIterator;
  11552. friend class ScopedPointer<Pimpl>;
  11553. ScopedPointer<Pimpl> pimpl;
  11554. NativeIterator (const NativeIterator&);
  11555. NativeIterator& operator= (const NativeIterator&);
  11556. };
  11557. friend class ScopedPointer<NativeIterator::Pimpl>;
  11558. NativeIterator fileFinder;
  11559. String wildCard, path;
  11560. int index;
  11561. mutable int totalNumFiles;
  11562. const int whatToLookFor;
  11563. const bool isRecursive;
  11564. ScopedPointer <DirectoryIterator> subIterator;
  11565. File currentFile;
  11566. DirectoryIterator (const DirectoryIterator&);
  11567. DirectoryIterator& operator= (const DirectoryIterator&);
  11568. };
  11569. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11570. /*** End of inlined file: juce_DirectoryIterator.h ***/
  11571. #endif
  11572. #ifndef __JUCE_FILE_JUCEHEADER__
  11573. #endif
  11574. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11575. /*** Start of inlined file: juce_FileInputStream.h ***/
  11576. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11577. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11578. /**
  11579. An input stream that reads from a local file.
  11580. @see InputStream, FileOutputStream, File::createInputStream
  11581. */
  11582. class JUCE_API FileInputStream : public InputStream
  11583. {
  11584. public:
  11585. /** Creates a FileInputStream.
  11586. @param fileToRead the file to read from - if the file can't be accessed for some
  11587. reason, then the stream will just contain no data
  11588. */
  11589. explicit FileInputStream (const File& fileToRead);
  11590. /** Destructor. */
  11591. ~FileInputStream();
  11592. const File& getFile() const throw() { return file; }
  11593. int64 getTotalLength();
  11594. int read (void* destBuffer, int maxBytesToRead);
  11595. bool isExhausted();
  11596. int64 getPosition();
  11597. bool setPosition (int64 pos);
  11598. juce_UseDebuggingNewOperator
  11599. private:
  11600. File file;
  11601. void* fileHandle;
  11602. int64 currentPosition, totalSize;
  11603. bool needToSeek;
  11604. FileInputStream (const FileInputStream&);
  11605. FileInputStream& operator= (const FileInputStream&);
  11606. };
  11607. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11608. /*** End of inlined file: juce_FileInputStream.h ***/
  11609. #endif
  11610. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11611. /*** Start of inlined file: juce_FileOutputStream.h ***/
  11612. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11613. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11614. /**
  11615. An output stream that writes into a local file.
  11616. @see OutputStream, FileInputStream, File::createOutputStream
  11617. */
  11618. class JUCE_API FileOutputStream : public OutputStream
  11619. {
  11620. public:
  11621. /** Creates a FileOutputStream.
  11622. If the file doesn't exist, it will first be created. If the file can't be
  11623. created or opened, the failedToOpen() method will return
  11624. true.
  11625. If the file already exists when opened, the stream's write-postion will
  11626. be set to the end of the file. To overwrite an existing file,
  11627. use File::deleteFile() before opening the stream, or use setPosition(0)
  11628. after it's opened (although this won't truncate the file).
  11629. It's better to use File::createOutputStream() to create one of these, rather
  11630. than using the class directly.
  11631. @see TemporaryFile
  11632. */
  11633. FileOutputStream (const File& fileToWriteTo,
  11634. int bufferSizeToUse = 16384);
  11635. /** Destructor. */
  11636. ~FileOutputStream();
  11637. /** Returns the file that this stream is writing to.
  11638. */
  11639. const File& getFile() const { return file; }
  11640. /** Returns true if the stream couldn't be opened for some reason.
  11641. */
  11642. bool failedToOpen() const { return fileHandle == 0; }
  11643. void flush();
  11644. int64 getPosition();
  11645. bool setPosition (int64 pos);
  11646. bool write (const void* data, int numBytes);
  11647. juce_UseDebuggingNewOperator
  11648. private:
  11649. File file;
  11650. void* fileHandle;
  11651. int64 currentPosition;
  11652. int bufferSize, bytesInBuffer;
  11653. HeapBlock <char> buffer;
  11654. void flushInternal();
  11655. int64 getPositionInternal() const;
  11656. FileOutputStream (const FileOutputStream&);
  11657. FileOutputStream& operator= (const FileOutputStream&);
  11658. };
  11659. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11660. /*** End of inlined file: juce_FileOutputStream.h ***/
  11661. #endif
  11662. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  11663. /*** Start of inlined file: juce_FileSearchPath.h ***/
  11664. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  11665. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  11666. /**
  11667. Encapsulates a set of folders that make up a search path.
  11668. @see File
  11669. */
  11670. class JUCE_API FileSearchPath
  11671. {
  11672. public:
  11673. /** Creates an empty search path. */
  11674. FileSearchPath();
  11675. /** Creates a search path from a string of pathnames.
  11676. The path can be semicolon- or comma-separated, e.g.
  11677. "/foo/bar;/foo/moose;/fish/moose"
  11678. The separate folders are tokenised and added to the search path.
  11679. */
  11680. FileSearchPath (const String& path);
  11681. /** Creates a copy of another search path. */
  11682. FileSearchPath (const FileSearchPath& other);
  11683. /** Destructor. */
  11684. ~FileSearchPath();
  11685. /** Uses a string containing a list of pathnames to re-initialise this list.
  11686. This search path is cleared and the semicolon- or comma-separated folders
  11687. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  11688. */
  11689. FileSearchPath& operator= (const String& path);
  11690. /** Returns the number of folders in this search path.
  11691. @see operator[]
  11692. */
  11693. int getNumPaths() const;
  11694. /** Returns one of the folders in this search path.
  11695. The file returned isn't guaranteed to actually be a valid directory.
  11696. @see getNumPaths
  11697. */
  11698. const File operator[] (int index) const;
  11699. /** Returns the search path as a semicolon-separated list of directories. */
  11700. const String toString() const;
  11701. /** Adds a new directory to the search path.
  11702. The new directory is added to the end of the list if the insertIndex parameter is
  11703. less than zero, otherwise it is inserted at the given index.
  11704. */
  11705. void add (const File& directoryToAdd,
  11706. int insertIndex = -1);
  11707. /** Adds a new directory to the search path if it's not already in there. */
  11708. void addIfNotAlreadyThere (const File& directoryToAdd);
  11709. /** Removes a directory from the search path. */
  11710. void remove (int indexToRemove);
  11711. /** Merges another search path into this one.
  11712. This will remove any duplicate directories.
  11713. */
  11714. void addPath (const FileSearchPath& other);
  11715. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  11716. If the search is intended to be recursive, there's no point having nested folders in the search
  11717. path, because they'll just get searched twice and you'll get duplicate results.
  11718. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  11719. */
  11720. void removeRedundantPaths();
  11721. /** Removes any directories that don't actually exist. */
  11722. void removeNonExistentPaths();
  11723. /** Searches the path for a wildcard.
  11724. This will search all the directories in the search path in order, adding any
  11725. matching files to the results array.
  11726. @param results an array to append the results to
  11727. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  11728. return files, directories, or both.
  11729. @param searchRecursively whether to recursively search the subdirectories too
  11730. @param wildCardPattern a pattern to match against the filenames
  11731. @returns the number of files added to the array
  11732. @see File::findChildFiles
  11733. */
  11734. int findChildFiles (Array<File>& results,
  11735. int whatToLookFor,
  11736. bool searchRecursively,
  11737. const String& wildCardPattern = "*") const;
  11738. /** Finds out whether a file is inside one of the path's directories.
  11739. This will return true if the specified file is a child of one of the
  11740. directories specified by this path. Note that this doesn't actually do any
  11741. searching or check that the files exist - it just looks at the pathnames
  11742. to work out whether the file would be inside a directory.
  11743. @param fileToCheck the file to look for
  11744. @param checkRecursively if true, then this will return true if the file is inside a
  11745. subfolder of one of the path's directories (at any depth). If false
  11746. it will only return true if the file is actually a direct child
  11747. of one of the directories.
  11748. @see File::isAChildOf
  11749. */
  11750. bool isFileInPath (const File& fileToCheck,
  11751. bool checkRecursively) const;
  11752. juce_UseDebuggingNewOperator
  11753. private:
  11754. StringArray directories;
  11755. void init (const String& path);
  11756. };
  11757. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  11758. /*** End of inlined file: juce_FileSearchPath.h ***/
  11759. #endif
  11760. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  11761. /*** Start of inlined file: juce_NamedPipe.h ***/
  11762. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  11763. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  11764. /**
  11765. A cross-process pipe that can have data written to and read from it.
  11766. Two or more processes can use these for inter-process communication.
  11767. @see InterprocessConnection
  11768. */
  11769. class JUCE_API NamedPipe
  11770. {
  11771. public:
  11772. /** Creates a NamedPipe. */
  11773. NamedPipe();
  11774. /** Destructor. */
  11775. ~NamedPipe();
  11776. /** Tries to open a pipe that already exists.
  11777. Returns true if it succeeds.
  11778. */
  11779. bool openExisting (const String& pipeName);
  11780. /** Tries to create a new pipe.
  11781. Returns true if it succeeds.
  11782. */
  11783. bool createNewPipe (const String& pipeName);
  11784. /** Closes the pipe, if it's open. */
  11785. void close();
  11786. /** True if the pipe is currently open. */
  11787. bool isOpen() const;
  11788. /** Returns the last name that was used to try to open this pipe. */
  11789. const String getName() const;
  11790. /** Reads data from the pipe.
  11791. This will block until another thread has written enough data into the pipe to fill
  11792. the number of bytes specified, or until another thread calls the cancelPendingReads()
  11793. method.
  11794. If the operation fails, it returns -1, otherwise, it will return the number of
  11795. bytes read.
  11796. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  11797. this is a maximum timeout for reading from the pipe.
  11798. */
  11799. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  11800. /** Writes some data to the pipe.
  11801. If the operation fails, it returns -1, otherwise, it will return the number of
  11802. bytes written.
  11803. */
  11804. int write (const void* sourceBuffer, int numBytesToWrite,
  11805. int timeOutMilliseconds = 2000);
  11806. /** If any threads are currently blocked on a read operation, this tells them to abort.
  11807. */
  11808. void cancelPendingReads();
  11809. juce_UseDebuggingNewOperator
  11810. private:
  11811. void* internal;
  11812. String currentPipeName;
  11813. CriticalSection lock;
  11814. NamedPipe (const NamedPipe&);
  11815. NamedPipe& operator= (const NamedPipe&);
  11816. bool openInternal (const String& pipeName, const bool createPipe);
  11817. };
  11818. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  11819. /*** End of inlined file: juce_NamedPipe.h ***/
  11820. #endif
  11821. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  11822. /*** Start of inlined file: juce_TemporaryFile.h ***/
  11823. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  11824. #define __JUCE_TEMPORARYFILE_JUCEHEADER__
  11825. /**
  11826. Manages a temporary file, which will be deleted when this object is deleted.
  11827. This object is intended to be used as a stack based object, using its scope
  11828. to make sure the temporary file isn't left lying around.
  11829. For example:
  11830. @code
  11831. {
  11832. File myTargetFile ("~/myfile.txt");
  11833. // this will choose a file called something like "~/myfile_temp239348.txt"
  11834. // which definitely doesn't exist at the time the constructor is called.
  11835. TemporaryFile temp (myTargetFile);
  11836. // create a stream to the temporary file, and write some data to it...
  11837. ScopedPointer <FileOutputStream> out (temp.getFile().createOutputStream());
  11838. if (out != 0)
  11839. {
  11840. out->write ( ...etc )
  11841. out->flush();
  11842. out = 0; // (deletes the stream)
  11843. // ..now we've finished writing, this will rename the temp file to
  11844. // make it replace the target file we specified above.
  11845. bool succeeded = temp.overwriteTargetFileWithTemporary();
  11846. }
  11847. // ..and even if something went wrong and our overwrite failed,
  11848. // as the TemporaryFile object goes out of scope here, it'll make sure
  11849. // that the temp file gets deleted.
  11850. }
  11851. @endcode
  11852. @see File, FileOutputStream
  11853. */
  11854. class JUCE_API TemporaryFile
  11855. {
  11856. public:
  11857. enum OptionFlags
  11858. {
  11859. useHiddenFile = 1, /**< Indicates that the temporary file should be hidden -
  11860. i.e. its name should start with a dot. */
  11861. putNumbersInBrackets = 2 /**< Indicates that when numbers are appended to make sure
  11862. the file is unique, they should go in brackets rather
  11863. than just being appended (see File::getNonexistentSibling() )*/
  11864. };
  11865. /** Creates a randomly-named temporary file in the default temp directory.
  11866. @param suffix a file suffix to use for the file
  11867. @param optionFlags a combination of the values listed in the OptionFlags enum
  11868. The file will not be created until you write to it. And remember that when
  11869. this object is deleted, the file will also be deleted!
  11870. */
  11871. TemporaryFile (const String& suffix = String::empty,
  11872. int optionFlags = 0);
  11873. /** Creates a temporary file in the same directory as a specified file.
  11874. This is useful if you have a file that you want to overwrite, but don't
  11875. want to harm the original file if the write operation fails. You can
  11876. use this to create a temporary file next to the target file, then
  11877. write to the temporary file, and finally use overwriteTargetFileWithTemporary()
  11878. to replace the target file with the one you've just written.
  11879. This class won't create any files until you actually write to them. And remember
  11880. that when this object is deleted, the temporary file will also be deleted!
  11881. @param targetFile the file that you intend to overwrite - the temporary
  11882. file will be created in the same directory as this
  11883. @param optionFlags a combination of the values listed in the OptionFlags enum
  11884. */
  11885. TemporaryFile (const File& targetFile,
  11886. int optionFlags = 0);
  11887. /** Destructor.
  11888. When this object is deleted it will make sure that its temporary file is
  11889. also deleted! If the operation fails, it'll throw an assertion in debug
  11890. mode.
  11891. */
  11892. ~TemporaryFile();
  11893. /** Returns the temporary file. */
  11894. const File getFile() const { return temporaryFile; }
  11895. /** Returns the target file that was specified in the constructor. */
  11896. const File getTargetFile() const { return targetFile; }
  11897. /** Tries to move the temporary file to overwrite the target file that was
  11898. specified in the constructor.
  11899. If you used the constructor that specified a target file, this will attempt
  11900. to replace that file with the temporary one.
  11901. Before calling this, make sure:
  11902. - that you've actually written to the temporary file
  11903. - that you've closed any open streams that you were using to write to it
  11904. - and that you don't have any streams open to the target file, which would
  11905. prevent it being overwritten
  11906. If the file move succeeds, this returns false, and the temporary file will
  11907. have disappeared. If it fails, the temporary file will probably still exist,
  11908. but will be deleted when this object is destroyed.
  11909. */
  11910. bool overwriteTargetFileWithTemporary() const;
  11911. juce_UseDebuggingNewOperator
  11912. private:
  11913. File temporaryFile, targetFile;
  11914. void createTempFile (const File& parentDirectory, String name, const String& suffix, int optionFlags);
  11915. TemporaryFile (const TemporaryFile&);
  11916. TemporaryFile& operator= (const TemporaryFile&);
  11917. };
  11918. #endif // __JUCE_TEMPORARYFILE_JUCEHEADER__
  11919. /*** End of inlined file: juce_TemporaryFile.h ***/
  11920. #endif
  11921. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  11922. /*** Start of inlined file: juce_ZipFile.h ***/
  11923. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  11924. #define __JUCE_ZIPFILE_JUCEHEADER__
  11925. /*** Start of inlined file: juce_InputSource.h ***/
  11926. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  11927. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  11928. /**
  11929. A lightweight object that can create a stream to read some kind of resource.
  11930. This may be used to refer to a file, or some other kind of source, allowing a
  11931. caller to create an input stream that can read from it when required.
  11932. @see FileInputSource
  11933. */
  11934. class JUCE_API InputSource
  11935. {
  11936. public:
  11937. InputSource() throw() {}
  11938. /** Destructor. */
  11939. virtual ~InputSource() {}
  11940. /** Returns a new InputStream to read this item.
  11941. @returns an inputstream that the caller will delete, or 0 if
  11942. the filename isn't found.
  11943. */
  11944. virtual InputStream* createInputStream() = 0;
  11945. /** Returns a new InputStream to read an item, relative.
  11946. @param relatedItemPath the relative pathname of the resource that is required
  11947. @returns an inputstream that the caller will delete, or 0 if
  11948. the item isn't found.
  11949. */
  11950. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  11951. /** Returns a hash code that uniquely represents this item.
  11952. */
  11953. virtual int64 hashCode() const = 0;
  11954. juce_UseDebuggingNewOperator
  11955. };
  11956. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  11957. /*** End of inlined file: juce_InputSource.h ***/
  11958. /**
  11959. Decodes a ZIP file from a stream.
  11960. This can enumerate the items in a ZIP file and can create suitable stream objects
  11961. to read each one.
  11962. */
  11963. class JUCE_API ZipFile
  11964. {
  11965. public:
  11966. /** Creates a ZipFile for a given stream.
  11967. @param inputStream the stream to read from
  11968. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  11969. will be deleted when this ZipFile object is deleted
  11970. */
  11971. ZipFile (InputStream* inputStream,
  11972. bool deleteStreamWhenDestroyed) throw();
  11973. /** Creates a ZipFile based for a file. */
  11974. ZipFile (const File& file);
  11975. /** Creates a ZipFile for an input source.
  11976. The inputSource object will be owned by the zip file, which will delete
  11977. it later when not needed.
  11978. */
  11979. ZipFile (InputSource* inputSource);
  11980. /** Destructor. */
  11981. ~ZipFile() throw();
  11982. /**
  11983. Contains information about one of the entries in a ZipFile.
  11984. @see ZipFile::getEntry
  11985. */
  11986. struct ZipEntry
  11987. {
  11988. /** The name of the file, which may also include a partial pathname. */
  11989. String filename;
  11990. /** The file's original size. */
  11991. unsigned int uncompressedSize;
  11992. /** The last time the file was modified. */
  11993. Time fileTime;
  11994. };
  11995. /** Returns the number of items in the zip file. */
  11996. int getNumEntries() const throw();
  11997. /** Returns a structure that describes one of the entries in the zip file.
  11998. This may return zero if the index is out of range.
  11999. @see ZipFile::ZipEntry
  12000. */
  12001. const ZipEntry* getEntry (int index) const throw();
  12002. /** Returns the index of the first entry with a given filename.
  12003. This uses a case-sensitive comparison to look for a filename in the
  12004. list of entries. It might return -1 if no match is found.
  12005. @see ZipFile::ZipEntry
  12006. */
  12007. int getIndexOfFileName (const String& fileName) const throw();
  12008. /** Returns a structure that describes one of the entries in the zip file.
  12009. This uses a case-sensitive comparison to look for a filename in the
  12010. list of entries. It might return 0 if no match is found.
  12011. @see ZipFile::ZipEntry
  12012. */
  12013. const ZipEntry* getEntry (const String& fileName) const throw();
  12014. /** Sorts the list of entries, based on the filename.
  12015. */
  12016. void sortEntriesByFilename();
  12017. /** Creates a stream that can read from one of the zip file's entries.
  12018. The stream that is returned must be deleted by the caller (and
  12019. zero might be returned if a stream can't be opened for some reason).
  12020. The stream must not be used after the ZipFile object that created
  12021. has been deleted.
  12022. */
  12023. InputStream* createStreamForEntry (int index);
  12024. /** Uncompresses all of the files in the zip file.
  12025. This will expand all the entires into a target directory. The relative
  12026. paths of the entries are used.
  12027. @param targetDirectory the root folder to uncompress to
  12028. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  12029. */
  12030. void uncompressTo (const File& targetDirectory,
  12031. bool shouldOverwriteFiles = true);
  12032. juce_UseDebuggingNewOperator
  12033. private:
  12034. class ZipInputStream;
  12035. class ZipFilenameComparator;
  12036. class ZipEntryInfo;
  12037. friend class ZipInputStream;
  12038. friend class ZipFilenameComparator;
  12039. friend class ZipEntryInfo;
  12040. OwnedArray <ZipEntryInfo> entries;
  12041. CriticalSection lock;
  12042. InputStream* inputStream;
  12043. ScopedPointer <InputStream> streamToDelete;
  12044. ScopedPointer <InputSource> inputSource;
  12045. #if JUCE_DEBUG
  12046. int numOpenStreams;
  12047. #endif
  12048. void init();
  12049. int findEndOfZipEntryTable (InputStream* in, int& numEntries);
  12050. static int compareElements (const ZipEntryInfo* first, const ZipEntryInfo* second);
  12051. ZipFile (const ZipFile&);
  12052. ZipFile& operator= (const ZipFile&);
  12053. };
  12054. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  12055. /*** End of inlined file: juce_ZipFile.h ***/
  12056. #endif
  12057. #ifndef __JUCE_SOCKET_JUCEHEADER__
  12058. /*** Start of inlined file: juce_Socket.h ***/
  12059. #ifndef __JUCE_SOCKET_JUCEHEADER__
  12060. #define __JUCE_SOCKET_JUCEHEADER__
  12061. /**
  12062. A wrapper for a streaming (TCP) socket.
  12063. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  12064. sockets, you could also try the InterprocessConnection class.
  12065. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  12066. */
  12067. class JUCE_API StreamingSocket
  12068. {
  12069. public:
  12070. /** Creates an uninitialised socket.
  12071. To connect it, use the connect() method, after which you can read() or write()
  12072. to it.
  12073. To wait for other sockets to connect to this one, the createListener() method
  12074. enters "listener" mode, and can be used to spawn new sockets for each connection
  12075. that comes along.
  12076. */
  12077. StreamingSocket();
  12078. /** Destructor. */
  12079. ~StreamingSocket();
  12080. /** Binds the socket to the specified local port.
  12081. @returns true on success; false may indicate that another socket is already bound
  12082. on the same port
  12083. */
  12084. bool bindToPort (int localPortNumber);
  12085. /** Tries to connect the socket to hostname:port.
  12086. If timeOutMillisecs is 0, then this method will block until the operating system
  12087. rejects the connection (which could take a long time).
  12088. @returns true if it succeeds.
  12089. @see isConnected
  12090. */
  12091. bool connect (const String& remoteHostname,
  12092. int remotePortNumber,
  12093. int timeOutMillisecs = 3000);
  12094. /** True if the socket is currently connected. */
  12095. bool isConnected() const throw() { return connected; }
  12096. /** Closes the connection. */
  12097. void close();
  12098. /** Returns the name of the currently connected host. */
  12099. const String& getHostName() const throw() { return hostName; }
  12100. /** Returns the port number that's currently open. */
  12101. int getPort() const throw() { return portNumber; }
  12102. /** True if the socket is connected to this machine rather than over the network. */
  12103. bool isLocal() const throw();
  12104. /** Waits until the socket is ready for reading or writing.
  12105. If readyForReading is true, it will wait until the socket is ready for
  12106. reading; if false, it will wait until it's ready for writing.
  12107. If the timeout is < 0, it will wait forever, or else will give up after
  12108. the specified time.
  12109. If the socket is ready on return, this returns 1. If it times-out before
  12110. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  12111. */
  12112. int waitUntilReady (bool readyForReading,
  12113. int timeoutMsecs) const;
  12114. /** Reads bytes from the socket.
  12115. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  12116. maxBytesToRead bytes have been read, (or until an error occurs). If this
  12117. flag is false, the method will return as much data as is currently available
  12118. without blocking.
  12119. @returns the number of bytes read, or -1 if there was an error.
  12120. @see waitUntilReady
  12121. */
  12122. int read (void* destBuffer, int maxBytesToRead,
  12123. bool blockUntilSpecifiedAmountHasArrived);
  12124. /** Writes bytes to the socket from a buffer.
  12125. Note that this method will block unless you have checked the socket is ready
  12126. for writing before calling it (see the waitUntilReady() method).
  12127. @returns the number of bytes written, or -1 if there was an error.
  12128. */
  12129. int write (const void* sourceBuffer, int numBytesToWrite);
  12130. /** Puts this socket into "listener" mode.
  12131. When in this mode, your thread can call waitForNextConnection() repeatedly,
  12132. which will spawn new sockets for each new connection, so that these can
  12133. be handled in parallel by other threads.
  12134. @param portNumber the port number to listen on
  12135. @param localHostName the interface address to listen on - pass an empty
  12136. string to listen on all addresses
  12137. @returns true if it manages to open the socket successfully.
  12138. @see waitForNextConnection
  12139. */
  12140. bool createListener (int portNumber, const String& localHostName = String::empty);
  12141. /** When in "listener" mode, this waits for a connection and spawns it as a new
  12142. socket.
  12143. The object that gets returned will be owned by the caller.
  12144. This method can only be called after using createListener().
  12145. @see createListener
  12146. */
  12147. StreamingSocket* waitForNextConnection() const;
  12148. juce_UseDebuggingNewOperator
  12149. private:
  12150. String hostName;
  12151. int volatile portNumber, handle;
  12152. bool connected, isListener;
  12153. StreamingSocket (const String& hostname, int portNumber, int handle);
  12154. StreamingSocket (const StreamingSocket&);
  12155. StreamingSocket& operator= (const StreamingSocket&);
  12156. };
  12157. /**
  12158. A wrapper for a datagram (UDP) socket.
  12159. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  12160. sockets, you could also try the InterprocessConnection class.
  12161. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  12162. */
  12163. class JUCE_API DatagramSocket
  12164. {
  12165. public:
  12166. /**
  12167. Creates an (uninitialised) datagram socket.
  12168. The localPortNumber is the port on which to bind this socket. If this value is 0,
  12169. the port number is assigned by the operating system.
  12170. To use the socket for sending, call the connect() method. This will not immediately
  12171. make a connection, but will save the destination you've provided. After this, you can
  12172. call read() or write().
  12173. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  12174. (may require extra privileges on linux)
  12175. To wait for other sockets to connect to this one, call waitForNextConnection().
  12176. */
  12177. DatagramSocket (int localPortNumber,
  12178. bool enableBroadcasting = false);
  12179. /** Destructor. */
  12180. ~DatagramSocket();
  12181. /** Binds the socket to the specified local port.
  12182. @returns true on success; false may indicate that another socket is already bound
  12183. on the same port
  12184. */
  12185. bool bindToPort (int localPortNumber);
  12186. /** Tries to connect the socket to hostname:port.
  12187. If timeOutMillisecs is 0, then this method will block until the operating system
  12188. rejects the connection (which could take a long time).
  12189. @returns true if it succeeds.
  12190. @see isConnected
  12191. */
  12192. bool connect (const String& remoteHostname,
  12193. int remotePortNumber,
  12194. int timeOutMillisecs = 3000);
  12195. /** True if the socket is currently connected. */
  12196. bool isConnected() const throw() { return connected; }
  12197. /** Closes the connection. */
  12198. void close();
  12199. /** Returns the name of the currently connected host. */
  12200. const String& getHostName() const throw() { return hostName; }
  12201. /** Returns the port number that's currently open. */
  12202. int getPort() const throw() { return portNumber; }
  12203. /** True if the socket is connected to this machine rather than over the network. */
  12204. bool isLocal() const throw();
  12205. /** Waits until the socket is ready for reading or writing.
  12206. If readyForReading is true, it will wait until the socket is ready for
  12207. reading; if false, it will wait until it's ready for writing.
  12208. If the timeout is < 0, it will wait forever, or else will give up after
  12209. the specified time.
  12210. If the socket is ready on return, this returns 1. If it times-out before
  12211. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  12212. */
  12213. int waitUntilReady (bool readyForReading,
  12214. int timeoutMsecs) const;
  12215. /** Reads bytes from the socket.
  12216. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  12217. maxBytesToRead bytes have been read, (or until an error occurs). If this
  12218. flag is false, the method will return as much data as is currently available
  12219. without blocking.
  12220. @returns the number of bytes read, or -1 if there was an error.
  12221. @see waitUntilReady
  12222. */
  12223. int read (void* destBuffer, int maxBytesToRead,
  12224. bool blockUntilSpecifiedAmountHasArrived);
  12225. /** Writes bytes to the socket from a buffer.
  12226. Note that this method will block unless you have checked the socket is ready
  12227. for writing before calling it (see the waitUntilReady() method).
  12228. @returns the number of bytes written, or -1 if there was an error.
  12229. */
  12230. int write (const void* sourceBuffer, int numBytesToWrite);
  12231. /** This waits for incoming data to be sent, and returns a socket that can be used
  12232. to read it.
  12233. The object that gets returned is owned by the caller, and can't be used for
  12234. sending, but can be used to read the data.
  12235. */
  12236. DatagramSocket* waitForNextConnection() const;
  12237. juce_UseDebuggingNewOperator
  12238. private:
  12239. String hostName;
  12240. int volatile portNumber, handle;
  12241. bool connected, allowBroadcast;
  12242. void* serverAddress;
  12243. DatagramSocket (const String& hostname, int portNumber, int handle, int localPortNumber);
  12244. DatagramSocket (const DatagramSocket&);
  12245. DatagramSocket& operator= (const DatagramSocket&);
  12246. };
  12247. #endif // __JUCE_SOCKET_JUCEHEADER__
  12248. /*** End of inlined file: juce_Socket.h ***/
  12249. #endif
  12250. #ifndef __JUCE_URL_JUCEHEADER__
  12251. /*** Start of inlined file: juce_URL.h ***/
  12252. #ifndef __JUCE_URL_JUCEHEADER__
  12253. #define __JUCE_URL_JUCEHEADER__
  12254. /**
  12255. Represents a URL and has a bunch of useful functions to manipulate it.
  12256. This class can be used to launch URLs in browsers, and also to create
  12257. InputStreams that can read from remote http or ftp sources.
  12258. */
  12259. class JUCE_API URL
  12260. {
  12261. public:
  12262. /** Creates an empty URL. */
  12263. URL();
  12264. /** Creates a URL from a string. */
  12265. URL (const String& url);
  12266. /** Creates a copy of another URL. */
  12267. URL (const URL& other);
  12268. /** Destructor. */
  12269. ~URL();
  12270. /** Copies this URL from another one. */
  12271. URL& operator= (const URL& other);
  12272. /** Returns a string version of the URL.
  12273. If includeGetParameters is true and any parameters have been set with the
  12274. withParameter() method, then the string will have these appended on the
  12275. end and url-encoded.
  12276. */
  12277. const String toString (bool includeGetParameters) const;
  12278. /** True if it seems to be valid. */
  12279. bool isWellFormed() const;
  12280. /** Returns just the domain part of the URL.
  12281. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  12282. */
  12283. const String getDomain() const;
  12284. /** Returns the path part of the URL.
  12285. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  12286. */
  12287. const String getSubPath() const;
  12288. /** Returns the scheme of the URL.
  12289. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  12290. include the colon).
  12291. */
  12292. const String getScheme() const;
  12293. /** Returns a new version of this URL that uses a different sub-path.
  12294. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  12295. "bar", it'll return "http://www.xyz.com/bar?x=1".
  12296. */
  12297. const URL withNewSubPath (const String& newPath) const;
  12298. /** Returns a copy of this URL, with a GET or POST parameter added to the end.
  12299. Any control characters in the value will be encoded.
  12300. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  12301. would produce a new url whose toString(true) method would return
  12302. "www.fish.com?amount=some+fish".
  12303. */
  12304. const URL withParameter (const String& parameterName,
  12305. const String& parameterValue) const;
  12306. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  12307. When performing a POST where one of your parameters is a binary file, this
  12308. lets you specify the file.
  12309. Note that the filename is stored, but the file itself won't actually be read
  12310. until this URL is later used to create a network input stream.
  12311. */
  12312. const URL withFileToUpload (const String& parameterName,
  12313. const File& fileToUpload,
  12314. const String& mimeType) const;
  12315. /** Returns a set of all the parameters encoded into the url.
  12316. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  12317. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  12318. The values returned will have been cleaned up to remove any escape characters.
  12319. @see getNamedParameter, withParameter
  12320. */
  12321. const StringPairArray& getParameters() const;
  12322. /** Returns the set of files that should be uploaded as part of a POST operation.
  12323. This is the set of files that were added to the URL with the withFileToUpload()
  12324. method.
  12325. */
  12326. const StringPairArray& getFilesToUpload() const;
  12327. /** Returns the set of mime types associated with each of the upload files.
  12328. */
  12329. const StringPairArray& getMimeTypesOfUploadFiles() const;
  12330. /** Returns a copy of this URL, with a block of data to send as the POST data.
  12331. If you're setting the POST data, be careful not to have any parameters set
  12332. as well, otherwise it'll all get thrown in together, and might not have the
  12333. desired effect.
  12334. If the URL already contains some POST data, this will replace it, rather
  12335. than being appended to it.
  12336. This data will only be used if you specify a post operation when you call
  12337. createInputStream().
  12338. */
  12339. const URL withPOSTData (const String& postData) const;
  12340. /** Returns the data that was set using withPOSTData().
  12341. */
  12342. const String getPostData() const { return postData; }
  12343. /** Tries to launch the system's default browser to open the URL.
  12344. Returns true if this seems to have worked.
  12345. */
  12346. bool launchInDefaultBrowser() const;
  12347. /** Takes a guess as to whether a string might be a valid website address.
  12348. This isn't foolproof!
  12349. */
  12350. static bool isProbablyAWebsiteURL (const String& possibleURL);
  12351. /** Takes a guess as to whether a string might be a valid email address.
  12352. This isn't foolproof!
  12353. */
  12354. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  12355. /** This callback function can be used by the createInputStream() method.
  12356. It allows your app to receive progress updates during a lengthy POST operation. If you
  12357. want to continue the operation, this should return true, or false to abort.
  12358. */
  12359. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  12360. /** Attempts to open a stream that can read from this URL.
  12361. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  12362. the paramters, otherwise it'll encode them into the
  12363. URL and do a 'GET'.
  12364. @param progressCallback if this is non-zero, it lets you supply a callback function
  12365. to keep track of the operation's progress. This can be useful
  12366. for lengthy POST operations, so that you can provide user feedback.
  12367. @param progressCallbackContext if a callback is specified, this value will be passed to
  12368. the function
  12369. @param extraHeaders if not empty, this string is appended onto the headers that
  12370. are used for the request. It must therefore be a valid set of HTML
  12371. header directives, separated by newlines.
  12372. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  12373. a negative number, it will be infinite. Otherwise it specifies a
  12374. time in milliseconds.
  12375. @param responseHeaders if this is non-zero, all the (key, value) pairs received as headers
  12376. in the response will be stored in this array
  12377. @returns an input stream that the caller must delete, or a null pointer if there was an
  12378. error trying to open it.
  12379. */
  12380. InputStream* createInputStream (bool usePostCommand,
  12381. OpenStreamProgressCallback* progressCallback = 0,
  12382. void* progressCallbackContext = 0,
  12383. const String& extraHeaders = String::empty,
  12384. int connectionTimeOutMs = 0,
  12385. StringPairArray* responseHeaders = 0) const;
  12386. /** Tries to download the entire contents of this URL into a binary data block.
  12387. If it succeeds, this will return true and append the data it read onto the end
  12388. of the memory block.
  12389. @param destData the memory block to append the new data to
  12390. @param usePostCommand whether to use a POST command to get the data (uses
  12391. a GET command if this is false)
  12392. @see readEntireTextStream, readEntireXmlStream
  12393. */
  12394. bool readEntireBinaryStream (MemoryBlock& destData,
  12395. bool usePostCommand = false) const;
  12396. /** Tries to download the entire contents of this URL as a string.
  12397. If it fails, this will return an empty string, otherwise it will return the
  12398. contents of the downloaded file. If you need to distinguish between a read
  12399. operation that fails and one that returns an empty string, you'll need to use
  12400. a different method, such as readEntireBinaryStream().
  12401. @param usePostCommand whether to use a POST command to get the data (uses
  12402. a GET command if this is false)
  12403. @see readEntireBinaryStream, readEntireXmlStream
  12404. */
  12405. const String readEntireTextStream (bool usePostCommand = false) const;
  12406. /** Tries to download the entire contents of this URL and parse it as XML.
  12407. If it fails, or if the text that it reads can't be parsed as XML, this will
  12408. return 0.
  12409. When it returns a valid XmlElement object, the caller is responsibile for deleting
  12410. this object when no longer needed.
  12411. @param usePostCommand whether to use a POST command to get the data (uses
  12412. a GET command if this is false)
  12413. @see readEntireBinaryStream, readEntireTextStream
  12414. */
  12415. XmlElement* readEntireXmlStream (bool usePostCommand = false) const;
  12416. /** Adds escape sequences to a string to encode any characters that aren't
  12417. legal in a URL.
  12418. E.g. any spaces will be replaced with "%20".
  12419. This is the opposite of removeEscapeChars().
  12420. If isParameter is true, it means that the string is going to be used
  12421. as a parameter, so it also encodes '$' and ',' (which would otherwise
  12422. be legal in a URL.
  12423. @see removeEscapeChars
  12424. */
  12425. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  12426. bool isParameter);
  12427. /** Replaces any escape character sequences in a string with their original
  12428. character codes.
  12429. E.g. any instances of "%20" will be replaced by a space.
  12430. This is the opposite of addEscapeChars().
  12431. @see addEscapeChars
  12432. */
  12433. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  12434. juce_UseDebuggingNewOperator
  12435. private:
  12436. String url, postData;
  12437. StringPairArray parameters, filesToUpload, mimeTypes;
  12438. };
  12439. #endif // __JUCE_URL_JUCEHEADER__
  12440. /*** End of inlined file: juce_URL.h ***/
  12441. #endif
  12442. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12443. /*** Start of inlined file: juce_BufferedInputStream.h ***/
  12444. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12445. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12446. /** Wraps another input stream, and reads from it using an intermediate buffer
  12447. If you're using an input stream such as a file input stream, and making lots of
  12448. small read accesses to it, it's probably sensible to wrap it in one of these,
  12449. so that the source stream gets accessed in larger chunk sizes, meaning less
  12450. work for the underlying stream.
  12451. */
  12452. class JUCE_API BufferedInputStream : public InputStream
  12453. {
  12454. public:
  12455. /** Creates a BufferedInputStream from an input source.
  12456. @param sourceStream the source stream to read from
  12457. @param bufferSize the size of reservoir to use to buffer the source
  12458. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  12459. deleted by this object when it is itself deleted.
  12460. */
  12461. BufferedInputStream (InputStream* sourceStream,
  12462. int bufferSize,
  12463. bool deleteSourceWhenDestroyed);
  12464. /** Destructor.
  12465. This may also delete the source stream, if that option was chosen when the
  12466. buffered stream was created.
  12467. */
  12468. ~BufferedInputStream();
  12469. int64 getTotalLength();
  12470. int64 getPosition();
  12471. bool setPosition (int64 newPosition);
  12472. int read (void* destBuffer, int maxBytesToRead);
  12473. const String readString();
  12474. bool isExhausted();
  12475. juce_UseDebuggingNewOperator
  12476. private:
  12477. InputStream* const source;
  12478. ScopedPointer <InputStream> sourceToDelete;
  12479. int bufferSize;
  12480. int64 position, lastReadPos, bufferStart, bufferOverlap;
  12481. HeapBlock <char> buffer;
  12482. void ensureBuffered();
  12483. BufferedInputStream (const BufferedInputStream&);
  12484. BufferedInputStream& operator= (const BufferedInputStream&);
  12485. };
  12486. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12487. /*** End of inlined file: juce_BufferedInputStream.h ***/
  12488. #endif
  12489. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12490. /*** Start of inlined file: juce_FileInputSource.h ***/
  12491. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12492. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12493. /**
  12494. A type of InputSource that represents a normal file.
  12495. @see InputSource
  12496. */
  12497. class JUCE_API FileInputSource : public InputSource
  12498. {
  12499. public:
  12500. FileInputSource (const File& file);
  12501. ~FileInputSource();
  12502. InputStream* createInputStream();
  12503. InputStream* createInputStreamFor (const String& relatedItemPath);
  12504. int64 hashCode() const;
  12505. juce_UseDebuggingNewOperator
  12506. private:
  12507. const File file;
  12508. FileInputSource (const FileInputSource&);
  12509. FileInputSource& operator= (const FileInputSource&);
  12510. };
  12511. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12512. /*** End of inlined file: juce_FileInputSource.h ***/
  12513. #endif
  12514. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12515. /*** Start of inlined file: juce_GZIPCompressorOutputStream.h ***/
  12516. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12517. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12518. class GZIPCompressorHelper;
  12519. /**
  12520. A stream which uses zlib to compress the data written into it.
  12521. @see GZIPDecompressorInputStream
  12522. */
  12523. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  12524. {
  12525. public:
  12526. /** Creates a compression stream.
  12527. @param destStream the stream into which the compressed data should
  12528. be written
  12529. @param compressionLevel how much to compress the data, between 1 and 9, where
  12530. 1 is the fastest/lowest compression, and 9 is the
  12531. slowest/highest compression. Any value outside this range
  12532. indicates that a default compression level should be used.
  12533. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  12534. this stream is destroyed
  12535. @param noWrap this is used internally by the ZipFile class
  12536. and should be ignored by user applications
  12537. */
  12538. GZIPCompressorOutputStream (OutputStream* destStream,
  12539. int compressionLevel = 0,
  12540. bool deleteDestStreamWhenDestroyed = false,
  12541. bool noWrap = false);
  12542. /** Destructor. */
  12543. ~GZIPCompressorOutputStream();
  12544. void flush();
  12545. int64 getPosition();
  12546. bool setPosition (int64 newPosition);
  12547. bool write (const void* destBuffer, int howMany);
  12548. juce_UseDebuggingNewOperator
  12549. private:
  12550. OutputStream* const destStream;
  12551. ScopedPointer <OutputStream> streamToDelete;
  12552. HeapBlock <uint8> buffer;
  12553. ScopedPointer <GZIPCompressorHelper> helper;
  12554. bool doNextBlock();
  12555. GZIPCompressorOutputStream (const GZIPCompressorOutputStream&);
  12556. GZIPCompressorOutputStream& operator= (const GZIPCompressorOutputStream&);
  12557. };
  12558. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12559. /*** End of inlined file: juce_GZIPCompressorOutputStream.h ***/
  12560. #endif
  12561. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12562. /*** Start of inlined file: juce_GZIPDecompressorInputStream.h ***/
  12563. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12564. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12565. class GZIPDecompressHelper;
  12566. /**
  12567. This stream will decompress a source-stream using zlib.
  12568. Tip: if you're reading lots of small items from one of these streams, you
  12569. can increase the performance enormously by passing it through a
  12570. BufferedInputStream, so that it has to read larger blocks less often.
  12571. @see GZIPCompressorOutputStream
  12572. */
  12573. class JUCE_API GZIPDecompressorInputStream : public InputStream
  12574. {
  12575. public:
  12576. /** Creates a decompressor stream.
  12577. @param sourceStream the stream to read from
  12578. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  12579. when this object is destroyed
  12580. @param noWrap this is used internally by the ZipFile class
  12581. and should be ignored by user applications
  12582. @param uncompressedStreamLength if the creator knows the length that the
  12583. uncompressed stream will be, then it can supply this
  12584. value, which will be returned by getTotalLength()
  12585. */
  12586. GZIPDecompressorInputStream (InputStream* sourceStream,
  12587. bool deleteSourceWhenDestroyed,
  12588. bool noWrap = false,
  12589. int64 uncompressedStreamLength = -1);
  12590. /** Destructor. */
  12591. ~GZIPDecompressorInputStream();
  12592. int64 getPosition();
  12593. bool setPosition (int64 pos);
  12594. int64 getTotalLength();
  12595. bool isExhausted();
  12596. int read (void* destBuffer, int maxBytesToRead);
  12597. juce_UseDebuggingNewOperator
  12598. private:
  12599. InputStream* const sourceStream;
  12600. ScopedPointer <InputStream> streamToDelete;
  12601. const int64 uncompressedStreamLength;
  12602. const bool noWrap;
  12603. bool isEof;
  12604. int activeBufferSize;
  12605. int64 originalSourcePos, currentPos;
  12606. HeapBlock <uint8> buffer;
  12607. ScopedPointer <GZIPDecompressHelper> helper;
  12608. GZIPDecompressorInputStream (const GZIPDecompressorInputStream&);
  12609. GZIPDecompressorInputStream& operator= (const GZIPDecompressorInputStream&);
  12610. };
  12611. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12612. /*** End of inlined file: juce_GZIPDecompressorInputStream.h ***/
  12613. #endif
  12614. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  12615. #endif
  12616. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  12617. #endif
  12618. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12619. /*** Start of inlined file: juce_MemoryInputStream.h ***/
  12620. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12621. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12622. /**
  12623. Allows a block of data and to be accessed as a stream.
  12624. This can either be used to refer to a shared block of memory, or can make its
  12625. own internal copy of the data when the MemoryInputStream is created.
  12626. */
  12627. class JUCE_API MemoryInputStream : public InputStream
  12628. {
  12629. public:
  12630. /** Creates a MemoryInputStream.
  12631. @param sourceData the block of data to use as the stream's source
  12632. @param sourceDataSize the number of bytes in the source data block
  12633. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  12634. the source data, so this data shouldn't be changed
  12635. for the lifetime of the stream; if this parameter is
  12636. true, the stream will make its own copy of the
  12637. data and use that.
  12638. */
  12639. MemoryInputStream (const void* sourceData,
  12640. size_t sourceDataSize,
  12641. bool keepInternalCopyOfData);
  12642. /** Creates a MemoryInputStream.
  12643. @param data a block of data to use as the stream's source
  12644. @param keepInternalCopyOfData if false, the stream will just keep a reference to
  12645. the source data, so this data shouldn't be changed
  12646. for the lifetime of the stream; if this parameter is
  12647. true, the stream will make its own copy of the
  12648. data and use that.
  12649. */
  12650. MemoryInputStream (const MemoryBlock& data,
  12651. bool keepInternalCopyOfData);
  12652. /** Destructor. */
  12653. ~MemoryInputStream();
  12654. int64 getPosition();
  12655. bool setPosition (int64 pos);
  12656. int64 getTotalLength();
  12657. bool isExhausted();
  12658. int read (void* destBuffer, int maxBytesToRead);
  12659. juce_UseDebuggingNewOperator
  12660. private:
  12661. const char* data;
  12662. size_t dataSize, position;
  12663. MemoryBlock internalCopy;
  12664. MemoryInputStream (const MemoryInputStream&);
  12665. MemoryInputStream& operator= (const MemoryInputStream&);
  12666. };
  12667. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12668. /*** End of inlined file: juce_MemoryInputStream.h ***/
  12669. #endif
  12670. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12671. /*** Start of inlined file: juce_MemoryOutputStream.h ***/
  12672. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12673. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12674. /** Writes data to an internal memory buffer, which grows as required.
  12675. The data that was written into the stream can then be accessed later as
  12676. a contiguous block of memory.
  12677. */
  12678. class JUCE_API MemoryOutputStream : public OutputStream
  12679. {
  12680. public:
  12681. /** Creates a memory stream ready for writing into.
  12682. @param initialSize the intial amount of space to allocate for writing into
  12683. @param granularity the increments by which the internal storage will be increased
  12684. @param memoryBlockToWriteTo if this is non-zero, then this block will be used as the
  12685. place that the data gets stored. If it's zero, the stream
  12686. will allocate its own storage internally, which you can
  12687. access using getData() and getDataSize()
  12688. */
  12689. MemoryOutputStream (size_t initialSize = 256,
  12690. size_t granularity = 256,
  12691. MemoryBlock* memoryBlockToWriteTo = 0);
  12692. /** Destructor.
  12693. This will free any data that was written to it.
  12694. */
  12695. ~MemoryOutputStream();
  12696. /** Returns a pointer to the data that has been written to the stream.
  12697. @see getDataSize
  12698. */
  12699. const char* getData() const throw();
  12700. /** Returns the number of bytes of data that have been written to the stream.
  12701. @see getData
  12702. */
  12703. size_t getDataSize() const throw() { return size; }
  12704. /** Resets the stream, clearing any data that has been written to it so far. */
  12705. void reset() throw();
  12706. /** Returns a String created from the (UTF8) data that has been written to the stream. */
  12707. const String toUTF8() const;
  12708. void flush();
  12709. bool write (const void* buffer, int howMany);
  12710. int64 getPosition() { return position; }
  12711. bool setPosition (int64 newPosition);
  12712. juce_UseDebuggingNewOperator
  12713. private:
  12714. MemoryBlock* data;
  12715. ScopedPointer <MemoryBlock> dataToDelete;
  12716. size_t position, size, blockSize;
  12717. MemoryOutputStream (const MemoryOutputStream&);
  12718. MemoryOutputStream& operator= (const MemoryOutputStream&);
  12719. };
  12720. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12721. /*** End of inlined file: juce_MemoryOutputStream.h ***/
  12722. #endif
  12723. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  12724. #endif
  12725. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12726. /*** Start of inlined file: juce_SubregionStream.h ***/
  12727. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12728. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12729. /** Wraps another input stream, and reads from a specific part of it.
  12730. This lets you take a subsection of a stream and present it as an entire
  12731. stream in its own right.
  12732. */
  12733. class JUCE_API SubregionStream : public InputStream
  12734. {
  12735. public:
  12736. /** Creates a SubregionStream from an input source.
  12737. @param sourceStream the source stream to read from
  12738. @param startPositionInSourceStream this is the position in the source stream that
  12739. corresponds to position 0 in this stream
  12740. @param lengthOfSourceStream this specifies the maximum number of bytes
  12741. from the source stream that will be passed through
  12742. by this stream. When the position of this stream
  12743. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  12744. If the length passed in here is greater than the length
  12745. of the source stream (as returned by getTotalLength()),
  12746. then the smaller value will be used.
  12747. Passing a negative value for this parameter means it
  12748. will keep reading until the source's end-of-stream.
  12749. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  12750. deleted by this object when it is itself deleted.
  12751. */
  12752. SubregionStream (InputStream* sourceStream,
  12753. int64 startPositionInSourceStream,
  12754. int64 lengthOfSourceStream,
  12755. bool deleteSourceWhenDestroyed);
  12756. /** Destructor.
  12757. This may also delete the source stream, if that option was chosen when the
  12758. buffered stream was created.
  12759. */
  12760. ~SubregionStream();
  12761. int64 getTotalLength();
  12762. int64 getPosition();
  12763. bool setPosition (int64 newPosition);
  12764. int read (void* destBuffer, int maxBytesToRead);
  12765. bool isExhausted();
  12766. juce_UseDebuggingNewOperator
  12767. private:
  12768. InputStream* const source;
  12769. ScopedPointer <InputStream> sourceToDelete;
  12770. const int64 startPositionInSourceStream, lengthOfSourceStream;
  12771. SubregionStream (const SubregionStream&);
  12772. SubregionStream& operator= (const SubregionStream&);
  12773. };
  12774. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12775. /*** End of inlined file: juce_SubregionStream.h ***/
  12776. #endif
  12777. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  12778. #endif
  12779. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12780. /*** Start of inlined file: juce_LocalisedStrings.h ***/
  12781. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12782. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12783. /** Used in the same way as the T(text) macro, this will attempt to translate a
  12784. string into a localised version using the LocalisedStrings class.
  12785. @see LocalisedStrings
  12786. */
  12787. #define TRANS(stringLiteral) \
  12788. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  12789. /**
  12790. Used to convert strings to localised foreign-language versions.
  12791. This is basically a look-up table of strings and their translated equivalents.
  12792. It can be loaded from a text file, so that you can supply a set of localised
  12793. versions of strings that you use in your app.
  12794. To use it in your code, simply call the translate() method on each string that
  12795. might have foreign versions, and if none is found, the method will just return
  12796. the original string.
  12797. The translation file should start with some lines specifying a description of
  12798. the language it contains, and also a list of ISO country codes where it might
  12799. be appropriate to use the file. After that, each line of the file should contain
  12800. a pair of quoted strings with an '=' sign.
  12801. E.g. for a french translation, the file might be:
  12802. @code
  12803. language: French
  12804. countries: fr be mc ch lu
  12805. "hello" = "bonjour"
  12806. "goodbye" = "au revoir"
  12807. @endcode
  12808. If the strings need to contain a quote character, they can use '\"' instead, and
  12809. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  12810. (you can use this to add comments).
  12811. Note that this is a singleton class, so don't create or destroy the object directly.
  12812. There's also a TRANS(text) macro defined to make it easy to use the this.
  12813. E.g. @code
  12814. printSomething (TRANS("hello"));
  12815. @endcode
  12816. This macro is used in the Juce classes themselves, so your application has a chance to
  12817. intercept and translate any internal Juce text strings that might be shown. (You can easily
  12818. get a list of all the messages by searching for the TRANS() macro in the Juce source
  12819. code).
  12820. */
  12821. class JUCE_API LocalisedStrings
  12822. {
  12823. public:
  12824. /** Creates a set of translations from the text of a translation file.
  12825. When you create one of these, you can call setCurrentMappings() to make it
  12826. the set of mappings that the system's using.
  12827. */
  12828. LocalisedStrings (const String& fileContents);
  12829. /** Creates a set of translations from a 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 File& fileToLoad);
  12834. /** Destructor. */
  12835. ~LocalisedStrings();
  12836. /** Selects the current set of mappings to be used by the system.
  12837. The object you pass in will be automatically deleted when no longer needed, so
  12838. don't keep a pointer to it. You can also pass in zero to remove the current
  12839. mappings.
  12840. See also the TRANS() macro, which uses the current set to do its translation.
  12841. @see translateWithCurrentMappings
  12842. */
  12843. static void setCurrentMappings (LocalisedStrings* newTranslations);
  12844. /** Returns the currently selected set of mappings.
  12845. This is the object that was last passed to setCurrentMappings(). It may
  12846. be 0 if none has been created.
  12847. */
  12848. static LocalisedStrings* getCurrentMappings();
  12849. /** Tries to translate a string using the currently selected set of mappings.
  12850. If no mapping has been set, or if the mapping doesn't contain a translation
  12851. for the string, this will just return the original string.
  12852. See also the TRANS() macro, which uses this method to do its translation.
  12853. @see setCurrentMappings, getCurrentMappings
  12854. */
  12855. static const String translateWithCurrentMappings (const String& text);
  12856. /** Tries to translate a string using the currently selected set of mappings.
  12857. If no mapping has been set, or if the mapping doesn't contain a translation
  12858. for the string, this will just return the original string.
  12859. See also the TRANS() macro, which uses this method to do its translation.
  12860. @see setCurrentMappings, getCurrentMappings
  12861. */
  12862. static const String translateWithCurrentMappings (const char* text);
  12863. /** Attempts to look up a string and return its localised version.
  12864. If the string isn't found in the list, the original string will be returned.
  12865. */
  12866. const String translate (const String& text) const;
  12867. /** Returns the name of the language specified in the translation file.
  12868. This is specified in the file using a line starting with "language:", e.g.
  12869. @code
  12870. language: german
  12871. @endcode
  12872. */
  12873. const String getLanguageName() const { return languageName; }
  12874. /** Returns the list of suitable country codes listed in the translation file.
  12875. These is specified in the file using a line starting with "countries:", e.g.
  12876. @code
  12877. countries: fr be mc ch lu
  12878. @endcode
  12879. The country codes are supposed to be 2-character ISO complient codes.
  12880. */
  12881. const StringArray getCountryCodes() const { return countryCodes; }
  12882. /** Indicates whether to use a case-insensitive search when looking up a string.
  12883. This defaults to true.
  12884. */
  12885. void setIgnoresCase (const bool shouldIgnoreCase);
  12886. juce_UseDebuggingNewOperator
  12887. private:
  12888. String languageName;
  12889. StringArray countryCodes;
  12890. StringPairArray translations;
  12891. void loadFromText (const String& fileContents);
  12892. };
  12893. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12894. /*** End of inlined file: juce_LocalisedStrings.h ***/
  12895. #endif
  12896. #ifndef __JUCE_STRING_JUCEHEADER__
  12897. #endif
  12898. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  12899. #endif
  12900. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  12901. #endif
  12902. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  12903. #endif
  12904. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  12905. /*** Start of inlined file: juce_XmlDocument.h ***/
  12906. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  12907. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  12908. /**
  12909. Parses a text-based XML document and creates an XmlElement object from it.
  12910. The parser will parse DTDs to load external entities but won't
  12911. check the document for validity against the DTD.
  12912. e.g.
  12913. @code
  12914. XmlDocument myDocument (File ("myfile.xml"));
  12915. XmlElement* mainElement = myDocument.getDocumentElement();
  12916. if (mainElement == 0)
  12917. {
  12918. String error = myDocument.getLastParseError();
  12919. }
  12920. else
  12921. {
  12922. ..use the element
  12923. }
  12924. @endcode
  12925. @see XmlElement
  12926. */
  12927. class JUCE_API XmlDocument
  12928. {
  12929. public:
  12930. /** Creates an XmlDocument from the xml text.
  12931. The text doesn't actually get parsed until the getDocumentElement() method is
  12932. called.
  12933. */
  12934. XmlDocument (const String& documentText);
  12935. /** Creates an XmlDocument from a file.
  12936. The text doesn't actually get parsed until the getDocumentElement() method is
  12937. called.
  12938. */
  12939. XmlDocument (const File& file);
  12940. /** Destructor. */
  12941. ~XmlDocument();
  12942. /** Creates an XmlElement object to represent the main document node.
  12943. This method will do the actual parsing of the text, and if there's a
  12944. parse error, it may returns 0 (and you can find out the error using
  12945. the getLastParseError() method).
  12946. @param onlyReadOuterDocumentElement if true, the parser will only read the
  12947. first section of the file, and will only
  12948. return the outer document element - this
  12949. allows quick checking of large files to
  12950. see if they contain the correct type of
  12951. tag, without having to parse the entire file
  12952. @returns a new XmlElement which the caller will need to delete, or null if
  12953. there was an error.
  12954. @see getLastParseError
  12955. */
  12956. XmlElement* getDocumentElement (const bool onlyReadOuterDocumentElement = false);
  12957. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  12958. @returns the error, or an empty string if there was no error.
  12959. */
  12960. const String& getLastParseError() const throw();
  12961. /** Sets an input source object to use for parsing documents that reference external entities.
  12962. If the document has been created from a file, this probably won't be needed, but
  12963. if you're parsing some text and there might be a DTD that references external
  12964. files, you may need to create a custom input source that can retrieve the
  12965. other files it needs.
  12966. The object that is passed-in will be deleted automatically when no longer needed.
  12967. @see InputSource
  12968. */
  12969. void setInputSource (InputSource* const newSource) throw();
  12970. /** Sets a flag to change the treatment of empty text elements.
  12971. If this is true (the default state), then any text elements that contain only
  12972. whitespace characters will be ingored during parsing. If you need to catch
  12973. whitespace-only text, then you should set this to false before calling the
  12974. getDocumentElement() method.
  12975. */
  12976. void setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw();
  12977. juce_UseDebuggingNewOperator
  12978. private:
  12979. String originalText;
  12980. const juce_wchar* input;
  12981. bool outOfData, errorOccurred;
  12982. bool identifierLookupTable [128];
  12983. String lastError, dtdText;
  12984. StringArray tokenisedDTD;
  12985. bool needToLoadDTD, ignoreEmptyTextElements;
  12986. ScopedPointer <InputSource> inputSource;
  12987. void setLastError (const String& desc, const bool carryOn);
  12988. void skipHeader();
  12989. void skipNextWhiteSpace();
  12990. juce_wchar readNextChar() throw();
  12991. XmlElement* readNextElement (const bool alsoParseSubElements);
  12992. void readChildElements (XmlElement* parent);
  12993. int findNextTokenLength() throw();
  12994. void readQuotedString (String& result);
  12995. void readEntity (String& result);
  12996. static bool isXmlIdentifierCharSlow (juce_wchar c) throw();
  12997. bool isXmlIdentifierChar (juce_wchar c) const throw();
  12998. const String getFileContents (const String& filename) const;
  12999. const String expandEntity (const String& entity);
  13000. const String expandExternalEntity (const String& entity);
  13001. const String getParameterEntity (const String& entity);
  13002. XmlDocument (const XmlDocument&);
  13003. XmlDocument& operator= (const XmlDocument&);
  13004. };
  13005. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  13006. /*** End of inlined file: juce_XmlDocument.h ***/
  13007. #endif
  13008. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  13009. #endif
  13010. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  13011. #endif
  13012. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13013. /*** Start of inlined file: juce_InterProcessLock.h ***/
  13014. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13015. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13016. /**
  13017. Acts as a critical section which processes can use to block each other.
  13018. @see CriticalSection
  13019. */
  13020. class JUCE_API InterProcessLock
  13021. {
  13022. public:
  13023. /** Creates a lock object.
  13024. @param name a name that processes will use to identify this lock object
  13025. */
  13026. explicit InterProcessLock (const String& name);
  13027. /** Destructor.
  13028. This will also release the lock if it's currently held by this process.
  13029. */
  13030. ~InterProcessLock();
  13031. /** Attempts to lock the critical section.
  13032. @param timeOutMillisecs how many milliseconds to wait if the lock
  13033. is already held by another process - a value of
  13034. 0 will return immediately, negative values will wait
  13035. forever
  13036. @returns true if the lock could be gained within the timeout period, or
  13037. false if the timeout expired.
  13038. */
  13039. bool enter (int timeOutMillisecs = -1);
  13040. /** Releases the lock if it's currently held by this process.
  13041. */
  13042. void exit();
  13043. /**
  13044. Automatically locks and unlocks an InterProcessLock object.
  13045. This works like a ScopedLock, but using an InterprocessLock rather than
  13046. a CriticalSection.
  13047. @see ScopedLock
  13048. */
  13049. class ScopedLockType
  13050. {
  13051. public:
  13052. /** Creates a scoped lock.
  13053. As soon as it is created, this will lock the InterProcessLock, and
  13054. when the ScopedLockType object is deleted, the InterProcessLock will
  13055. be unlocked.
  13056. Note that since an InterprocessLock can fail due to errors, you should check
  13057. isLocked() to make sure that the lock was successful before using it.
  13058. Make sure this object is created and deleted by the same thread,
  13059. otherwise there are no guarantees what will happen! Best just to use it
  13060. as a local stack object, rather than creating one with the new() operator.
  13061. */
  13062. explicit ScopedLockType (InterProcessLock& lock) : lock_ (lock) { lockWasSuccessful = lock.enter(); }
  13063. /** Destructor.
  13064. The InterProcessLock will be unlocked when the destructor is called.
  13065. Make sure this object is created and deleted by the same thread,
  13066. otherwise there are no guarantees what will happen!
  13067. */
  13068. inline ~ScopedLockType() { lock_.exit(); }
  13069. /** Returns true if the InterProcessLock was successfully locked. */
  13070. bool isLocked() const throw() { return lockWasSuccessful; }
  13071. private:
  13072. InterProcessLock& lock_;
  13073. bool lockWasSuccessful;
  13074. ScopedLockType (const ScopedLockType&);
  13075. ScopedLockType& operator= (const ScopedLockType&);
  13076. };
  13077. juce_UseDebuggingNewOperator
  13078. private:
  13079. class Pimpl;
  13080. friend class ScopedPointer <Pimpl>;
  13081. ScopedPointer <Pimpl> pimpl;
  13082. CriticalSection lock;
  13083. String name;
  13084. InterProcessLock (const InterProcessLock&);
  13085. InterProcessLock& operator= (const InterProcessLock&);
  13086. };
  13087. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13088. /*** End of inlined file: juce_InterProcessLock.h ***/
  13089. #endif
  13090. #ifndef __JUCE_PROCESS_JUCEHEADER__
  13091. /*** Start of inlined file: juce_Process.h ***/
  13092. #ifndef __JUCE_PROCESS_JUCEHEADER__
  13093. #define __JUCE_PROCESS_JUCEHEADER__
  13094. /** Represents the current executable's process.
  13095. This contains methods for controlling the current application at the
  13096. process-level.
  13097. @see Thread, JUCEApplication
  13098. */
  13099. class JUCE_API Process
  13100. {
  13101. public:
  13102. enum ProcessPriority
  13103. {
  13104. LowPriority = 0,
  13105. NormalPriority = 1,
  13106. HighPriority = 2,
  13107. RealtimePriority = 3
  13108. };
  13109. /** Changes the current process's priority.
  13110. @param priority the process priority, where
  13111. 0=low, 1=normal, 2=high, 3=realtime
  13112. */
  13113. static void setPriority (const ProcessPriority priority);
  13114. /** Kills the current process immediately.
  13115. This is an emergency process terminator that kills the application
  13116. immediately - it's intended only for use only when something goes
  13117. horribly wrong.
  13118. @see JUCEApplication::quit
  13119. */
  13120. static void terminate();
  13121. /** Returns true if this application process is the one that the user is
  13122. currently using.
  13123. */
  13124. static bool isForegroundProcess();
  13125. /** Raises the current process's privilege level.
  13126. Does nothing if this isn't supported by the current OS, or if process
  13127. privilege level is fixed.
  13128. */
  13129. static void raisePrivilege();
  13130. /** Lowers 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 lowerPrivilege();
  13135. /** Returns true if this process is being hosted by a debugger.
  13136. */
  13137. static bool JUCE_CALLTYPE isRunningUnderDebugger();
  13138. private:
  13139. Process();
  13140. Process (const Process&);
  13141. Process& operator= (const Process&);
  13142. };
  13143. #endif // __JUCE_PROCESS_JUCEHEADER__
  13144. /*** End of inlined file: juce_Process.h ***/
  13145. #endif
  13146. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  13147. /*** Start of inlined file: juce_ReadWriteLock.h ***/
  13148. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  13149. #define __JUCE_READWRITELOCK_JUCEHEADER__
  13150. /*** Start of inlined file: juce_WaitableEvent.h ***/
  13151. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  13152. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  13153. /**
  13154. Allows threads to wait for events triggered by other threads.
  13155. A thread can call wait() on a WaitableObject, and this will suspend the
  13156. calling thread until another thread wakes it up by calling the signal()
  13157. method.
  13158. */
  13159. class JUCE_API WaitableEvent
  13160. {
  13161. public:
  13162. /** Creates a WaitableEvent object.
  13163. @param manualReset If this is false, the event will be reset automatically when the wait()
  13164. method is called. If manualReset is true, then once the event is signalled,
  13165. the only way to reset it will be by calling the reset() method.
  13166. */
  13167. WaitableEvent (bool manualReset = false) throw();
  13168. /** Destructor.
  13169. If other threads are waiting on this object when it gets deleted, this
  13170. can cause nasty errors, so be careful!
  13171. */
  13172. ~WaitableEvent() throw();
  13173. /** Suspends the calling thread until the event has been signalled.
  13174. This will wait until the object's signal() method is called by another thread,
  13175. or until the timeout expires.
  13176. After the event has been signalled, this method will return true and if manualReset
  13177. was set to false in the WaitableEvent's constructor, then the event will be reset.
  13178. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  13179. value will cause it to wait forever.
  13180. @returns true if the object has been signalled, false if the timeout expires first.
  13181. @see signal, reset
  13182. */
  13183. bool wait (int timeOutMilliseconds = -1) const throw();
  13184. /** Wakes up any threads that are currently waiting on this object.
  13185. If signal() is called when nothing is waiting, the next thread to call wait()
  13186. will return immediately and reset the signal.
  13187. @see wait, reset
  13188. */
  13189. void signal() const throw();
  13190. /** Resets the event to an unsignalled state.
  13191. If it's not already signalled, this does nothing.
  13192. */
  13193. void reset() const throw();
  13194. juce_UseDebuggingNewOperator
  13195. private:
  13196. void* internal;
  13197. WaitableEvent (const WaitableEvent&);
  13198. WaitableEvent& operator= (const WaitableEvent&);
  13199. };
  13200. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  13201. /*** End of inlined file: juce_WaitableEvent.h ***/
  13202. /*** Start of inlined file: juce_Thread.h ***/
  13203. #ifndef __JUCE_THREAD_JUCEHEADER__
  13204. #define __JUCE_THREAD_JUCEHEADER__
  13205. /**
  13206. Encapsulates a thread.
  13207. Subclasses derive from Thread and implement the run() method, in which they
  13208. do their business. The thread can then be started with the startThread() method
  13209. and controlled with various other methods.
  13210. This class also contains some thread-related static methods, such
  13211. as sleep(), yield(), getCurrentThreadId() etc.
  13212. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  13213. MessageManagerLock
  13214. */
  13215. class JUCE_API Thread
  13216. {
  13217. public:
  13218. /**
  13219. Creates a thread.
  13220. When first created, the thread is not running. Use the startThread()
  13221. method to start it.
  13222. */
  13223. explicit Thread (const String& threadName);
  13224. /** Destructor.
  13225. Deleting a Thread object that is running will only give the thread a
  13226. brief opportunity to stop itself cleanly, so it's recommended that you
  13227. should always call stopThread() with a decent timeout before deleting,
  13228. to avoid the thread being forcibly killed (which is a Bad Thing).
  13229. */
  13230. virtual ~Thread();
  13231. /** Must be implemented to perform the thread's actual code.
  13232. Remember that the thread must regularly check the threadShouldExit()
  13233. method whilst running, and if this returns true it should return from
  13234. the run() method as soon as possible to avoid being forcibly killed.
  13235. @see threadShouldExit, startThread
  13236. */
  13237. virtual void run() = 0;
  13238. // Thread control functions..
  13239. /** Starts the thread running.
  13240. This will start the thread's run() method.
  13241. (if it's already started, startThread() won't do anything).
  13242. @see stopThread
  13243. */
  13244. void startThread();
  13245. /** Starts the thread with a given priority.
  13246. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  13247. If the thread is already running, its priority will be changed.
  13248. @see startThread, setPriority
  13249. */
  13250. void startThread (int priority);
  13251. /** Attempts to stop the thread running.
  13252. This method will cause the threadShouldExit() method to return true
  13253. and call notify() in case the thread is currently waiting.
  13254. Hopefully the thread will then respond to this by exiting cleanly, and
  13255. the stopThread method will wait for a given time-period for this to
  13256. happen.
  13257. If the thread is stuck and fails to respond after the time-out, it gets
  13258. forcibly killed, which is a very bad thing to happen, as it could still
  13259. be holding locks, etc. which are needed by other parts of your program.
  13260. @param timeOutMilliseconds The number of milliseconds to wait for the
  13261. thread to finish before killing it by force. A negative
  13262. value in here will wait forever.
  13263. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  13264. */
  13265. void stopThread (int timeOutMilliseconds);
  13266. /** Returns true if the thread is currently active */
  13267. bool isThreadRunning() const;
  13268. /** Sets a flag to tell the thread it should stop.
  13269. Calling this means that the threadShouldExit() method will then return true.
  13270. The thread should be regularly checking this to see whether it should exit.
  13271. If your thread makes use of wait(), you might want to call notify() after calling
  13272. this method, to interrupt any waits that might be in progress, and allow it
  13273. to reach a point where it can exit.
  13274. @see threadShouldExit
  13275. @see waitForThreadToExit
  13276. */
  13277. void signalThreadShouldExit();
  13278. /** Checks whether the thread has been told to stop running.
  13279. Threads need to check this regularly, and if it returns true, they should
  13280. return from their run() method at the first possible opportunity.
  13281. @see signalThreadShouldExit
  13282. */
  13283. inline bool threadShouldExit() const { return threadShouldExit_; }
  13284. /** Waits for the thread to stop.
  13285. This will waits until isThreadRunning() is false or until a timeout expires.
  13286. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  13287. is less than zero, it will wait forever.
  13288. @returns true if the thread exits, or false if the timeout expires first.
  13289. */
  13290. bool waitForThreadToExit (int timeOutMilliseconds) const;
  13291. /** Changes the thread's priority.
  13292. May return false if for some reason the priority can't be changed.
  13293. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  13294. of 5 is normal.
  13295. */
  13296. bool setPriority (int priority);
  13297. /** Changes the priority of the caller thread.
  13298. Similar to setPriority(), but this static method acts on the caller thread.
  13299. May return false if for some reason the priority can't be changed.
  13300. @see setPriority
  13301. */
  13302. static bool setCurrentThreadPriority (int priority);
  13303. /** Sets the affinity mask for the thread.
  13304. This will only have an effect next time the thread is started - i.e. if the
  13305. thread is already running when called, it'll have no effect.
  13306. @see setCurrentThreadAffinityMask
  13307. */
  13308. void setAffinityMask (uint32 affinityMask);
  13309. /** Changes the affinity mask for the caller thread.
  13310. This will change the affinity mask for the thread that calls this static method.
  13311. @see setAffinityMask
  13312. */
  13313. static void setCurrentThreadAffinityMask (uint32 affinityMask);
  13314. // this can be called from any thread that needs to pause..
  13315. static void JUCE_CALLTYPE sleep (int milliseconds);
  13316. /** Yields the calling thread's current time-slot. */
  13317. static void JUCE_CALLTYPE yield();
  13318. /** Makes the thread wait for a notification.
  13319. This puts the thread to sleep until either the timeout period expires, or
  13320. another thread calls the notify() method to wake it up.
  13321. A negative time-out value means that the method will wait indefinitely.
  13322. @returns true if the event has been signalled, false if the timeout expires.
  13323. */
  13324. bool wait (int timeOutMilliseconds) const;
  13325. /** Wakes up the thread.
  13326. If the thread has called the wait() method, this will wake it up.
  13327. @see wait
  13328. */
  13329. void notify() const;
  13330. /** A value type used for thread IDs.
  13331. @see getCurrentThreadId(), getThreadId()
  13332. */
  13333. typedef void* ThreadID;
  13334. /** Returns an id that identifies the caller thread.
  13335. To find the ID of a particular thread object, use getThreadId().
  13336. @returns a unique identifier that identifies the calling thread.
  13337. @see getThreadId
  13338. */
  13339. static ThreadID getCurrentThreadId();
  13340. /** Finds the thread object that is currently running.
  13341. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  13342. object associated with them, so this will return 0.
  13343. */
  13344. static Thread* getCurrentThread();
  13345. /** Returns the ID of this thread.
  13346. That means the ID of this thread object - not of the thread that's calling the method.
  13347. This can change when the thread is started and stopped, and will be invalid if the
  13348. thread's not actually running.
  13349. @see getCurrentThreadId
  13350. */
  13351. ThreadID getThreadId() const throw() { return threadId_; }
  13352. /** Returns the name of the thread.
  13353. This is the name that gets set in the constructor.
  13354. */
  13355. const String getThreadName() const { return threadName_; }
  13356. /** Returns the number of currently-running threads.
  13357. @returns the number of Thread objects known to be currently running.
  13358. @see stopAllThreads
  13359. */
  13360. static int getNumRunningThreads();
  13361. /** Tries to stop all currently-running threads.
  13362. This will attempt to stop all the threads known to be running at the moment.
  13363. */
  13364. static void stopAllThreads (int timeoutInMillisecs);
  13365. juce_UseDebuggingNewOperator
  13366. private:
  13367. const String threadName_;
  13368. void* volatile threadHandle_;
  13369. CriticalSection startStopLock;
  13370. WaitableEvent startSuspensionEvent_, defaultEvent_;
  13371. int threadPriority_;
  13372. ThreadID threadId_;
  13373. uint32 affinityMask_;
  13374. bool volatile threadShouldExit_;
  13375. friend void JUCE_API juce_threadEntryPoint (void*);
  13376. static void threadEntryPoint (Thread* thread);
  13377. static Array<Thread*> runningThreads;
  13378. static CriticalSection runningThreadsLock;
  13379. Thread (const Thread&);
  13380. Thread& operator= (const Thread&);
  13381. };
  13382. #endif // __JUCE_THREAD_JUCEHEADER__
  13383. /*** End of inlined file: juce_Thread.h ***/
  13384. /**
  13385. A critical section that allows multiple simultaneous readers.
  13386. Features of this type of lock are:
  13387. - Multiple readers can hold the lock at the same time, but only one writer
  13388. can hold it at once.
  13389. - Writers trying to gain the lock will be blocked until all readers and writers
  13390. have released it
  13391. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  13392. blocked until the writer has obtained and released it
  13393. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  13394. there are no other readers
  13395. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  13396. - Recursive locking is supported.
  13397. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  13398. */
  13399. class JUCE_API ReadWriteLock
  13400. {
  13401. public:
  13402. /**
  13403. Creates a ReadWriteLock object.
  13404. */
  13405. ReadWriteLock() throw();
  13406. /** Destructor.
  13407. If the object is deleted whilst locked, any subsequent behaviour
  13408. is unpredictable.
  13409. */
  13410. ~ReadWriteLock() throw();
  13411. /** Locks this object for reading.
  13412. Multiple threads can simulaneously lock the object for reading, but if another
  13413. thread has it locked for writing, then this will block until it releases the
  13414. lock.
  13415. @see exitRead, ScopedReadLock
  13416. */
  13417. void enterRead() const throw();
  13418. /** Releases the read-lock.
  13419. If the caller thread hasn't got the lock, this can have unpredictable results.
  13420. If the enterRead() method has been called multiple times by the thread, each
  13421. call must be matched by a call to exitRead() before other threads will be allowed
  13422. to take over the lock.
  13423. @see enterRead, ScopedReadLock
  13424. */
  13425. void exitRead() const throw();
  13426. /** Locks this object for writing.
  13427. This will block until any other threads that have it locked for reading or
  13428. writing have released their lock.
  13429. @see exitWrite, ScopedWriteLock
  13430. */
  13431. void enterWrite() const throw();
  13432. /** Tries to lock this object for writing.
  13433. This is like enterWrite(), but doesn't block - it returns true if it manages
  13434. to obtain the lock.
  13435. @see enterWrite
  13436. */
  13437. bool tryEnterWrite() const throw();
  13438. /** Releases the write-lock.
  13439. If the caller thread hasn't got the lock, this can have unpredictable results.
  13440. If the enterWrite() method has been called multiple times by the thread, each
  13441. call must be matched by a call to exit() before other threads will be allowed
  13442. to take over the lock.
  13443. @see enterWrite, ScopedWriteLock
  13444. */
  13445. void exitWrite() const throw();
  13446. juce_UseDebuggingNewOperator
  13447. private:
  13448. CriticalSection accessLock;
  13449. WaitableEvent waitEvent;
  13450. mutable int numWaitingWriters, numWriters;
  13451. mutable Thread::ThreadID writerThreadId;
  13452. mutable Array <Thread::ThreadID> readerThreads;
  13453. ReadWriteLock (const ReadWriteLock&);
  13454. ReadWriteLock& operator= (const ReadWriteLock&);
  13455. };
  13456. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  13457. /*** End of inlined file: juce_ReadWriteLock.h ***/
  13458. #endif
  13459. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  13460. #endif
  13461. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13462. /*** Start of inlined file: juce_ScopedReadLock.h ***/
  13463. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13464. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13465. /**
  13466. Automatically locks and unlocks a ReadWriteLock object.
  13467. Use one of these as a local variable to control access to a ReadWriteLock.
  13468. e.g. @code
  13469. ReadWriteLock myLock;
  13470. for (;;)
  13471. {
  13472. const ScopedReadLock myScopedLock (myLock);
  13473. // myLock is now locked
  13474. ...do some stuff...
  13475. // myLock gets unlocked here.
  13476. }
  13477. @endcode
  13478. @see ReadWriteLock, ScopedWriteLock
  13479. */
  13480. class JUCE_API ScopedReadLock
  13481. {
  13482. public:
  13483. /** Creates a ScopedReadLock.
  13484. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  13485. when the ScopedReadLock object is deleted, the ReadWriteLock will
  13486. be unlocked.
  13487. Make sure this object is created and deleted by the same thread,
  13488. otherwise there are no guarantees what will happen! Best just to use it
  13489. as a local stack object, rather than creating one with the new() operator.
  13490. */
  13491. inline explicit ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  13492. /** Destructor.
  13493. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  13494. Make sure this object is created and deleted by the same thread,
  13495. otherwise there are no guarantees what will happen!
  13496. */
  13497. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  13498. private:
  13499. const ReadWriteLock& lock_;
  13500. ScopedReadLock (const ScopedReadLock&);
  13501. ScopedReadLock& operator= (const ScopedReadLock&);
  13502. };
  13503. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13504. /*** End of inlined file: juce_ScopedReadLock.h ***/
  13505. #endif
  13506. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13507. /*** Start of inlined file: juce_ScopedTryLock.h ***/
  13508. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13509. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13510. /**
  13511. Automatically tries to lock and unlock a CriticalSection object.
  13512. Use one of these as a local variable to control access to a CriticalSection.
  13513. e.g. @code
  13514. CriticalSection myCriticalSection;
  13515. for (;;)
  13516. {
  13517. const ScopedTryLock myScopedTryLock (myCriticalSection);
  13518. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  13519. // should test this with the isLocked() method before doing your thread-unsafe
  13520. // action..
  13521. if (myScopedTryLock.isLocked())
  13522. {
  13523. ...do some stuff...
  13524. }
  13525. else
  13526. {
  13527. ..our attempt at locking failed because another thread had already locked it..
  13528. }
  13529. // myCriticalSection gets unlocked here (if it was locked)
  13530. }
  13531. @endcode
  13532. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  13533. */
  13534. class JUCE_API ScopedTryLock
  13535. {
  13536. public:
  13537. /** Creates a ScopedTryLock.
  13538. As soon as it is created, this will try to lock the CriticalSection, and
  13539. when the ScopedTryLock object is deleted, the CriticalSection will
  13540. be unlocked if the lock was successful.
  13541. Make sure this object is created and deleted by the same thread,
  13542. otherwise there are no guarantees what will happen! Best just to use it
  13543. as a local stack object, rather than creating one with the new() operator.
  13544. */
  13545. inline explicit ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  13546. /** Destructor.
  13547. The CriticalSection will be unlocked (if locked) when the destructor is called.
  13548. Make sure this object is created and deleted by the same thread,
  13549. otherwise there are no guarantees what will happen!
  13550. */
  13551. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  13552. /** Returns true if the CriticalSection was successfully locked. */
  13553. bool isLocked() const throw() { return lockWasSuccessful; }
  13554. private:
  13555. const CriticalSection& lock_;
  13556. const bool lockWasSuccessful;
  13557. ScopedTryLock (const ScopedTryLock&);
  13558. ScopedTryLock& operator= (const ScopedTryLock&);
  13559. };
  13560. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13561. /*** End of inlined file: juce_ScopedTryLock.h ***/
  13562. #endif
  13563. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13564. /*** Start of inlined file: juce_ScopedWriteLock.h ***/
  13565. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13566. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13567. /**
  13568. Automatically locks and unlocks a ReadWriteLock object.
  13569. Use one of these as a local variable to control access to a ReadWriteLock.
  13570. e.g. @code
  13571. ReadWriteLock myLock;
  13572. for (;;)
  13573. {
  13574. const ScopedWriteLock myScopedLock (myLock);
  13575. // myLock is now locked
  13576. ...do some stuff...
  13577. // myLock gets unlocked here.
  13578. }
  13579. @endcode
  13580. @see ReadWriteLock, ScopedReadLock
  13581. */
  13582. class JUCE_API ScopedWriteLock
  13583. {
  13584. public:
  13585. /** Creates a ScopedWriteLock.
  13586. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  13587. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  13588. be unlocked.
  13589. Make sure this object is created and deleted by the same thread,
  13590. otherwise there are no guarantees what will happen! Best just to use it
  13591. as a local stack object, rather than creating one with the new() operator.
  13592. */
  13593. inline explicit ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  13594. /** Destructor.
  13595. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  13596. Make sure this object is created and deleted by the same thread,
  13597. otherwise there are no guarantees what will happen!
  13598. */
  13599. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  13600. private:
  13601. const ReadWriteLock& lock_;
  13602. ScopedWriteLock (const ScopedWriteLock&);
  13603. ScopedWriteLock& operator= (const ScopedWriteLock&);
  13604. };
  13605. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13606. /*** End of inlined file: juce_ScopedWriteLock.h ***/
  13607. #endif
  13608. #ifndef __JUCE_THREAD_JUCEHEADER__
  13609. #endif
  13610. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  13611. /*** Start of inlined file: juce_ThreadPool.h ***/
  13612. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  13613. #define __JUCE_THREADPOOL_JUCEHEADER__
  13614. class ThreadPool;
  13615. class ThreadPoolThread;
  13616. /**
  13617. A task that is executed by a ThreadPool object.
  13618. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  13619. its threads.
  13620. The runJob() method needs to be implemented to do the task, and if the code that
  13621. does the work takes a significant time to run, it must keep checking the shouldExit()
  13622. method to see if something is trying to interrupt the job. If shouldExit() returns
  13623. true, the runJob() method must return immediately.
  13624. @see ThreadPool, Thread
  13625. */
  13626. class JUCE_API ThreadPoolJob
  13627. {
  13628. public:
  13629. /** Creates a thread pool job object.
  13630. After creating your job, add it to a thread pool with ThreadPool::addJob().
  13631. */
  13632. explicit ThreadPoolJob (const String& name);
  13633. /** Destructor. */
  13634. virtual ~ThreadPoolJob();
  13635. /** Returns the name of this job.
  13636. @see setJobName
  13637. */
  13638. const String getJobName() const;
  13639. /** Changes the job's name.
  13640. @see getJobName
  13641. */
  13642. void setJobName (const String& newName);
  13643. /** These are the values that can be returned by the runJob() method.
  13644. */
  13645. enum JobStatus
  13646. {
  13647. jobHasFinished = 0, /**< indicates that the job has finished and can be
  13648. removed from the pool. */
  13649. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  13650. should be automatically deleted by the pool. */
  13651. jobNeedsRunningAgain /**< indicates that the job would like to be called
  13652. again when a thread is free. */
  13653. };
  13654. /** Peforms the actual work that this job needs to do.
  13655. Your subclass must implement this method, in which is does its work.
  13656. If the code in this method takes a significant time to run, it must repeatedly check
  13657. the shouldExit() method to see if something is trying to interrupt the job.
  13658. If shouldExit() ever returns true, the runJob() method must return immediately.
  13659. If this method returns jobHasFinished, then the job will be removed from the pool
  13660. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  13661. pool and will get a chance to run again as soon as a thread is free.
  13662. @see shouldExit()
  13663. */
  13664. virtual JobStatus runJob() = 0;
  13665. /** Returns true if this job is currently running its runJob() method. */
  13666. bool isRunning() const { return isActive; }
  13667. /** Returns true if something is trying to interrupt this job and make it stop.
  13668. Your runJob() method must call this whenever it gets a chance, and if it ever
  13669. returns true, the runJob() method must return immediately.
  13670. @see signalJobShouldExit()
  13671. */
  13672. bool shouldExit() const { return shouldStop; }
  13673. /** Calling this will cause the shouldExit() method to return true, and the job
  13674. should (if it's been implemented correctly) stop as soon as possible.
  13675. @see shouldExit()
  13676. */
  13677. void signalJobShouldExit();
  13678. juce_UseDebuggingNewOperator
  13679. private:
  13680. friend class ThreadPool;
  13681. friend class ThreadPoolThread;
  13682. String jobName;
  13683. ThreadPool* pool;
  13684. bool shouldStop, isActive, shouldBeDeleted;
  13685. ThreadPoolJob (const ThreadPoolJob&);
  13686. ThreadPoolJob& operator= (const ThreadPoolJob&);
  13687. };
  13688. /**
  13689. A set of threads that will run a list of jobs.
  13690. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  13691. will be called by the next pooled thread that becomes free.
  13692. @see ThreadPoolJob, Thread
  13693. */
  13694. class JUCE_API ThreadPool
  13695. {
  13696. public:
  13697. /** Creates a thread pool.
  13698. Once you've created a pool, you can give it some things to do with the addJob()
  13699. method.
  13700. @param numberOfThreads the maximum number of actual threads to run.
  13701. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  13702. until there are some jobs to run. If false, then
  13703. all the threads will be fired-up immediately so that
  13704. they're ready for action
  13705. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  13706. inactive for this length of time, they will automatically
  13707. be stopped until more jobs come along and they're needed
  13708. */
  13709. ThreadPool (int numberOfThreads,
  13710. bool startThreadsOnlyWhenNeeded = true,
  13711. int stopThreadsWhenNotUsedTimeoutMs = 5000);
  13712. /** Destructor.
  13713. This will attempt to remove all the jobs before deleting, but if you want to
  13714. specify a timeout, you should call removeAllJobs() explicitly before deleting
  13715. the pool.
  13716. */
  13717. ~ThreadPool();
  13718. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  13719. for some kind of operation.
  13720. @see ThreadPool::removeAllJobs
  13721. */
  13722. class JUCE_API JobSelector
  13723. {
  13724. public:
  13725. virtual ~JobSelector() {}
  13726. /** Should return true if the specified thread matches your criteria for whatever
  13727. operation that this object is being used for.
  13728. Any implementation of this method must be extremely fast and thread-safe!
  13729. */
  13730. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  13731. };
  13732. /** Adds a job to the queue.
  13733. Once a job has been added, then the next time a thread is free, it will run
  13734. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  13735. runJob() method, the pool will either remove the job from the pool or add it to
  13736. the back of the queue to be run again.
  13737. */
  13738. void addJob (ThreadPoolJob* job);
  13739. /** Tries to remove a job from the pool.
  13740. If the job isn't yet running, this will simply remove it. If it is running, it
  13741. will wait for it to finish.
  13742. If the timeout period expires before the job finishes running, then the job will be
  13743. left in the pool and this will return false. It returns true if the job is sucessfully
  13744. stopped and removed.
  13745. @param job the job to remove
  13746. @param interruptIfRunning if true, then if the job is currently busy, its
  13747. ThreadPoolJob::signalJobShouldExit() method will be called to try
  13748. to interrupt it. If false, then if the job will be allowed to run
  13749. until it stops normally (or the timeout expires)
  13750. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  13751. before giving up and returning false
  13752. */
  13753. bool removeJob (ThreadPoolJob* job,
  13754. bool interruptIfRunning,
  13755. int timeOutMilliseconds);
  13756. /** Tries to remove all jobs from the pool.
  13757. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  13758. methods called to try to interrupt them
  13759. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  13760. before giving up and returning false
  13761. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  13762. they will simply be removed from the pool. Jobs that are already running when
  13763. this method is called can choose whether they should be deleted by
  13764. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  13765. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  13766. jobs should be removed. If it is zero, all jobs are removed
  13767. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  13768. expires while waiting for one or more jobs to stop
  13769. */
  13770. bool removeAllJobs (bool interruptRunningJobs,
  13771. int timeOutMilliseconds,
  13772. bool deleteInactiveJobs = false,
  13773. JobSelector* selectedJobsToRemove = 0);
  13774. /** Returns the number of jobs currently running or queued.
  13775. */
  13776. int getNumJobs() const;
  13777. /** Returns one of the jobs in the queue.
  13778. Note that this can be a very volatile list as jobs might be continuously getting shifted
  13779. around in the list, and this method may return 0 if the index is currently out-of-range.
  13780. */
  13781. ThreadPoolJob* getJob (int index) const;
  13782. /** Returns true if the given job is currently queued or running.
  13783. @see isJobRunning()
  13784. */
  13785. bool contains (const ThreadPoolJob* job) const;
  13786. /** Returns true if the given job is currently being run by a thread.
  13787. */
  13788. bool isJobRunning (const ThreadPoolJob* job) const;
  13789. /** Waits until a job has finished running and has been removed from the pool.
  13790. This will wait until the job is no longer in the pool - i.e. until its
  13791. runJob() method returns ThreadPoolJob::jobHasFinished.
  13792. If the timeout period expires before the job finishes, this will return false;
  13793. it returns true if the job has finished successfully.
  13794. */
  13795. bool waitForJobToFinish (const ThreadPoolJob* job,
  13796. int timeOutMilliseconds) const;
  13797. /** Returns a list of the names of all the jobs currently running or queued.
  13798. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  13799. */
  13800. const StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  13801. /** Changes the priority of all the threads.
  13802. This will call Thread::setPriority() for each thread in the pool.
  13803. May return false if for some reason the priority can't be changed.
  13804. */
  13805. bool setThreadPriorities (int newPriority);
  13806. juce_UseDebuggingNewOperator
  13807. private:
  13808. const int threadStopTimeout;
  13809. int priority;
  13810. class ThreadPoolThread;
  13811. OwnedArray <ThreadPoolThread> threads;
  13812. Array <ThreadPoolJob*> jobs;
  13813. CriticalSection lock;
  13814. uint32 lastJobEndTime;
  13815. WaitableEvent jobFinishedSignal;
  13816. friend class ThreadPoolThread;
  13817. bool runNextJob();
  13818. ThreadPool (const ThreadPool&);
  13819. ThreadPool& operator= (const ThreadPool&);
  13820. };
  13821. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  13822. /*** End of inlined file: juce_ThreadPool.h ***/
  13823. #endif
  13824. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13825. /*** Start of inlined file: juce_TimeSliceThread.h ***/
  13826. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13827. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13828. /**
  13829. Used by the TimeSliceThread class.
  13830. To register your class with a TimeSliceThread, derive from this class and
  13831. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  13832. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  13833. deleting your client!
  13834. @see TimeSliceThread
  13835. */
  13836. class JUCE_API TimeSliceClient
  13837. {
  13838. public:
  13839. /** Destructor. */
  13840. virtual ~TimeSliceClient() {}
  13841. /** Called back by a TimeSliceThread.
  13842. When you register this class with it, a TimeSliceThread will repeatedly call
  13843. this method.
  13844. The implementation of this method should use its time-slice to do something that's
  13845. quick - never block for longer than absolutely necessary.
  13846. @returns Your method should return true if it needs more time, or false if it's
  13847. not too busy and doesn't need calling back urgently. If all the thread's
  13848. clients indicate that they're not busy, then it'll save CPU by sleeping for
  13849. up to half a second in between callbacks. You can force the TimeSliceThread
  13850. to wake up and poll again immediately by calling its notify() method.
  13851. */
  13852. virtual bool useTimeSlice() = 0;
  13853. };
  13854. /**
  13855. A thread that keeps a list of clients, and calls each one in turn, giving them
  13856. all a chance to run some sort of short task.
  13857. @see TimeSliceClient, Thread
  13858. */
  13859. class JUCE_API TimeSliceThread : public Thread
  13860. {
  13861. public:
  13862. /**
  13863. Creates a TimeSliceThread.
  13864. When first created, the thread is not running. Use the startThread()
  13865. method to start it.
  13866. */
  13867. explicit TimeSliceThread (const String& threadName);
  13868. /** Destructor.
  13869. Deleting a Thread object that is running will only give the thread a
  13870. brief opportunity to stop itself cleanly, so it's recommended that you
  13871. should always call stopThread() with a decent timeout before deleting,
  13872. to avoid the thread being forcibly killed (which is a Bad Thing).
  13873. */
  13874. ~TimeSliceThread();
  13875. /** Adds a client to the list.
  13876. The client's callbacks will start immediately (possibly before the method
  13877. has returned).
  13878. */
  13879. void addTimeSliceClient (TimeSliceClient* client);
  13880. /** Removes a client from the list.
  13881. This method will make sure that all callbacks to the client have completely
  13882. finished before the method returns.
  13883. */
  13884. void removeTimeSliceClient (TimeSliceClient* client);
  13885. /** Returns the number of registered clients. */
  13886. int getNumClients() const;
  13887. /** Returns one of the registered clients. */
  13888. TimeSliceClient* getClient (int index) const;
  13889. /** @internal */
  13890. void run();
  13891. juce_UseDebuggingNewOperator
  13892. private:
  13893. CriticalSection callbackLock, listLock;
  13894. Array <TimeSliceClient*> clients;
  13895. int index;
  13896. TimeSliceClient* clientBeingCalled;
  13897. bool clientsChanged;
  13898. TimeSliceThread (const TimeSliceThread&);
  13899. TimeSliceThread& operator= (const TimeSliceThread&);
  13900. };
  13901. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13902. /*** End of inlined file: juce_TimeSliceThread.h ***/
  13903. #endif
  13904. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  13905. #endif
  13906. #endif
  13907. /*** End of inlined file: juce_core_includes.h ***/
  13908. // if you're compiling a command-line app, you might want to just include the core headers,
  13909. // so you can set this macro before including juce.h
  13910. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  13911. /*** Start of inlined file: juce_app_includes.h ***/
  13912. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  13913. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  13914. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  13915. /*** Start of inlined file: juce_Application.h ***/
  13916. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  13917. #define __JUCE_APPLICATION_JUCEHEADER__
  13918. /*** Start of inlined file: juce_ApplicationCommandTarget.h ***/
  13919. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  13920. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  13921. /*** Start of inlined file: juce_Component.h ***/
  13922. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  13923. #define __JUCE_COMPONENT_JUCEHEADER__
  13924. /*** Start of inlined file: juce_MouseCursor.h ***/
  13925. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  13926. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  13927. class Image;
  13928. class ComponentPeer;
  13929. class Component;
  13930. /**
  13931. Represents a mouse cursor image.
  13932. This object can either be used to represent one of the standard mouse
  13933. cursor shapes, or a custom one generated from an image.
  13934. */
  13935. class JUCE_API MouseCursor
  13936. {
  13937. public:
  13938. /** The set of available standard mouse cursors. */
  13939. enum StandardCursorType
  13940. {
  13941. NoCursor = 0, /**< An invisible cursor. */
  13942. NormalCursor, /**< The stardard arrow cursor. */
  13943. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  13944. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  13945. CrosshairCursor, /**< A pair of crosshairs. */
  13946. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  13947. that you're dragging a copy of something. */
  13948. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  13949. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  13950. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  13951. UpDownResizeCursor, /**< an arrow pointing up and down. */
  13952. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  13953. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  13954. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  13955. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  13956. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  13957. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  13958. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  13959. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  13960. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  13961. };
  13962. /** Creates the standard arrow cursor. */
  13963. MouseCursor();
  13964. /** Creates one of the standard mouse cursor */
  13965. MouseCursor (StandardCursorType type);
  13966. /** Creates a custom cursor from an image.
  13967. @param image the image to use for the cursor - if this is bigger than the
  13968. system can manage, it might get scaled down first, and might
  13969. also have to be turned to black-and-white if it can't do colour
  13970. cursors.
  13971. @param hotSpotX the x position of the cursor's hotspot within the image
  13972. @param hotSpotY the y position of the cursor's hotspot within the image
  13973. */
  13974. MouseCursor (const Image& image, int hotSpotX, int hotSpotY);
  13975. /** Creates a copy of another cursor object. */
  13976. MouseCursor (const MouseCursor& other);
  13977. /** Copies this cursor from another object. */
  13978. MouseCursor& operator= (const MouseCursor& other);
  13979. /** Destructor. */
  13980. ~MouseCursor();
  13981. /** Checks whether two mouse cursors are the same.
  13982. For custom cursors, two cursors created from the same image won't be
  13983. recognised as the same, only MouseCursor objects that have been
  13984. copied from the same object.
  13985. */
  13986. bool operator== (const MouseCursor& other) const throw();
  13987. /** Checks whether two mouse cursors are the same.
  13988. For custom cursors, two cursors created from the same image won't be
  13989. recognised as the same, only MouseCursor objects that have been
  13990. copied from the same object.
  13991. */
  13992. bool operator!= (const MouseCursor& other) const throw();
  13993. /** Makes the system show its default 'busy' cursor.
  13994. This will turn the system cursor to an hourglass or spinning beachball
  13995. until the next time the mouse is moved, or hideWaitCursor() is called.
  13996. This is handy if the message loop is about to block for a couple of
  13997. seconds while busy and you want to give the user feedback about this.
  13998. @see MessageManager::setTimeBeforeShowingWaitCursor
  13999. */
  14000. static void showWaitCursor();
  14001. /** If showWaitCursor has been called, this will return the mouse to its
  14002. normal state.
  14003. This will look at what component is under the mouse, and update the
  14004. cursor to be the correct one for that component.
  14005. @see showWaitCursor
  14006. */
  14007. static void hideWaitCursor();
  14008. juce_UseDebuggingNewOperator
  14009. private:
  14010. class SharedCursorHandle;
  14011. friend class SharedCursorHandle;
  14012. SharedCursorHandle* cursorHandle;
  14013. friend class MouseInputSourceInternal;
  14014. void showInWindow (ComponentPeer* window) const;
  14015. void showInAllWindows() const;
  14016. void* getHandle() const throw();
  14017. static void* createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY);
  14018. static void* createStandardMouseCursor (MouseCursor::StandardCursorType type);
  14019. static void deleteMouseCursor (void* cursorHandle, bool isStandard);
  14020. };
  14021. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  14022. /*** End of inlined file: juce_MouseCursor.h ***/
  14023. /*** Start of inlined file: juce_MouseListener.h ***/
  14024. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  14025. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  14026. class MouseEvent;
  14027. /**
  14028. A MouseListener can be registered with a component to receive callbacks
  14029. about mouse events that happen to that component.
  14030. @see Component::addMouseListener, Component::removeMouseListener
  14031. */
  14032. class JUCE_API MouseListener
  14033. {
  14034. public:
  14035. /** Destructor. */
  14036. virtual ~MouseListener() {}
  14037. /** Called when the mouse moves inside a component.
  14038. If the mouse button isn't pressed and the mouse moves over a component,
  14039. this will be called to let the component react to this.
  14040. A component will always get a mouseEnter callback before a mouseMove.
  14041. @param e details about the position and status of the mouse event, including
  14042. the source component in which it occurred
  14043. @see mouseEnter, mouseExit, mouseDrag, contains
  14044. */
  14045. virtual void mouseMove (const MouseEvent& e);
  14046. /** Called when the mouse first enters a component.
  14047. If the mouse button isn't pressed and the mouse moves into a component,
  14048. this will be called to let the component react to this.
  14049. When the mouse button is pressed and held down while being moved in
  14050. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  14051. mouseDrag messages are sent to the component that the mouse was originally
  14052. clicked on, until the button is released.
  14053. @param e details about the position and status of the mouse event, including
  14054. the source component in which it occurred
  14055. @see mouseExit, mouseDrag, mouseMove, contains
  14056. */
  14057. virtual void mouseEnter (const MouseEvent& e);
  14058. /** Called when the mouse moves out of a component.
  14059. This will be called when the mouse moves off the edge of this
  14060. component.
  14061. If the mouse button was pressed, and it was then dragged off the
  14062. edge of the component and released, then this callback will happen
  14063. when the button is released, after the mouseUp callback.
  14064. @param e details about the position and status of the mouse event, including
  14065. the source component in which it occurred
  14066. @see mouseEnter, mouseDrag, mouseMove, contains
  14067. */
  14068. virtual void mouseExit (const MouseEvent& e);
  14069. /** Called when a mouse button is pressed.
  14070. The MouseEvent object passed in contains lots of methods for finding out
  14071. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  14072. were held down at the time.
  14073. Once a button is held down, the mouseDrag method will be called when the
  14074. mouse moves, until the button is released.
  14075. @param e details about the position and status of the mouse event, including
  14076. the source component in which it occurred
  14077. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  14078. */
  14079. virtual void mouseDown (const MouseEvent& e);
  14080. /** Called when the mouse is moved while a button is held down.
  14081. When a mouse button is pressed inside a component, that component
  14082. receives mouseDrag callbacks each time the mouse moves, even if the
  14083. mouse strays outside the component's bounds.
  14084. @param e details about the position and status of the mouse event, including
  14085. the source component in which it occurred
  14086. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  14087. */
  14088. virtual void mouseDrag (const MouseEvent& e);
  14089. /** Called when a mouse button is released.
  14090. A mouseUp callback is sent to the component in which a button was pressed
  14091. even if the mouse is actually over a different component when the
  14092. button is released.
  14093. The MouseEvent object passed in contains lots of methods for finding out
  14094. which buttons were down just before they were released.
  14095. @param e details about the position and status of the mouse event, including
  14096. the source component in which it occurred
  14097. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  14098. */
  14099. virtual void mouseUp (const MouseEvent& e);
  14100. /** Called when a mouse button has been double-clicked on a component.
  14101. The MouseEvent object passed in contains lots of methods for finding out
  14102. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  14103. were held down at the time.
  14104. @param e details about the position and status of the mouse event, including
  14105. the source component in which it occurred
  14106. @see mouseDown, mouseUp
  14107. */
  14108. virtual void mouseDoubleClick (const MouseEvent& e);
  14109. /** Called when the mouse-wheel is moved.
  14110. This callback is sent to the component that the mouse is over when the
  14111. wheel is moved.
  14112. If not overridden, the component will forward this message to its parent, so
  14113. that parent components can collect mouse-wheel messages that happen to
  14114. child components which aren't interested in them.
  14115. @param e details about the position and status of the mouse event, including
  14116. the source component in which it occurred
  14117. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  14118. value means the wheel has been pushed to the right, negative means it
  14119. was pushed to the left
  14120. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  14121. value means the wheel has been pushed upwards, negative means it
  14122. was pushed downwards
  14123. */
  14124. virtual void mouseWheelMove (const MouseEvent& e,
  14125. float wheelIncrementX,
  14126. float wheelIncrementY);
  14127. };
  14128. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  14129. /*** End of inlined file: juce_MouseListener.h ***/
  14130. /*** Start of inlined file: juce_MouseEvent.h ***/
  14131. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  14132. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  14133. class Component;
  14134. class MouseInputSource;
  14135. /*** Start of inlined file: juce_ModifierKeys.h ***/
  14136. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  14137. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  14138. /**
  14139. Represents the state of the mouse buttons and modifier keys.
  14140. This is used both by mouse events and by KeyPress objects to describe
  14141. the state of keys such as shift, control, alt, etc.
  14142. @see KeyPress, MouseEvent::mods
  14143. */
  14144. class JUCE_API ModifierKeys
  14145. {
  14146. public:
  14147. /** Creates a ModifierKeys object from a raw set of flags.
  14148. @param flags to represent the keys that are down
  14149. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  14150. rightButtonModifier, commandModifier, popupMenuClickModifier
  14151. */
  14152. ModifierKeys (int flags = 0) throw();
  14153. /** Creates a copy of another object. */
  14154. ModifierKeys (const ModifierKeys& other) throw();
  14155. /** Copies this object from another one. */
  14156. ModifierKeys& operator= (const ModifierKeys& other) throw();
  14157. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  14158. This is a platform-agnostic way of checking for the operating system's
  14159. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  14160. Windows/Linux, it's actually checking for the CTRL key.
  14161. */
  14162. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  14163. /** Checks whether the user is trying to launch a pop-up menu.
  14164. This checks for platform-specific modifiers that might indicate that the user
  14165. is following the operating system's normal method of showing a pop-up menu.
  14166. So on Windows/Linux, this method is really testing for a right-click.
  14167. On the Mac, it tests for either the CTRL key being down, or a right-click.
  14168. */
  14169. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  14170. /** Checks whether the flag is set for the left mouse-button. */
  14171. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  14172. /** Checks whether the flag is set for the right mouse-button.
  14173. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  14174. this is platform-independent (and makes your code more explanatory too).
  14175. */
  14176. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  14177. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  14178. /** Tests for any of the mouse-button flags. */
  14179. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  14180. /** Tests for any of the modifier key flags. */
  14181. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  14182. /** Checks whether the shift key's flag is set. */
  14183. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  14184. /** Checks whether the CTRL key's flag is set.
  14185. Remember that it's better to use the platform-agnostic routines to test for command-key and
  14186. popup-menu modifiers.
  14187. @see isCommandDown, isPopupMenu
  14188. */
  14189. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  14190. /** Checks whether the shift key's flag is set. */
  14191. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  14192. /** Flags that represent the different keys. */
  14193. enum Flags
  14194. {
  14195. /** Shift key flag. */
  14196. shiftModifier = 1,
  14197. /** CTRL key flag. */
  14198. ctrlModifier = 2,
  14199. /** ALT key flag. */
  14200. altModifier = 4,
  14201. /** Left mouse button flag. */
  14202. leftButtonModifier = 16,
  14203. /** Right mouse button flag. */
  14204. rightButtonModifier = 32,
  14205. /** Middle mouse button flag. */
  14206. middleButtonModifier = 64,
  14207. #if JUCE_MAC
  14208. /** Command key flag - on windows this is the same as the CTRL key flag. */
  14209. commandModifier = 8,
  14210. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  14211. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  14212. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  14213. #else
  14214. /** Command key flag - on windows this is the same as the CTRL key flag. */
  14215. commandModifier = ctrlModifier,
  14216. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  14217. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  14218. popupMenuClickModifier = rightButtonModifier,
  14219. #endif
  14220. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  14221. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  14222. /** Represents a combination of all the mouse buttons at once. */
  14223. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  14224. };
  14225. /** Returns a copy of only the mouse-button flags */
  14226. const ModifierKeys withOnlyMouseButtons() const throw() { return ModifierKeys (flags & allMouseButtonModifiers); }
  14227. /** Returns a copy of only the non-mouse flags */
  14228. const ModifierKeys withoutMouseButtons() const throw() { return ModifierKeys (flags & ~allMouseButtonModifiers); }
  14229. bool operator== (const ModifierKeys& other) const throw() { return flags == other.flags; }
  14230. bool operator!= (const ModifierKeys& other) const throw() { return flags != other.flags; }
  14231. /** Returns the raw flags for direct testing. */
  14232. inline int getRawFlags() const throw() { return flags; }
  14233. inline const ModifierKeys withoutFlags (int rawFlagsToClear) const throw() { return ModifierKeys (flags & ~rawFlagsToClear); }
  14234. inline const ModifierKeys withFlags (int rawFlagsToSet) const throw() { return ModifierKeys (flags | rawFlagsToSet); }
  14235. /** Tests a combination of flags and returns true if any of them are set. */
  14236. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  14237. /** Returns the total number of mouse buttons that are down. */
  14238. int getNumMouseButtonsDown() const throw();
  14239. /** Creates a ModifierKeys object to represent the last-known state of the
  14240. keyboard and mouse buttons.
  14241. @see getCurrentModifiersRealtime
  14242. */
  14243. static const ModifierKeys getCurrentModifiers() throw();
  14244. /** Creates a ModifierKeys object to represent the current state of the
  14245. keyboard and mouse buttons.
  14246. This isn't often needed and isn't recommended, but will actively check all the
  14247. mouse and key states rather than just returning their last-known state like
  14248. getCurrentModifiers() does.
  14249. This is only needed in special circumstances for up-to-date modifier information
  14250. at times when the app's event loop isn't running normally.
  14251. */
  14252. static const ModifierKeys getCurrentModifiersRealtime() throw();
  14253. private:
  14254. int flags;
  14255. static ModifierKeys currentModifiers;
  14256. friend class ComponentPeer;
  14257. friend class MouseInputSource;
  14258. friend class MouseInputSourceInternal;
  14259. static void updateCurrentModifiers() throw();
  14260. };
  14261. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  14262. /*** End of inlined file: juce_ModifierKeys.h ***/
  14263. /*** Start of inlined file: juce_Point.h ***/
  14264. #ifndef __JUCE_POINT_JUCEHEADER__
  14265. #define __JUCE_POINT_JUCEHEADER__
  14266. /*** Start of inlined file: juce_AffineTransform.h ***/
  14267. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  14268. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  14269. /**
  14270. Represents a 2D affine-transformation matrix.
  14271. An affine transformation is a transformation such as a rotation, scale, shear,
  14272. resize or translation.
  14273. These are used for various 2D transformation tasks, e.g. with Path objects.
  14274. @see Path, Point, Line
  14275. */
  14276. class JUCE_API AffineTransform
  14277. {
  14278. public:
  14279. /** Creates an identity transform. */
  14280. AffineTransform() throw();
  14281. /** Creates a copy of another transform. */
  14282. AffineTransform (const AffineTransform& other) throw();
  14283. /** Creates a transform from a set of raw matrix values.
  14284. The resulting matrix is:
  14285. (mat00 mat01 mat02)
  14286. (mat10 mat11 mat12)
  14287. ( 0 0 1 )
  14288. */
  14289. AffineTransform (float mat00, float mat01, float mat02,
  14290. float mat10, float mat11, float mat12) throw();
  14291. /** Copies from another AffineTransform object */
  14292. AffineTransform& operator= (const AffineTransform& other) throw();
  14293. /** Compares two transforms. */
  14294. bool operator== (const AffineTransform& other) const throw();
  14295. /** Compares two transforms. */
  14296. bool operator!= (const AffineTransform& other) const throw();
  14297. /** A ready-to-use identity transform, which you can use to append other
  14298. transformations to.
  14299. e.g. @code
  14300. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  14301. .scaled (2.0f);
  14302. @endcode
  14303. */
  14304. static const AffineTransform identity;
  14305. /** Transforms a 2D co-ordinate using this matrix. */
  14306. void transformPoint (float& x,
  14307. float& y) const throw();
  14308. /** Transforms a 2D co-ordinate using this matrix. */
  14309. void transformPoint (double& x,
  14310. double& y) const throw();
  14311. /** Returns a new transform which is the same as this one followed by a translation. */
  14312. const AffineTransform translated (float deltaX,
  14313. float deltaY) const throw();
  14314. /** Returns a new transform which is a translation. */
  14315. static const AffineTransform translation (float deltaX,
  14316. float deltaY) throw();
  14317. /** Returns a transform which is the same as this one followed by a rotation.
  14318. The rotation is specified by a number of radians to rotate clockwise, centred around
  14319. the origin (0, 0).
  14320. */
  14321. const AffineTransform rotated (float angleInRadians) const throw();
  14322. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  14323. The rotation is specified by a number of radians to rotate clockwise, centred around
  14324. the co-ordinates passed in.
  14325. */
  14326. const AffineTransform rotated (float angleInRadians,
  14327. float pivotX,
  14328. float pivotY) const throw();
  14329. /** Returns a new transform which is a rotation about (0, 0). */
  14330. static const AffineTransform rotation (float angleInRadians) throw();
  14331. /** Returns a new transform which is a rotation about a given point. */
  14332. static const AffineTransform rotation (float angleInRadians,
  14333. float pivotX,
  14334. float pivotY) throw();
  14335. /** Returns a transform which is the same as this one followed by a re-scaling.
  14336. The scaling is centred around the origin (0, 0).
  14337. */
  14338. const AffineTransform scaled (float factorX,
  14339. float factorY) const throw();
  14340. /** Returns a new transform which is a re-scale about the origin. */
  14341. static const AffineTransform scale (float factorX,
  14342. float factorY) throw();
  14343. /** Returns a transform which is the same as this one followed by a shear.
  14344. The shear is centred around the origin (0, 0).
  14345. */
  14346. const AffineTransform sheared (float shearX,
  14347. float shearY) const throw();
  14348. /** Returns a matrix which is the inverse operation of this one.
  14349. Some matrices don't have an inverse - in this case, the method will just return
  14350. an identity transform.
  14351. */
  14352. const AffineTransform inverted() const throw();
  14353. /** Returns the transform that will map three known points onto three coordinates
  14354. that are supplied.
  14355. This returns the transform that will transform (0, 0) into (x00, y00),
  14356. (1, 0) to (x10, y10), and (0, 1) to (x01, y01).
  14357. */
  14358. static const AffineTransform fromTargetPoints (float x00, float y00,
  14359. float x10, float y10,
  14360. float x01, float y01) throw();
  14361. /** Returns the transform that will map three specified points onto three target points.
  14362. */
  14363. static const AffineTransform fromTargetPoints (float sourceX1, float sourceY1, float targetX1, float targetY1,
  14364. float sourceX2, float sourceY2, float targetX2, float targetY2,
  14365. float sourceX3, float sourceY3, float targetX3, float targetY3) throw();
  14366. /** Returns the result of concatenating another transformation after this one. */
  14367. const AffineTransform followedBy (const AffineTransform& other) const throw();
  14368. /** Returns true if this transform has no effect on points. */
  14369. bool isIdentity() const throw();
  14370. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  14371. bool isSingularity() const throw();
  14372. /** Returns true if the transform only translates, and doesn't scale or rotate the
  14373. points. */
  14374. bool isOnlyTranslation() const throw();
  14375. /** If this transform is only a translation, this returns the X offset.
  14376. @see isOnlyTranslation
  14377. */
  14378. float getTranslationX() const throw() { return mat02; }
  14379. /** If this transform is only a translation, this returns the X offset.
  14380. @see isOnlyTranslation
  14381. */
  14382. float getTranslationY() const throw() { return mat12; }
  14383. /* The transform matrix is:
  14384. (mat00 mat01 mat02)
  14385. (mat10 mat11 mat12)
  14386. ( 0 0 1 )
  14387. */
  14388. float mat00, mat01, mat02;
  14389. float mat10, mat11, mat12;
  14390. juce_UseDebuggingNewOperator
  14391. private:
  14392. const AffineTransform followedBy (float mat00, float mat01, float mat02,
  14393. float mat10, float mat11, float mat12) const throw();
  14394. };
  14395. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  14396. /*** End of inlined file: juce_AffineTransform.h ***/
  14397. /**
  14398. A pair of (x, y) co-ordinates.
  14399. The ValueType template should be a primitive type such as int, float, double,
  14400. rather than a class.
  14401. @see Line, Path, AffineTransform
  14402. */
  14403. template <typename ValueType>
  14404. class Point
  14405. {
  14406. public:
  14407. /** Creates a point with co-ordinates (0, 0). */
  14408. Point() throw() : x (0), y (0) {}
  14409. /** Creates a copy of another point. */
  14410. Point (const Point& other) throw() : x (other.x), y (other.y) {}
  14411. /** Creates a point from an (x, y) position. */
  14412. Point (const ValueType initialX, const ValueType initialY) throw() : x (initialX), y (initialY) {}
  14413. /** Destructor. */
  14414. ~Point() throw() {}
  14415. /** Copies this point from another one. */
  14416. Point& operator= (const Point& other) throw() { x = other.x; y = other.y; return *this; }
  14417. inline bool operator== (const Point& other) const throw() { return x == other.x && y == other.y; }
  14418. inline bool operator!= (const Point& other) const throw() { return x != other.x || y != other.y; }
  14419. /** Returns true if the point is (0, 0). */
  14420. bool isOrigin() const throw() { return x == ValueType() && y == ValueType(); }
  14421. /** Returns the point's x co-ordinate. */
  14422. inline ValueType getX() const throw() { return x; }
  14423. /** Returns the point's y co-ordinate. */
  14424. inline ValueType getY() const throw() { return y; }
  14425. /** Sets the point's x co-ordinate. */
  14426. inline void setX (const ValueType newX) throw() { x = newX; }
  14427. /** Sets the point's y co-ordinate. */
  14428. inline void setY (const ValueType newY) throw() { y = newY; }
  14429. /** Returns a point which has the same Y position as this one, but a new X. */
  14430. const Point withX (const ValueType newX) const throw() { return Point (newX, y); }
  14431. /** Returns a point which has the same X position as this one, but a new Y. */
  14432. const Point withY (const ValueType newY) const throw() { return Point (x, newY); }
  14433. /** Changes the point's x and y co-ordinates. */
  14434. void setXY (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  14435. /** Adds a pair of co-ordinates to this value. */
  14436. void addXY (const ValueType xToAdd, const ValueType yToAdd) throw() { x += xToAdd; y += yToAdd; }
  14437. /** Adds two points together. */
  14438. const Point operator+ (const Point& other) const throw() { return Point (x + other.x, y + other.y); }
  14439. /** Adds another point's co-ordinates to this one. */
  14440. Point& operator+= (const Point& other) throw() { x += other.x; y += other.y; return *this; }
  14441. /** Subtracts one points from another. */
  14442. const Point operator- (const Point& other) const throw() { return Point (x - other.x, y - other.y); }
  14443. /** Subtracts another point's co-ordinates to this one. */
  14444. Point& operator-= (const Point& other) throw() { x -= other.x; y -= other.y; return *this; }
  14445. /** Returns a point whose coordinates are multiplied by a given value. */
  14446. const Point operator* (const ValueType multiplier) const throw() { return Point (x * multiplier, y * multiplier); }
  14447. /** Multiplies the point's co-ordinates by a value. */
  14448. Point& operator*= (const ValueType multiplier) throw() { x *= multiplier; y *= multiplier; return *this; }
  14449. /** Returns a point whose coordinates are divided by a given value. */
  14450. const Point operator/ (const ValueType divisor) const throw() { return Point (x / divisor, y / divisor); }
  14451. /** Divides the point's co-ordinates by a value. */
  14452. Point& operator/= (const ValueType divisor) throw() { x /= divisor; y /= divisor; return *this; }
  14453. /** Returns the inverse of this point. */
  14454. const Point operator-() const throw() { return Point (-x, -y); }
  14455. /** Returns the straight-line distance between this point and another one. */
  14456. ValueType getDistanceFromOrigin() const throw() { return (ValueType) juce_hypot (x, y); }
  14457. /** Returns the straight-line distance between this point and another one. */
  14458. ValueType getDistanceFrom (const Point& other) const throw() { return (ValueType) juce_hypot (x - other.x, y - other.y); }
  14459. /** Returns the angle from this point to another one.
  14460. The return value is the number of radians clockwise from the 3 o'clock direction,
  14461. where this point is the centre and the other point is on the circumference.
  14462. */
  14463. ValueType getAngleToPoint (const Point& other) const throw() { return (ValueType) std::atan2 (other.x - x, other.y - y); }
  14464. /** Taking this point to be the centre of a circle, this returns a point on its circumference.
  14465. @param radius the radius of the circle.
  14466. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  14467. */
  14468. const Point getPointOnCircumference (const float radius, const float angle) const throw() { return Point<float> (x + radius * std::sin (angle),
  14469. y - radius * std::cos (angle)); }
  14470. /** Taking this point to be the centre of an ellipse, this returns a point on its circumference.
  14471. @param radiusX the horizontal radius of the circle.
  14472. @param radiusY the vertical 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 radiusX, const float radiusY, const float angle) const throw() { return Point<float> (x + radiusX * std::sin (angle),
  14476. y - radiusY * std::cos (angle)); }
  14477. /** Uses a transform to change the point's co-ordinates.
  14478. This will only compile if ValueType = float!
  14479. @see AffineTransform::transformPoint
  14480. */
  14481. void applyTransform (const AffineTransform& transform) throw() { transform.transformPoint (x, y); }
  14482. /** Returns the position of this point, if it is transformed by a given AffineTransform. */
  14483. const Point transformedBy (const AffineTransform& transform) const throw() { ValueType x2 (x), y2 (y); transform.transformPoint (x2, y2); return Point (x2, y2); }
  14484. /** Casts this point to a Point<float> object. */
  14485. const Point<float> toFloat() const throw() { return Point<float> (static_cast <float> (x), static_cast<float> (y)); }
  14486. /** Returns the point as a string in the form "x, y". */
  14487. const String toString() const { return String (x) + ", " + String (y); }
  14488. juce_UseDebuggingNewOperator
  14489. private:
  14490. ValueType x, y;
  14491. };
  14492. #endif // __JUCE_POINT_JUCEHEADER__
  14493. /*** End of inlined file: juce_Point.h ***/
  14494. /**
  14495. Contains position and status information about a mouse event.
  14496. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  14497. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  14498. */
  14499. class JUCE_API MouseEvent
  14500. {
  14501. public:
  14502. /** Creates a MouseEvent.
  14503. Normally an application will never need to use this.
  14504. @param source the source that's invoking the event
  14505. @param position the position of the mouse, relative to the component that is passed-in
  14506. @param modifiers the key modifiers at the time of the event
  14507. @param eventComponent the component that the mouse event applies to
  14508. @param originator the component that originally received the event
  14509. @param eventTime the time the event happened
  14510. @param mouseDownPos the position of the corresponding mouse-down event (relative to the component that is passed-in).
  14511. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  14512. the same as the current mouse-x position.
  14513. @param mouseDownTime the time at which the corresponding mouse-down event happened
  14514. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  14515. the same as the current mouse-event time.
  14516. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  14517. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  14518. */
  14519. MouseEvent (MouseInputSource& source,
  14520. const Point<int>& position,
  14521. const ModifierKeys& modifiers,
  14522. Component* eventComponent,
  14523. Component* originator,
  14524. const Time& eventTime,
  14525. const Point<int> mouseDownPos,
  14526. const Time& mouseDownTime,
  14527. int numberOfClicks,
  14528. bool mouseWasDragged) throw();
  14529. /** Destructor. */
  14530. ~MouseEvent() throw();
  14531. /** The x-position of the mouse when the event occurred.
  14532. This value is relative to the top-left of the component to which the
  14533. event applies (as indicated by the MouseEvent::eventComponent field).
  14534. */
  14535. const int x;
  14536. /** The y-position of the mouse when the event occurred.
  14537. This value is relative to the top-left of the component to which the
  14538. event applies (as indicated by the MouseEvent::eventComponent field).
  14539. */
  14540. const int y;
  14541. /** The key modifiers associated with the event.
  14542. This will let you find out which mouse buttons were down, as well as which
  14543. modifier keys were held down.
  14544. When used for mouse-up events, this will indicate the state of the mouse buttons
  14545. just before they were released, so that you can tell which button they let go of.
  14546. */
  14547. const ModifierKeys mods;
  14548. /** The component that this event applies to.
  14549. This is usually the component that the mouse was over at the time, but for mouse-drag
  14550. events the mouse could actually be over a different component and the events are
  14551. still sent to the component that the button was originally pressed on.
  14552. The x and y member variables are relative to this component's position.
  14553. If you use getEventRelativeTo() to retarget this object to be relative to a different
  14554. component, this pointer will be updated, but originalComponent remains unchanged.
  14555. @see originalComponent
  14556. */
  14557. Component* const eventComponent;
  14558. /** The component that the event first occurred on.
  14559. If you use getEventRelativeTo() to retarget this object to be relative to a different
  14560. component, this value remains unchanged to indicate the first component that received it.
  14561. @see eventComponent
  14562. */
  14563. Component* const originalComponent;
  14564. /** The time that this mouse-event occurred.
  14565. */
  14566. const Time eventTime;
  14567. /** The source device that generated this event.
  14568. */
  14569. MouseInputSource& source;
  14570. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  14571. The co-ordinate is relative to the component specified in MouseEvent::component.
  14572. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  14573. */
  14574. int getMouseDownX() const throw();
  14575. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  14576. The co-ordinate is relative to the component specified in MouseEvent::component.
  14577. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  14578. */
  14579. int getMouseDownY() const throw();
  14580. /** Returns the co-ordinates of the last place that a mouse was pressed.
  14581. The co-ordinates are relative to the component specified in MouseEvent::component.
  14582. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  14583. */
  14584. const Point<int> getMouseDownPosition() const throw();
  14585. /** Returns the straight-line distance between where the mouse is now and where it
  14586. was the last time the button was pressed.
  14587. This is quite handy for things like deciding whether the user has moved far enough
  14588. for it to be considered a drag operation.
  14589. @see getDistanceFromDragStartX
  14590. */
  14591. int getDistanceFromDragStart() const throw();
  14592. /** Returns the difference between the mouse's current x postion and where it was
  14593. when the button was last pressed.
  14594. @see getDistanceFromDragStart
  14595. */
  14596. int getDistanceFromDragStartX() const throw();
  14597. /** Returns the difference between the mouse's current y postion and where it was
  14598. when the button was last pressed.
  14599. @see getDistanceFromDragStart
  14600. */
  14601. int getDistanceFromDragStartY() const throw();
  14602. /** Returns the difference between the mouse's current postion and where it was
  14603. when the button was last pressed.
  14604. @see getDistanceFromDragStart
  14605. */
  14606. const Point<int> getOffsetFromDragStart() const throw();
  14607. /** Returns true if the mouse has just been clicked.
  14608. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  14609. the user has dragged the mouse more than a few pixels from the place where the
  14610. mouse-down occurred.
  14611. Once they have dragged it far enough for this method to return false, it will continue
  14612. to return false until the mouse-up, even if they move the mouse back to the same
  14613. position where they originally pressed it. This means that it's very handy for
  14614. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  14615. callback to ignore any small movements they might make while clicking.
  14616. @returns true if the mouse wasn't dragged by more than a few pixels between
  14617. the last time the button was pressed and released.
  14618. */
  14619. bool mouseWasClicked() const throw();
  14620. /** For a click event, the number of times the mouse was clicked in succession.
  14621. So for example a double-click event will return 2, a triple-click 3, etc.
  14622. */
  14623. int getNumberOfClicks() const throw() { return numberOfClicks; }
  14624. /** Returns the time that the mouse button has been held down for.
  14625. If called from a mouseDrag or mouseUp callback, this will return the
  14626. number of milliseconds since the corresponding mouseDown event occurred.
  14627. If called in other contexts, e.g. a mouseMove, then the returned value
  14628. may be 0 or an undefined value.
  14629. */
  14630. int getLengthOfMousePress() const throw();
  14631. /** The position of the mouse when the event occurred.
  14632. This position is relative to the top-left of the component to which the
  14633. event applies (as indicated by the MouseEvent::eventComponent field).
  14634. */
  14635. const Point<int> getPosition() const throw();
  14636. /** Returns the mouse x position of this event, in global screen co-ordinates.
  14637. The co-ordinates are relative to the top-left of the main monitor.
  14638. @see getScreenPosition
  14639. */
  14640. int getScreenX() const;
  14641. /** Returns the mouse y position of this event, in global screen co-ordinates.
  14642. The co-ordinates are relative to the top-left of the main monitor.
  14643. @see getScreenPosition
  14644. */
  14645. int getScreenY() const;
  14646. /** Returns the mouse position of this event, in global screen co-ordinates.
  14647. The co-ordinates are relative to the top-left of the main monitor.
  14648. @see getMouseDownScreenPosition
  14649. */
  14650. const Point<int> getScreenPosition() const;
  14651. /** Returns the x co-ordinate at which the mouse button was last pressed.
  14652. The co-ordinates are relative to the top-left of the main monitor.
  14653. @see getMouseDownScreenPosition
  14654. */
  14655. int getMouseDownScreenX() const;
  14656. /** Returns the y co-ordinate at which the mouse button was last pressed.
  14657. The co-ordinates are relative to the top-left of the main monitor.
  14658. @see getMouseDownScreenPosition
  14659. */
  14660. int getMouseDownScreenY() const;
  14661. /** Returns the co-ordinates at which the mouse button was last pressed.
  14662. The co-ordinates are relative to the top-left of the main monitor.
  14663. @see getScreenPosition
  14664. */
  14665. const Point<int> getMouseDownScreenPosition() const;
  14666. /** Creates a version of this event that is relative to a different component.
  14667. The x and y positions of the event that is returned will have been
  14668. adjusted to be relative to the new component.
  14669. */
  14670. const MouseEvent getEventRelativeTo (Component* otherComponent) const throw();
  14671. /** Creates a copy of this event with a different position.
  14672. All other members of the event object are the same, but the x and y are
  14673. replaced with these new values.
  14674. */
  14675. const MouseEvent withNewPosition (const Point<int>& newPosition) const throw();
  14676. /** Changes the application-wide setting for the double-click time limit.
  14677. This is the maximum length of time between mouse-clicks for it to be
  14678. considered a double-click. It's used by the Component class.
  14679. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  14680. */
  14681. static void setDoubleClickTimeout (int timeOutMilliseconds) throw();
  14682. /** Returns the application-wide setting for the double-click time limit.
  14683. This is the maximum length of time between mouse-clicks for it to be
  14684. considered a double-click. It's used by the Component class.
  14685. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  14686. */
  14687. static int getDoubleClickTimeout() throw();
  14688. juce_UseDebuggingNewOperator
  14689. private:
  14690. const Point<int> mouseDownPos;
  14691. const Time mouseDownTime;
  14692. const int numberOfClicks;
  14693. const bool wasMovedSinceMouseDown;
  14694. MouseEvent& operator= (const MouseEvent&);
  14695. };
  14696. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  14697. /*** End of inlined file: juce_MouseEvent.h ***/
  14698. /*** Start of inlined file: juce_ComponentListener.h ***/
  14699. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  14700. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  14701. class Component;
  14702. /**
  14703. Gets informed about changes to a component's hierarchy or position.
  14704. To monitor a component for changes, register a subclass of ComponentListener
  14705. with the component using Component::addComponentListener().
  14706. Be sure to deregister listeners before you delete them!
  14707. @see Component::addComponentListener, Component::removeComponentListener
  14708. */
  14709. class JUCE_API ComponentListener
  14710. {
  14711. public:
  14712. /** Destructor. */
  14713. virtual ~ComponentListener() {}
  14714. /** Called when the component's position or size changes.
  14715. @param component the component that was moved or resized
  14716. @param wasMoved true if the component's top-left corner has just moved
  14717. @param wasResized true if the component's width or height has just changed
  14718. @see Component::setBounds, Component::resized, Component::moved
  14719. */
  14720. virtual void componentMovedOrResized (Component& component,
  14721. bool wasMoved,
  14722. bool wasResized);
  14723. /** Called when the component is brought to the top of the z-order.
  14724. @param component the component that was moved
  14725. @see Component::toFront, Component::broughtToFront
  14726. */
  14727. virtual void componentBroughtToFront (Component& component);
  14728. /** Called when the component is made visible or invisible.
  14729. @param component the component that changed
  14730. @see Component::setVisible
  14731. */
  14732. virtual void componentVisibilityChanged (Component& component);
  14733. /** Called when the component has children added or removed.
  14734. @param component the component whose children were changed
  14735. @see Component::childrenChanged, Component::addChildComponent,
  14736. Component::removeChildComponent
  14737. */
  14738. virtual void componentChildrenChanged (Component& component);
  14739. /** Called to indicate that the component's parents have changed.
  14740. When a component is added or removed from its parent, all of its children
  14741. will produce this notification (recursively - so all children of its
  14742. children will also be called as well).
  14743. @param component the component that this listener is registered with
  14744. @see Component::parentHierarchyChanged
  14745. */
  14746. virtual void componentParentHierarchyChanged (Component& component);
  14747. /** Called when the component's name is changed.
  14748. @see Component::setName, Component::getName
  14749. */
  14750. virtual void componentNameChanged (Component& component);
  14751. /** Called when the component is in the process of being deleted.
  14752. This callback is made from inside the destructor, so be very, very cautious
  14753. about what you do inside the callback.
  14754. It will be called before the component has been removed from its parent, and
  14755. before any child components have been removed.
  14756. */
  14757. virtual void componentBeingDeleted (Component& component);
  14758. };
  14759. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  14760. /*** End of inlined file: juce_ComponentListener.h ***/
  14761. /*** Start of inlined file: juce_KeyListener.h ***/
  14762. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  14763. #define __JUCE_KEYLISTENER_JUCEHEADER__
  14764. /*** Start of inlined file: juce_KeyPress.h ***/
  14765. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  14766. #define __JUCE_KEYPRESS_JUCEHEADER__
  14767. /**
  14768. Represents a key press, including any modifier keys that are needed.
  14769. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  14770. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  14771. */
  14772. class JUCE_API KeyPress
  14773. {
  14774. public:
  14775. /** Creates an (invalid) KeyPress.
  14776. @see isValid
  14777. */
  14778. KeyPress() throw();
  14779. /** Creates a KeyPress for a key and some modifiers.
  14780. e.g.
  14781. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  14782. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  14783. @param keyCode a code that represents the key - this value must be
  14784. one of special constants listed in this class, or an
  14785. 8-bit character code such as a letter (case is ignored),
  14786. digit or a simple key like "," or ".". Note that this
  14787. isn't the same as the textCharacter parameter, so for example
  14788. a keyCode of 'a' and a shift-key modifier should have a
  14789. textCharacter value of 'A'.
  14790. @param modifiers the modifiers to associate with the keystroke
  14791. @param textCharacter the character that would be printed if someone typed
  14792. this keypress into a text editor. This value may be
  14793. null if the keypress is a non-printing character
  14794. @see getKeyCode, isKeyCode, getModifiers
  14795. */
  14796. KeyPress (int keyCode,
  14797. const ModifierKeys& modifiers,
  14798. juce_wchar textCharacter) throw();
  14799. /** Creates a keypress with a keyCode but no modifiers or text character.
  14800. */
  14801. KeyPress (int keyCode) throw();
  14802. /** Creates a copy of another KeyPress. */
  14803. KeyPress (const KeyPress& other) throw();
  14804. /** Copies this KeyPress from another one. */
  14805. KeyPress& operator= (const KeyPress& other) throw();
  14806. /** Compares two KeyPress objects. */
  14807. bool operator== (const KeyPress& other) const throw();
  14808. /** Compares two KeyPress objects. */
  14809. bool operator!= (const KeyPress& other) const throw();
  14810. /** Returns true if this is a valid KeyPress.
  14811. A null keypress can be created by the default constructor, in case it's
  14812. needed.
  14813. */
  14814. bool isValid() const throw() { return keyCode != 0; }
  14815. /** Returns the key code itself.
  14816. This will either be one of the special constants defined in this class,
  14817. or an 8-bit character code.
  14818. */
  14819. int getKeyCode() const throw() { return keyCode; }
  14820. /** Returns the key modifiers.
  14821. @see ModifierKeys
  14822. */
  14823. const ModifierKeys getModifiers() const throw() { return mods; }
  14824. /** Returns the character that is associated with this keypress.
  14825. This is the character that you'd expect to see printed if you press this
  14826. keypress in a text editor or similar component.
  14827. */
  14828. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  14829. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  14830. the modifiers.
  14831. The values for key codes can either be one of the special constants defined in
  14832. this class, or an 8-bit character code.
  14833. @see getKeyCode
  14834. */
  14835. bool isKeyCode (int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  14836. /** Converts a textual key description to a KeyPress.
  14837. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  14838. This isn't designed to cope with any kind of input, but should be given the
  14839. strings that are created by the getTextDescription() method.
  14840. If the string can't be parsed, the object returned will be invalid.
  14841. @see getTextDescription
  14842. */
  14843. static const KeyPress createFromDescription (const String& textVersion);
  14844. /** Creates a textual description of the key combination.
  14845. e.g. "CTRL + C" or "DELETE".
  14846. To store a keypress in a file, use this method, along with createFromDescription()
  14847. to retrieve it later.
  14848. */
  14849. const String getTextDescription() const;
  14850. /** Checks whether the user is currently holding down the keys that make up this
  14851. KeyPress.
  14852. Note that this will return false if any extra modifier keys are
  14853. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  14854. then it will be false.
  14855. */
  14856. bool isCurrentlyDown() const;
  14857. /** Checks whether a particular key is held down, irrespective of modifiers.
  14858. The values for key codes can either be one of the special constants defined in
  14859. this class, or an 8-bit character code.
  14860. */
  14861. static bool isKeyCurrentlyDown (int keyCode);
  14862. // Key codes
  14863. //
  14864. // Note that the actual values of these are platform-specific and may change
  14865. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  14866. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  14867. //
  14868. static const int spaceKey; /**< key-code for the space bar */
  14869. static const int escapeKey; /**< key-code for the escape key */
  14870. static const int returnKey; /**< key-code for the return key*/
  14871. static const int tabKey; /**< key-code for the tab key*/
  14872. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  14873. static const int backspaceKey; /**< key-code for the backspace key */
  14874. static const int insertKey; /**< key-code for the insert key */
  14875. static const int upKey; /**< key-code for the cursor-up key */
  14876. static const int downKey; /**< key-code for the cursor-down key */
  14877. static const int leftKey; /**< key-code for the cursor-left key */
  14878. static const int rightKey; /**< key-code for the cursor-right key */
  14879. static const int pageUpKey; /**< key-code for the page-up key */
  14880. static const int pageDownKey; /**< key-code for the page-down key */
  14881. static const int homeKey; /**< key-code for the home key */
  14882. static const int endKey; /**< key-code for the end key */
  14883. static const int F1Key; /**< key-code for the F1 key */
  14884. static const int F2Key; /**< key-code for the F2 key */
  14885. static const int F3Key; /**< key-code for the F3 key */
  14886. static const int F4Key; /**< key-code for the F4 key */
  14887. static const int F5Key; /**< key-code for the F5 key */
  14888. static const int F6Key; /**< key-code for the F6 key */
  14889. static const int F7Key; /**< key-code for the F7 key */
  14890. static const int F8Key; /**< key-code for the F8 key */
  14891. static const int F9Key; /**< key-code for the F9 key */
  14892. static const int F10Key; /**< key-code for the F10 key */
  14893. static const int F11Key; /**< key-code for the F11 key */
  14894. static const int F12Key; /**< key-code for the F12 key */
  14895. static const int F13Key; /**< key-code for the F13 key */
  14896. static const int F14Key; /**< key-code for the F14 key */
  14897. static const int F15Key; /**< key-code for the F15 key */
  14898. static const int F16Key; /**< key-code for the F16 key */
  14899. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  14900. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  14901. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  14902. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  14903. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  14904. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  14905. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  14906. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  14907. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  14908. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  14909. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  14910. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  14911. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  14912. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  14913. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  14914. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  14915. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  14916. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  14917. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  14918. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  14919. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  14920. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  14921. juce_UseDebuggingNewOperator
  14922. private:
  14923. int keyCode;
  14924. ModifierKeys mods;
  14925. juce_wchar textCharacter;
  14926. };
  14927. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  14928. /*** End of inlined file: juce_KeyPress.h ***/
  14929. class Component;
  14930. /**
  14931. Receives callbacks when keys are pressed.
  14932. You can add a key listener to a component to be informed when that component
  14933. gets key events. See the Component::addListener method for more details.
  14934. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  14935. */
  14936. class JUCE_API KeyListener
  14937. {
  14938. public:
  14939. /** Destructor. */
  14940. virtual ~KeyListener() {}
  14941. /** Called to indicate that a key has been pressed.
  14942. If your implementation returns true, then the key event is considered to have
  14943. been consumed, and will not be passed on to any other components. If it returns
  14944. false, then the key will be passed to other components that might want to use it.
  14945. @param key the keystroke, including modifier keys
  14946. @param originatingComponent the component that received the key event
  14947. @see keyStateChanged, Component::keyPressed
  14948. */
  14949. virtual bool keyPressed (const KeyPress& key,
  14950. Component* originatingComponent) = 0;
  14951. /** Called when any key is pressed or released.
  14952. When this is called, classes that might be interested in
  14953. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  14954. check whether their key has changed.
  14955. If your implementation returns true, then the key event is considered to have
  14956. been consumed, and will not be passed on to any other components. If it returns
  14957. false, then the key will be passed to other components that might want to use it.
  14958. @param originatingComponent the component that received the key event
  14959. @param isKeyDown true if a key is being pressed, false if one is being released
  14960. @see KeyPress, Component::keyStateChanged
  14961. */
  14962. virtual bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  14963. };
  14964. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  14965. /*** End of inlined file: juce_KeyListener.h ***/
  14966. /*** Start of inlined file: juce_KeyboardFocusTraverser.h ***/
  14967. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  14968. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  14969. class Component;
  14970. /**
  14971. Controls the order in which focus moves between components.
  14972. The default algorithm used by this class to work out the order of traversal
  14973. is as follows:
  14974. - if two components both have an explicit focus order specified, then the
  14975. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  14976. method).
  14977. - any component with an explicit focus order greater than 0 comes before ones
  14978. that don't have an order specified.
  14979. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  14980. order.
  14981. If you need traversal in a more customised way, you can create a subclass
  14982. of KeyboardFocusTraverser that uses your own algorithm, and use
  14983. Component::createFocusTraverser() to create it.
  14984. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  14985. */
  14986. class JUCE_API KeyboardFocusTraverser
  14987. {
  14988. public:
  14989. KeyboardFocusTraverser();
  14990. /** Destructor. */
  14991. virtual ~KeyboardFocusTraverser();
  14992. /** Returns the component that should be given focus after the specified one
  14993. when moving "forwards".
  14994. The default implementation will return the next component which is to the
  14995. right of or below this one.
  14996. This may return 0 if there's no suitable candidate.
  14997. */
  14998. virtual Component* getNextComponent (Component* current);
  14999. /** Returns the component that should be given focus after the specified one
  15000. when moving "backwards".
  15001. The default implementation will return the next component which is to the
  15002. left of or above this one.
  15003. This may return 0 if there's no suitable candidate.
  15004. */
  15005. virtual Component* getPreviousComponent (Component* current);
  15006. /** Returns the component that should receive focus be default within the given
  15007. parent component.
  15008. The default implementation will just return the foremost child component that
  15009. wants focus.
  15010. This may return 0 if there's no suitable candidate.
  15011. */
  15012. virtual Component* getDefaultComponent (Component* parentComponent);
  15013. };
  15014. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  15015. /*** End of inlined file: juce_KeyboardFocusTraverser.h ***/
  15016. /*** Start of inlined file: juce_ImageEffectFilter.h ***/
  15017. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  15018. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  15019. /*** Start of inlined file: juce_Graphics.h ***/
  15020. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  15021. #define __JUCE_GRAPHICS_JUCEHEADER__
  15022. /*** Start of inlined file: juce_Font.h ***/
  15023. #ifndef __JUCE_FONT_JUCEHEADER__
  15024. #define __JUCE_FONT_JUCEHEADER__
  15025. /*** Start of inlined file: juce_Typeface.h ***/
  15026. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  15027. #define __JUCE_TYPEFACE_JUCEHEADER__
  15028. /*** Start of inlined file: juce_Path.h ***/
  15029. #ifndef __JUCE_PATH_JUCEHEADER__
  15030. #define __JUCE_PATH_JUCEHEADER__
  15031. /*** Start of inlined file: juce_Line.h ***/
  15032. #ifndef __JUCE_LINE_JUCEHEADER__
  15033. #define __JUCE_LINE_JUCEHEADER__
  15034. /**
  15035. Represents a line.
  15036. This class contains a bunch of useful methods for various geometric
  15037. tasks.
  15038. The ValueType template parameter should be a primitive type - float or double
  15039. are what it's designed for. Integer types will work in a basic way, but some methods
  15040. that perform mathematical operations may not compile, or they may not produce
  15041. sensible results.
  15042. @see Point, Rectangle, Path, Graphics::drawLine
  15043. */
  15044. template <typename ValueType>
  15045. class Line
  15046. {
  15047. public:
  15048. /** Creates a line, using (0, 0) as its start and end points. */
  15049. Line() throw() {}
  15050. /** Creates a copy of another line. */
  15051. Line (const Line& other) throw()
  15052. : start (other.start),
  15053. end (other.end)
  15054. {
  15055. }
  15056. /** Creates a line based on the co-ordinates of its start and end points. */
  15057. Line (ValueType startX, ValueType startY, ValueType endX, ValueType endY) throw()
  15058. : start (startX, startY),
  15059. end (endX, endY)
  15060. {
  15061. }
  15062. /** Creates a line from its start and end points. */
  15063. Line (const Point<ValueType>& startPoint,
  15064. const Point<ValueType>& endPoint) throw()
  15065. : start (startPoint),
  15066. end (endPoint)
  15067. {
  15068. }
  15069. /** Copies a line from another one. */
  15070. Line& operator= (const Line& other) throw()
  15071. {
  15072. start = other.start;
  15073. end = other.end;
  15074. return *this;
  15075. }
  15076. /** Destructor. */
  15077. ~Line() throw() {}
  15078. /** Returns the x co-ordinate of the line's start point. */
  15079. inline ValueType getStartX() const throw() { return start.getX(); }
  15080. /** Returns the y co-ordinate of the line's start point. */
  15081. inline ValueType getStartY() const throw() { return start.getY(); }
  15082. /** Returns the x co-ordinate of the line's end point. */
  15083. inline ValueType getEndX() const throw() { return end.getX(); }
  15084. /** Returns the y co-ordinate of the line's end point. */
  15085. inline ValueType getEndY() const throw() { return end.getY(); }
  15086. /** Returns the line's start point. */
  15087. inline const Point<ValueType>& getStart() const throw() { return start; }
  15088. /** Returns the line's end point. */
  15089. inline const Point<ValueType>& getEnd() const throw() { return end; }
  15090. /** Changes this line's start point */
  15091. void setStart (ValueType newStartX, ValueType newStartY) throw() { start.setXY (newStartX, newStartY); }
  15092. /** Changes this line's end point */
  15093. void setEnd (ValueType newEndX, ValueType newEndY) throw() { end.setXY (newEndX, newEndY); }
  15094. /** Changes this line's start point */
  15095. void setStart (const Point<ValueType>& newStart) throw() { start = newStart; }
  15096. /** Changes this line's end point */
  15097. void setEnd (const Point<ValueType>& newEnd) throw() { end = newEnd; }
  15098. /** Returns a line that is the same as this one, but with the start and end reversed, */
  15099. const Line reversed() const throw() { return Line (end, start); }
  15100. /** Applies an affine transform to the line's start and end points. */
  15101. void applyTransform (const AffineTransform& transform) throw()
  15102. {
  15103. start.applyTransform (transform);
  15104. end.applyTransform (transform);
  15105. }
  15106. /** Returns the length of the line. */
  15107. ValueType getLength() const throw() { return start.getDistanceFrom (end); }
  15108. /** Returns true if the line's start and end x co-ordinates are the same. */
  15109. bool isVertical() const throw() { return start.getX() == end.getX(); }
  15110. /** Returns true if the line's start and end y co-ordinates are the same. */
  15111. bool isHorizontal() const throw() { return start.getY() == end.getY(); }
  15112. /** Returns the line's angle.
  15113. This value is the number of radians clockwise from the 3 o'clock direction,
  15114. where the line's start point is considered to be at the centre.
  15115. */
  15116. ValueType getAngle() const throw() { return start.getAngleToPoint (end); }
  15117. /** Compares two lines. */
  15118. bool operator== (const Line& other) const throw() { return start == other.start && end == other.end; }
  15119. /** Compares two lines. */
  15120. bool operator!= (const Line& other) const throw() { return start != other.start || end != other.end; }
  15121. /** Finds the intersection between two lines.
  15122. @param line the other line
  15123. @param intersection the position of the point where the lines meet (or
  15124. where they would meet if they were infinitely long)
  15125. the intersection (if the lines intersect). If the lines
  15126. are parallel, this will just be set to the position
  15127. of one of the line's endpoints.
  15128. @returns true if the line segments intersect; false if they dont. Even if they
  15129. don't intersect, the intersection co-ordinates returned will still
  15130. be valid
  15131. */
  15132. bool intersects (const Line& line, Point<ValueType>& intersection) const throw()
  15133. {
  15134. return findIntersection (start, end, line.start, line.end, intersection);
  15135. }
  15136. /** Finds the intersection between two lines.
  15137. @param line the line to intersect with
  15138. @returns the point at which the lines intersect, even if this lies beyond the end of the lines
  15139. */
  15140. const Point<ValueType> getIntersection (const Line& line) const throw()
  15141. {
  15142. Point<ValueType> p;
  15143. findIntersection (start, end, line.start, line.end, p);
  15144. return p;
  15145. }
  15146. /** Returns the location of the point which is a given distance along this line.
  15147. @param distanceFromStart the distance to move along the line from its
  15148. start point. This value can be negative or longer
  15149. than the line itself
  15150. @see getPointAlongLineProportionally
  15151. */
  15152. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart) const throw()
  15153. {
  15154. return start + (end - start) * (distanceFromStart / getLength());
  15155. }
  15156. /** Returns a point which is a certain distance along and to the side of this line.
  15157. This effectively moves a given distance along the line, then another distance
  15158. perpendicularly to this, and returns the resulting position.
  15159. @param distanceFromStart the distance to move along the line from its
  15160. start point. This value can be negative or longer
  15161. than the line itself
  15162. @param perpendicularDistance how far to move sideways from the line. If you're
  15163. looking along the line from its start towards its
  15164. end, then a positive value here will move to the
  15165. right, negative value move to the left.
  15166. */
  15167. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart,
  15168. ValueType perpendicularDistance) const throw()
  15169. {
  15170. const Point<ValueType> delta (end - start);
  15171. const double length = juce_hypot (delta.getX(), delta.getY());
  15172. if (length == 0)
  15173. return start;
  15174. return Point<ValueType> (start.getX() + (ValueType) ((delta.getX() * distanceFromStart - delta.getY() * perpendicularDistance) / length),
  15175. start.getY() + (ValueType) ((delta.getY() * distanceFromStart + delta.getX() * perpendicularDistance) / length));
  15176. }
  15177. /** Returns the location of the point which is a given distance along this line
  15178. proportional to the line's length.
  15179. @param proportionOfLength the distance to move along the line from its
  15180. start point, in multiples of the line's length.
  15181. So a value of 0.0 will return the line's start point
  15182. and a value of 1.0 will return its end point. (This value
  15183. can be negative or greater than 1.0).
  15184. @see getPointAlongLine
  15185. */
  15186. const Point<ValueType> getPointAlongLineProportionally (ValueType proportionOfLength) const throw()
  15187. {
  15188. return start + (end - start) * proportionOfLength;
  15189. }
  15190. /** Returns the smallest distance between this line segment and a given point.
  15191. So if the point is close to the line, this will return the perpendicular
  15192. distance from the line; if the point is a long way beyond one of the line's
  15193. end-point's, it'll return the straight-line distance to the nearest end-point.
  15194. @returns the point's distance from the line
  15195. @see getPositionAlongLineOfNearestPoint
  15196. */
  15197. ValueType getDistanceFromLine (const Point<ValueType>& point) const throw()
  15198. {
  15199. const Point<ValueType> delta (end - start);
  15200. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  15201. if (length > 0)
  15202. {
  15203. const double prop = ((point.getX() - start.getX()) * delta.getX()
  15204. + (point.getY() - start.getY()) * delta.getY()) / length;
  15205. if (prop >= 0 && prop <= 1.0)
  15206. return point.getDistanceFrom (start + delta * (ValueType) prop);
  15207. }
  15208. return jmin (point.getDistanceFrom (start),
  15209. point.getDistanceFrom (end));
  15210. }
  15211. /** Finds the point on this line which is nearest to a given point, and
  15212. returns its position as a proportional position along the line.
  15213. @returns a value 0 to 1.0 which is the distance along this line from the
  15214. line's start to the point which is nearest to the point passed-in. To
  15215. turn this number into a position, use getPointAlongLineProportionally().
  15216. @see getDistanceFromLine, getPointAlongLineProportionally
  15217. */
  15218. ValueType findNearestPointTo (const Point<ValueType>& point) const throw()
  15219. {
  15220. const Point<ValueType> delta (end - start);
  15221. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  15222. return length <= 0 ? 0
  15223. : jlimit ((ValueType) 0, (ValueType) 1,
  15224. (ValueType) (((point.getX() - start.getX()) * delta.getX()
  15225. + (point.getY() - start.getY()) * delta.getY()) / length));
  15226. }
  15227. /** Returns true if the given point lies above this line.
  15228. The return value is true if the point's y coordinate is less than the y
  15229. coordinate of this line at the given x (assuming the line extends infinitely
  15230. in both directions).
  15231. */
  15232. bool isPointAbove (const Point<ValueType>& point) const throw()
  15233. {
  15234. return start.getX() != end.getX()
  15235. && point.getY() < ((end.getY() - start.getY())
  15236. * (point.getX() - start.getX())) / (end.getX() - start.getX()) + start.getY();
  15237. }
  15238. /** Returns a shortened copy of this line.
  15239. This will chop off part of the start of this line by a certain amount, (leaving the
  15240. end-point the same), and return the new line.
  15241. */
  15242. const Line withShortenedStart (ValueType distanceToShortenBy) const throw()
  15243. {
  15244. return Line (getPointAlongLine (jmin (distanceToShortenBy, getLength())), end);
  15245. }
  15246. /** Returns a shortened copy of this line.
  15247. This will chop off part of the end of this line by a certain amount, (leaving the
  15248. start-point the same), and return the new line.
  15249. */
  15250. const Line withShortenedEnd (ValueType distanceToShortenBy) const throw()
  15251. {
  15252. const ValueType length = getLength();
  15253. return Line (start, getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  15254. }
  15255. juce_UseDebuggingNewOperator
  15256. private:
  15257. Point<ValueType> start, end;
  15258. static bool findIntersection (const Point<ValueType>& p1, const Point<ValueType>& p2,
  15259. const Point<ValueType>& p3, const Point<ValueType>& p4,
  15260. Point<ValueType>& intersection) throw()
  15261. {
  15262. if (p2 == p3)
  15263. {
  15264. intersection = p2;
  15265. return true;
  15266. }
  15267. const Point<ValueType> d1 (p2 - p1);
  15268. const Point<ValueType> d2 (p4 - p3);
  15269. const ValueType divisor = d1.getX() * d2.getY() - d2.getX() * d1.getY();
  15270. if (divisor == 0)
  15271. {
  15272. if (! (d1.isOrigin() || d2.isOrigin()))
  15273. {
  15274. if (d1.getY() == 0 && d2.getY() != 0)
  15275. {
  15276. const ValueType along = (p1.getY() - p3.getY()) / d2.getY();
  15277. intersection = p1.withX (p3.getX() + along * d2.getX());
  15278. return along >= 0 && along <= (ValueType) 1;
  15279. }
  15280. else if (d2.getY() == 0 && d1.getY() != 0)
  15281. {
  15282. const ValueType along = (p3.getY() - p1.getY()) / d1.getY();
  15283. intersection = p3.withX (p1.getX() + along * d1.getX());
  15284. return along >= 0 && along <= (ValueType) 1;
  15285. }
  15286. else if (d1.getX() == 0 && d2.getX() != 0)
  15287. {
  15288. const ValueType along = (p1.getX() - p3.getX()) / d2.getX();
  15289. intersection = p1.withY (p3.getY() + along * d2.getY());
  15290. return along >= 0 && along <= (ValueType) 1;
  15291. }
  15292. else if (d2.getX() == 0 && d1.getX() != 0)
  15293. {
  15294. const ValueType along = (p3.getX() - p1.getX()) / d1.getX();
  15295. intersection = p3.withY (p1.getY() + along * d1.getY());
  15296. return along >= 0 && along <= (ValueType) 1;
  15297. }
  15298. }
  15299. intersection = (p2 + p3) / (ValueType) 2;
  15300. return false;
  15301. }
  15302. const ValueType along1 = ((p1.getY() - p3.getY()) * d2.getX() - (p1.getX() - p3.getX()) * d2.getY()) / divisor;
  15303. intersection = p1 + d1 * along1;
  15304. if (along1 < 0 || along1 > (ValueType) 1)
  15305. return false;
  15306. const ValueType along2 = ((p1.getY() - p3.getY()) * d1.getX() - (p1.getX() - p3.getX()) * d1.getY()) / divisor;
  15307. return along2 >= 0 && along2 <= (ValueType) 1;
  15308. }
  15309. };
  15310. #endif // __JUCE_LINE_JUCEHEADER__
  15311. /*** End of inlined file: juce_Line.h ***/
  15312. /*** Start of inlined file: juce_Rectangle.h ***/
  15313. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  15314. #define __JUCE_RECTANGLE_JUCEHEADER__
  15315. class RectangleList;
  15316. /**
  15317. Manages a rectangle and allows geometric operations to be performed on it.
  15318. @see RectangleList, Path, Line, Point
  15319. */
  15320. template <typename ValueType>
  15321. class Rectangle
  15322. {
  15323. public:
  15324. /** Creates a rectangle of zero size.
  15325. The default co-ordinates will be (0, 0, 0, 0).
  15326. */
  15327. Rectangle() throw()
  15328. : x (0), y (0), w (0), h (0)
  15329. {
  15330. }
  15331. /** Creates a copy of another rectangle. */
  15332. Rectangle (const Rectangle& other) throw()
  15333. : x (other.x), y (other.y),
  15334. w (other.w), h (other.h)
  15335. {
  15336. }
  15337. /** Creates a rectangle with a given position and size. */
  15338. Rectangle (const ValueType initialX, const ValueType initialY,
  15339. const ValueType width, const ValueType height) throw()
  15340. : x (initialX), y (initialY),
  15341. w (width), h (height)
  15342. {
  15343. }
  15344. /** Creates a rectangle with a given size, and a position of (0, 0). */
  15345. Rectangle (const ValueType width, const ValueType height) throw()
  15346. : x (0), y (0), w (width), h (height)
  15347. {
  15348. }
  15349. /** Creates a Rectangle from the positions of two opposite corners. */
  15350. Rectangle (const Point<ValueType>& corner1, const Point<ValueType>& corner2) throw()
  15351. : x (jmin (corner1.getX(), corner2.getX())),
  15352. y (jmin (corner1.getY(), corner2.getY())),
  15353. w (corner1.getX() - corner2.getX()),
  15354. h (corner1.getY() - corner2.getY())
  15355. {
  15356. if (w < 0) w = -w;
  15357. if (h < 0) h = -h;
  15358. }
  15359. Rectangle& operator= (const Rectangle& other) throw()
  15360. {
  15361. x = other.x; y = other.y;
  15362. w = other.w; h = other.h;
  15363. return *this;
  15364. }
  15365. /** Destructor. */
  15366. ~Rectangle() throw() {}
  15367. /** Returns true if the rectangle's width and height are both zero or less */
  15368. bool isEmpty() const throw() { return w <= 0 || h <= 0; }
  15369. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  15370. inline ValueType getX() const throw() { return x; }
  15371. /** Returns the y co-ordinate of the rectangle's top edge. */
  15372. inline ValueType getY() const throw() { return y; }
  15373. /** Returns the width of the rectangle. */
  15374. inline ValueType getWidth() const throw() { return w; }
  15375. /** Returns the height of the rectangle. */
  15376. inline ValueType getHeight() const throw() { return h; }
  15377. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  15378. inline ValueType getRight() const throw() { return x + w; }
  15379. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  15380. inline ValueType getBottom() const throw() { return y + h; }
  15381. /** Returns the x co-ordinate of the rectangle's centre. */
  15382. ValueType getCentreX() const throw() { return x + w / (ValueType) 2; }
  15383. /** Returns the y co-ordinate of the rectangle's centre. */
  15384. ValueType getCentreY() const throw() { return y + h / (ValueType) 2; }
  15385. /** Returns the centre point of the rectangle. */
  15386. const Point<ValueType> getCentre() const throw() { return Point<ValueType> (x + w / (ValueType) 2, y + h / (ValueType) 2); }
  15387. /** Returns the aspect ratio of the rectangle's width / height.
  15388. If widthOverHeight is true, it returns width / height; if widthOverHeight is false,
  15389. it returns height / width. */
  15390. ValueType getAspectRatio (const bool widthOverHeight = true) const throw() { return widthOverHeight ? w / h : h / w; }
  15391. /** Returns the rectangle's top-left position as a Point. */
  15392. const Point<ValueType> getPosition() const throw() { return Point<ValueType> (x, y); }
  15393. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  15394. void setPosition (const Point<ValueType>& newPos) throw() { x = newPos.getX(); y = newPos.getY(); }
  15395. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  15396. void setPosition (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  15397. /** Returns a rectangle with the same size as this one, but a new position. */
  15398. const Rectangle withPosition (const Point<ValueType>& newPos) const throw() { return Rectangle (newPos.getX(), newPos.getY(), w, h); }
  15399. /** Returns the rectangle's top-left position as a Point. */
  15400. const Point<ValueType> getTopLeft() const throw() { return getPosition(); }
  15401. /** Returns the rectangle's top-right position as a Point. */
  15402. const Point<ValueType> getTopRight() const throw() { return Point<float> (x + w, y); }
  15403. /** Returns the rectangle's bottom-left position as a Point. */
  15404. const Point<ValueType> getBottomLeft() const throw() { return Point<float> (x, y + h); }
  15405. /** Returns the rectangle's bottom-right position as a Point. */
  15406. const Point<ValueType> getBottomRight() const throw() { return Point<float> (x + w, y + h); }
  15407. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  15408. void setSize (const ValueType newWidth, const ValueType newHeight) throw() { w = newWidth; h = newHeight; }
  15409. /** Returns a rectangle with the same position as this one, but a new size. */
  15410. const Rectangle withSize (const ValueType newWidth, const ValueType newHeight) const throw() { return Rectangle (x, y, newWidth, newHeight); }
  15411. /** Changes all the rectangle's co-ordinates. */
  15412. void setBounds (const ValueType newX, const ValueType newY,
  15413. const ValueType newWidth, const ValueType newHeight) throw()
  15414. {
  15415. x = newX; y = newY; w = newWidth; h = newHeight;
  15416. }
  15417. /** Changes the rectangle's width */
  15418. void setWidth (const ValueType newWidth) throw() { w = newWidth; }
  15419. /** Changes the rectangle's height */
  15420. void setHeight (const ValueType newHeight) throw() { h = newHeight; }
  15421. /** Returns a rectangle which has the same size and y-position as this one, but with a different x-position. */
  15422. const Rectangle withX (const ValueType newX) const throw() { return Rectangle (newX, y, w, h); }
  15423. /** Returns a rectangle which has the same size and x-position as this one, but with a different y-position. */
  15424. const Rectangle withY (const ValueType newY) const throw() { return Rectangle (x, newY, w, h); }
  15425. /** Returns a rectangle which has the same position and height as this one, but with a different width. */
  15426. const Rectangle withWidth (const ValueType newWidth) const throw() { return Rectangle (x, y, newWidth, h); }
  15427. /** Returns a rectangle which has the same position and width as this one, but with a different height. */
  15428. const Rectangle withHeight (const ValueType newHeight) const throw() { return Rectangle (x, y, w, newHeight); }
  15429. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  15430. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  15431. */
  15432. void setLeft (const ValueType newLeft) throw()
  15433. {
  15434. w = jmax (ValueType(), x + w - newLeft);
  15435. x = newLeft;
  15436. }
  15437. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  15438. If the y is moved to be below the current bottom edge, the height will be set to zero.
  15439. */
  15440. void setTop (const ValueType newTop) throw()
  15441. {
  15442. h = jmax (ValueType(), y + h - newTop);
  15443. y = newTop;
  15444. }
  15445. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  15446. If the new right is below the current X value, the X will be pushed down to match it.
  15447. @see getRight
  15448. */
  15449. void setRight (const ValueType newRight) throw()
  15450. {
  15451. x = jmin (x, newRight);
  15452. w = newRight - x;
  15453. }
  15454. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  15455. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  15456. @see getBottom
  15457. */
  15458. void setBottom (const ValueType newBottom) throw()
  15459. {
  15460. y = jmin (y, newBottom);
  15461. h = newBottom - y;
  15462. }
  15463. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  15464. void translate (const ValueType deltaX,
  15465. const ValueType deltaY) throw()
  15466. {
  15467. x += deltaX;
  15468. y += deltaY;
  15469. }
  15470. /** Returns a rectangle which is the same as this one moved by a given amount. */
  15471. const Rectangle translated (const ValueType deltaX,
  15472. const ValueType deltaY) const throw()
  15473. {
  15474. return Rectangle (x + deltaX, y + deltaY, w, h);
  15475. }
  15476. /** Returns a rectangle which is the same as this one moved by a given amount. */
  15477. const Rectangle operator+ (const Point<ValueType>& deltaPosition) const throw()
  15478. {
  15479. return Rectangle (x + deltaPosition.getX(), y + deltaPosition.getY(), w, h);
  15480. }
  15481. /** Moves this rectangle by a given amount. */
  15482. Rectangle& operator+= (const Point<ValueType>& deltaPosition) throw()
  15483. {
  15484. x += deltaPosition.getX(); y += deltaPosition.getY();
  15485. return *this;
  15486. }
  15487. /** Returns a rectangle which is the same as this one moved by a given amount. */
  15488. const Rectangle operator- (const Point<ValueType>& deltaPosition) const throw()
  15489. {
  15490. return Rectangle (x - deltaPosition.getX(), y - deltaPosition.getY(), w, h);
  15491. }
  15492. /** Moves this rectangle by a given amount. */
  15493. Rectangle& operator-= (const Point<ValueType>& deltaPosition) throw()
  15494. {
  15495. x -= deltaPosition.getX(); y -= deltaPosition.getY();
  15496. return *this;
  15497. }
  15498. /** Expands the rectangle by a given amount.
  15499. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  15500. @see expanded, reduce, reduced
  15501. */
  15502. void expand (const ValueType deltaX,
  15503. const ValueType deltaY) throw()
  15504. {
  15505. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  15506. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  15507. setBounds (x - deltaX, y - deltaY, nw, nh);
  15508. }
  15509. /** Returns a rectangle that is larger than this one by a given amount.
  15510. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  15511. @see expand, reduce, reduced
  15512. */
  15513. const Rectangle expanded (const ValueType deltaX,
  15514. const ValueType deltaY) const throw()
  15515. {
  15516. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  15517. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  15518. return Rectangle (x - deltaX, y - deltaY, nw, nh);
  15519. }
  15520. /** Shrinks the rectangle by a given amount.
  15521. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  15522. @see reduced, expand, expanded
  15523. */
  15524. void reduce (const ValueType deltaX,
  15525. const ValueType deltaY) throw()
  15526. {
  15527. expand (-deltaX, -deltaY);
  15528. }
  15529. /** Returns a rectangle that is smaller than this one by a given amount.
  15530. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  15531. @see reduce, expand, expanded
  15532. */
  15533. const Rectangle reduced (const ValueType deltaX,
  15534. const ValueType deltaY) const throw()
  15535. {
  15536. return expanded (-deltaX, -deltaY);
  15537. }
  15538. /** Returns true if the two rectangles are identical. */
  15539. bool operator== (const Rectangle& other) const throw()
  15540. {
  15541. return x == other.x && y == other.y
  15542. && w == other.w && h == other.h;
  15543. }
  15544. /** Returns true if the two rectangles are not identical. */
  15545. bool operator!= (const Rectangle& other) const throw()
  15546. {
  15547. return x != other.x || y != other.y
  15548. || w != other.w || h != other.h;
  15549. }
  15550. /** Returns true if this co-ordinate is inside the rectangle. */
  15551. bool contains (const ValueType xCoord, const ValueType yCoord) const throw()
  15552. {
  15553. return xCoord >= x && yCoord >= y && xCoord < x + w && yCoord < y + h;
  15554. }
  15555. /** Returns true if this co-ordinate is inside the rectangle. */
  15556. bool contains (const Point<ValueType>& point) const throw()
  15557. {
  15558. return point.getX() >= x && point.getY() >= y && point.getX() < x + w && point.getY() < y + h;
  15559. }
  15560. /** Returns true if this other rectangle is completely inside this one. */
  15561. bool contains (const Rectangle& other) const throw()
  15562. {
  15563. return x <= other.x && y <= other.y
  15564. && x + w >= other.x + other.w && y + h >= other.y + other.h;
  15565. }
  15566. /** Returns the nearest point to the specified point that lies within this rectangle. */
  15567. const Point<ValueType> getConstrainedPoint (const Point<ValueType>& point) const throw()
  15568. {
  15569. return Point<ValueType> (jlimit (x, x + w, point.getX()),
  15570. jlimit (y, y + h, point.getY()));
  15571. }
  15572. /** Returns true if any part of another rectangle overlaps this one. */
  15573. bool intersects (const Rectangle& other) const throw()
  15574. {
  15575. return x + w > other.x
  15576. && y + h > other.y
  15577. && x < other.x + other.w
  15578. && y < other.y + other.h
  15579. && w > ValueType() && h > ValueType();
  15580. }
  15581. /** Returns the region that is the overlap between this and another rectangle.
  15582. If the two rectangles don't overlap, the rectangle returned will be empty.
  15583. */
  15584. const Rectangle getIntersection (const Rectangle& other) const throw()
  15585. {
  15586. const ValueType nx = jmax (x, other.x);
  15587. const ValueType ny = jmax (y, other.y);
  15588. const ValueType nw = jmin (x + w, other.x + other.w) - nx;
  15589. const ValueType nh = jmin (y + h, other.y + other.h) - ny;
  15590. if (nw >= ValueType() && nh >= ValueType())
  15591. return Rectangle (nx, ny, nw, nh);
  15592. return Rectangle();
  15593. }
  15594. /** Clips a rectangle so that it lies only within this one.
  15595. This is a non-static version of intersectRectangles().
  15596. Returns false if the two regions didn't overlap.
  15597. */
  15598. bool intersectRectangle (ValueType& otherX, ValueType& otherY, ValueType& otherW, ValueType& otherH) const throw()
  15599. {
  15600. const int maxX = jmax (otherX, x);
  15601. otherW = jmin (otherX + otherW, x + w) - maxX;
  15602. if (otherW > 0)
  15603. {
  15604. const int maxY = jmax (otherY, y);
  15605. otherH = jmin (otherY + otherH, y + h) - maxY;
  15606. if (otherH > 0)
  15607. {
  15608. otherX = maxX; otherY = maxY;
  15609. return true;
  15610. }
  15611. }
  15612. return false;
  15613. }
  15614. /** Returns the smallest rectangle that contains both this one and the one passed-in.
  15615. If either this or the other rectangle are empty, they will not be counted as
  15616. part of the resulting region.
  15617. */
  15618. const Rectangle getUnion (const Rectangle& other) const throw()
  15619. {
  15620. if (other.isEmpty()) return *this;
  15621. if (isEmpty()) return other;
  15622. const ValueType newX = jmin (x, other.x);
  15623. const ValueType newY = jmin (y, other.y);
  15624. return Rectangle (newX, newY,
  15625. jmax (x + w, other.x + other.w) - newX,
  15626. jmax (y + h, other.y + other.h) - newY);
  15627. }
  15628. /** If this rectangle merged with another one results in a simple rectangle, this
  15629. will set this rectangle to the result, and return true.
  15630. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  15631. or if they form a complex region.
  15632. */
  15633. bool enlargeIfAdjacent (const Rectangle& other) throw()
  15634. {
  15635. if (x == other.x && getRight() == other.getRight()
  15636. && (other.getBottom() >= y && other.y <= getBottom()))
  15637. {
  15638. const ValueType newY = jmin (y, other.y);
  15639. h = jmax (getBottom(), other.getBottom()) - newY;
  15640. y = newY;
  15641. return true;
  15642. }
  15643. else if (y == other.y && getBottom() == other.getBottom()
  15644. && (other.getRight() >= x && other.x <= getRight()))
  15645. {
  15646. const ValueType newX = jmin (x, other.x);
  15647. w = jmax (getRight(), other.getRight()) - newX;
  15648. x = newX;
  15649. return true;
  15650. }
  15651. return false;
  15652. }
  15653. /** If after removing another rectangle from this one the result is a simple rectangle,
  15654. this will set this object's bounds to be the result, and return true.
  15655. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  15656. or if removing the other one would form a complex region.
  15657. */
  15658. bool reduceIfPartlyContainedIn (const Rectangle& other) throw()
  15659. {
  15660. int inside = 0;
  15661. const int otherR = other.getRight();
  15662. if (x >= other.x && x < otherR) inside = 1;
  15663. const int otherB = other.getBottom();
  15664. if (y >= other.y && y < otherB) inside |= 2;
  15665. const int r = x + w;
  15666. if (r >= other.x && r < otherR) inside |= 4;
  15667. const int b = y + h;
  15668. if (b >= other.y && b < otherB) inside |= 8;
  15669. switch (inside)
  15670. {
  15671. case 1 + 2 + 8: w = r - otherR; x = otherR; return true;
  15672. case 1 + 2 + 4: h = b - otherB; y = otherB; return true;
  15673. case 2 + 4 + 8: w = other.x - x; return true;
  15674. case 1 + 4 + 8: h = other.y - y; return true;
  15675. }
  15676. return false;
  15677. }
  15678. /** Returns the smallest rectangle that can contain the shape created by applying
  15679. a transform to this rectangle.
  15680. This should only be used on floating point rectangles.
  15681. */
  15682. const Rectangle<ValueType> transformed (const AffineTransform& transform) const throw()
  15683. {
  15684. float x1 = x, y1 = y;
  15685. float x2 = x + w, y2 = y;
  15686. float x3 = x, y3 = y + h;
  15687. float x4 = x2, y4 = y3;
  15688. transform.transformPoint (x1, y1);
  15689. transform.transformPoint (x2, y2);
  15690. transform.transformPoint (x3, y3);
  15691. transform.transformPoint (x4, y4);
  15692. const float rx = jmin (x1, x2, x3, x4);
  15693. const float ry = jmin (y1, y2, y3, y4);
  15694. return Rectangle (rx, ry,
  15695. jmax (x1, x2, x3, x4) - rx,
  15696. jmax (y1, y2, y3, y4) - ry);
  15697. }
  15698. /** Returns the smallest integer-aligned rectangle that completely contains this one.
  15699. This is only relevent for floating-point rectangles, of course.
  15700. @see toFloat()
  15701. */
  15702. const Rectangle<int> getSmallestIntegerContainer() const throw()
  15703. {
  15704. const int x1 = (int) std::floor (static_cast<float> (x));
  15705. const int y1 = (int) std::floor (static_cast<float> (y));
  15706. const int x2 = (int) std::floor (static_cast<float> (x + w + 0.9999f));
  15707. const int y2 = (int) std::floor (static_cast<float> (y + h + 0.9999f));
  15708. return Rectangle<int> (x1, y1, x2 - x1, y2 - y1);
  15709. }
  15710. /** Returns the smallest Rectangle that can contain a set of points. */
  15711. static const Rectangle findAreaContainingPoints (const Point<ValueType>* const points, const int numPoints) throw()
  15712. {
  15713. if (numPoints == 0)
  15714. return Rectangle();
  15715. ValueType minX (points[0].getX());
  15716. ValueType maxX (minX);
  15717. ValueType minY (points[0].getY());
  15718. ValueType maxY (minY);
  15719. for (int i = 1; i < numPoints; ++i)
  15720. {
  15721. minX = jmin (minX, points[i].getX());
  15722. maxX = jmax (maxX, points[i].getX());
  15723. minY = jmin (minY, points[i].getY());
  15724. maxY = jmax (maxY, points[i].getY());
  15725. }
  15726. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  15727. }
  15728. /** Casts this rectangle to a Rectangle<float>.
  15729. Obviously this is mainly useful for rectangles that use integer types.
  15730. @see getSmallestIntegerContainer
  15731. */
  15732. const Rectangle<float> toFloat() const throw()
  15733. {
  15734. return Rectangle<float> (static_cast<float> (x), static_cast<float> (y),
  15735. static_cast<float> (w), static_cast<float> (h));
  15736. }
  15737. /** Static utility to intersect two sets of rectangular co-ordinates.
  15738. Returns false if the two regions didn't overlap.
  15739. @see intersectRectangle
  15740. */
  15741. static bool intersectRectangles (ValueType& x1, ValueType& y1, ValueType& w1, ValueType& h1,
  15742. const ValueType x2, const ValueType y2, const ValueType w2, const ValueType h2) throw()
  15743. {
  15744. const ValueType x = jmax (x1, x2);
  15745. w1 = jmin (x1 + w1, x2 + w2) - x;
  15746. if (w1 > 0)
  15747. {
  15748. const ValueType y = jmax (y1, y2);
  15749. h1 = jmin (y1 + h1, y2 + h2) - y;
  15750. if (h1 > 0)
  15751. {
  15752. x1 = x; y1 = y;
  15753. return true;
  15754. }
  15755. }
  15756. return false;
  15757. }
  15758. /** Creates a string describing this rectangle.
  15759. The string will be of the form "x y width height", e.g. "100 100 400 200".
  15760. Coupled with the fromString() method, this is very handy for things like
  15761. storing rectangles (particularly component positions) in XML attributes.
  15762. @see fromString
  15763. */
  15764. const String toString() const
  15765. {
  15766. String s;
  15767. s.preallocateStorage (16);
  15768. s << x << ' ' << y << ' ' << w << ' ' << h;
  15769. return s;
  15770. }
  15771. /** Parses a string containing a rectangle's details.
  15772. The string should contain 4 integer tokens, in the form "x y width height". They
  15773. can be comma or whitespace separated.
  15774. This method is intended to go with the toString() method, to form an easy way
  15775. of saving/loading rectangles as strings.
  15776. @see toString
  15777. */
  15778. static const Rectangle fromString (const String& stringVersion)
  15779. {
  15780. StringArray toks;
  15781. toks.addTokens (stringVersion.trim(), ",; \t\r\n", String::empty);
  15782. return Rectangle (toks[0].trim().getIntValue(),
  15783. toks[1].trim().getIntValue(),
  15784. toks[2].trim().getIntValue(),
  15785. toks[3].trim().getIntValue());
  15786. }
  15787. juce_UseDebuggingNewOperator
  15788. private:
  15789. friend class RectangleList;
  15790. ValueType x, y, w, h;
  15791. };
  15792. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  15793. /*** End of inlined file: juce_Rectangle.h ***/
  15794. /*** Start of inlined file: juce_Justification.h ***/
  15795. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  15796. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  15797. /**
  15798. Represents a type of justification to be used when positioning graphical items.
  15799. e.g. it indicates whether something should be placed top-left, top-right,
  15800. centred, etc.
  15801. It is used in various places wherever this kind of information is needed.
  15802. */
  15803. class JUCE_API Justification
  15804. {
  15805. public:
  15806. /** Creates a Justification object using a combination of flags. */
  15807. inline Justification (int flags_) throw() : flags (flags_) {}
  15808. /** Creates a copy of another Justification object. */
  15809. Justification (const Justification& other) throw();
  15810. /** Copies another Justification object. */
  15811. Justification& operator= (const Justification& other) throw();
  15812. bool operator== (const Justification& other) const throw() { return flags == other.flags; }
  15813. bool operator!= (const Justification& other) const throw() { return flags != other.flags; }
  15814. /** Returns the raw flags that are set for this Justification object. */
  15815. inline int getFlags() const throw() { return flags; }
  15816. /** Tests a set of flags for this object.
  15817. @returns true if any of the flags passed in are set on this object.
  15818. */
  15819. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  15820. /** Returns just the flags from this object that deal with vertical layout. */
  15821. int getOnlyVerticalFlags() const throw();
  15822. /** Returns just the flags from this object that deal with horizontal layout. */
  15823. int getOnlyHorizontalFlags() const throw();
  15824. /** Adjusts the position of a rectangle to fit it into a space.
  15825. The (x, y) position of the rectangle will be updated to position it inside the
  15826. given space according to the justification flags.
  15827. */
  15828. void applyToRectangle (int& x, int& y, int w, int h,
  15829. int spaceX, int spaceY, int spaceW, int spaceH) const throw();
  15830. /** Flag values that can be combined and used in the constructor. */
  15831. enum
  15832. {
  15833. /** Indicates that the item should be aligned against the left edge of the available space. */
  15834. left = 1,
  15835. /** Indicates that the item should be aligned against the right edge of the available space. */
  15836. right = 2,
  15837. /** Indicates that the item should be placed in the centre between the left and right
  15838. sides of the available space. */
  15839. horizontallyCentred = 4,
  15840. /** Indicates that the item should be aligned against the top edge of the available space. */
  15841. top = 8,
  15842. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  15843. bottom = 16,
  15844. /** Indicates that the item should be placed in the centre between the top and bottom
  15845. sides of the available space. */
  15846. verticallyCentred = 32,
  15847. /** Indicates that lines of text should be spread out to fill the maximum width
  15848. available, so that both margins are aligned vertically.
  15849. */
  15850. horizontallyJustified = 64,
  15851. /** Indicates that the item should be centred vertically and horizontally.
  15852. This is equivalent to (horizontallyCentred | verticallyCentred)
  15853. */
  15854. centred = 36,
  15855. /** Indicates that the item should be centred vertically but placed on the left hand side.
  15856. This is equivalent to (left | verticallyCentred)
  15857. */
  15858. centredLeft = 33,
  15859. /** Indicates that the item should be centred vertically but placed on the right hand side.
  15860. This is equivalent to (right | verticallyCentred)
  15861. */
  15862. centredRight = 34,
  15863. /** Indicates that the item should be centred horizontally and placed at the top.
  15864. This is equivalent to (horizontallyCentred | top)
  15865. */
  15866. centredTop = 12,
  15867. /** Indicates that the item should be centred horizontally and placed at the bottom.
  15868. This is equivalent to (horizontallyCentred | bottom)
  15869. */
  15870. centredBottom = 20,
  15871. /** Indicates that the item should be placed in the top-left corner.
  15872. This is equivalent to (left | top)
  15873. */
  15874. topLeft = 9,
  15875. /** Indicates that the item should be placed in the top-right corner.
  15876. This is equivalent to (right | top)
  15877. */
  15878. topRight = 10,
  15879. /** Indicates that the item should be placed in the bottom-left corner.
  15880. This is equivalent to (left | bottom)
  15881. */
  15882. bottomLeft = 17,
  15883. /** Indicates that the item should be placed in the bottom-left corner.
  15884. This is equivalent to (right | bottom)
  15885. */
  15886. bottomRight = 18
  15887. };
  15888. private:
  15889. int flags;
  15890. };
  15891. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  15892. /*** End of inlined file: juce_Justification.h ***/
  15893. class Image;
  15894. /**
  15895. A path is a sequence of lines and curves that may either form a closed shape
  15896. or be open-ended.
  15897. To use a path, you can create an empty one, then add lines and curves to it
  15898. to create shapes, then it can be rendered by a Graphics context or used
  15899. for geometric operations.
  15900. e.g. @code
  15901. Path myPath;
  15902. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  15903. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  15904. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  15905. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  15906. // add an ellipse as well, which will form a second sub-path within the path..
  15907. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  15908. // double the width of the whole thing..
  15909. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  15910. // and draw it to a graphics context with a 5-pixel thick outline.
  15911. g.strokePath (myPath, PathStrokeType (5.0f));
  15912. @endcode
  15913. A path object can actually contain multiple sub-paths, which may themselves
  15914. be open or closed.
  15915. @see PathFlatteningIterator, PathStrokeType, Graphics
  15916. */
  15917. class JUCE_API Path
  15918. {
  15919. public:
  15920. /** Creates an empty path. */
  15921. Path();
  15922. /** Creates a copy of another path. */
  15923. Path (const Path& other);
  15924. /** Destructor. */
  15925. ~Path();
  15926. /** Copies this path from another one. */
  15927. Path& operator= (const Path& other);
  15928. bool operator== (const Path& other) const throw();
  15929. bool operator!= (const Path& other) const throw();
  15930. /** Returns true if the path doesn't contain any lines or curves. */
  15931. bool isEmpty() const throw();
  15932. /** Returns the smallest rectangle that contains all points within the path.
  15933. */
  15934. const Rectangle<float> getBounds() const throw();
  15935. /** Returns the smallest rectangle that contains all points within the path
  15936. after it's been transformed with the given tranasform matrix.
  15937. */
  15938. const Rectangle<float> getBoundsTransformed (const AffineTransform& transform) const throw();
  15939. /** Checks whether a point lies within the path.
  15940. This is only relevent for closed paths (see closeSubPath()), and
  15941. may produce false results if used on a path which has open sub-paths.
  15942. The path's winding rule is taken into account by this method.
  15943. The tolerence parameter is passed to the PathFlatteningIterator that
  15944. is used to trace the path - for more info about it, see the notes for
  15945. the PathFlatteningIterator constructor.
  15946. @see closeSubPath, setUsingNonZeroWinding
  15947. */
  15948. bool contains (float x, float y,
  15949. float tolerence = 10.0f) const;
  15950. /** Checks whether a point lies within the path.
  15951. This is only relevent for closed paths (see closeSubPath()), and
  15952. may produce false results if used on a path which has open sub-paths.
  15953. The path's winding rule is taken into account by this method.
  15954. The tolerence parameter is passed to the PathFlatteningIterator that
  15955. is used to trace the path - for more info about it, see the notes for
  15956. the PathFlatteningIterator constructor.
  15957. @see closeSubPath, setUsingNonZeroWinding
  15958. */
  15959. bool contains (const Point<float>& point,
  15960. float tolerence = 10.0f) const;
  15961. /** Checks whether a line crosses the path.
  15962. This will return positive if the line crosses any of the paths constituent
  15963. lines or curves. It doesn't take into account whether the line is inside
  15964. or outside the path, or whether the path is open or closed.
  15965. The tolerence parameter is passed to the PathFlatteningIterator that
  15966. is used to trace the path - for more info about it, see the notes for
  15967. the PathFlatteningIterator constructor.
  15968. */
  15969. bool intersectsLine (const Line<float>& line,
  15970. float tolerence = 10.0f);
  15971. /** Cuts off parts of a line to keep the parts that are either inside or
  15972. outside this path.
  15973. Note that this isn't smart enough to cope with situations where the
  15974. line would need to be cut into multiple pieces to correctly clip against
  15975. a re-entrant shape.
  15976. @param line the line to clip
  15977. @param keepSectionOutsidePath if true, it's the section outside the path
  15978. that will be kept; if false its the section inside
  15979. the path
  15980. */
  15981. const Line<float> getClippedLine (const Line<float>& line, bool keepSectionOutsidePath) const;
  15982. /** Removes all lines and curves, resetting the path completely. */
  15983. void clear() throw();
  15984. /** Begins a new subpath with a given starting position.
  15985. This will move the path's current position to the co-ordinates passed in and
  15986. make it ready to draw lines or curves starting from this position.
  15987. After adding whatever lines and curves are needed, you can either
  15988. close the current sub-path using closeSubPath() or call startNewSubPath()
  15989. to move to a new sub-path, leaving the old one open-ended.
  15990. @see lineTo, quadraticTo, cubicTo, closeSubPath
  15991. */
  15992. void startNewSubPath (float startX, float startY);
  15993. /** Begins a new subpath with a given starting position.
  15994. This will move the path's current position to the co-ordinates passed in and
  15995. make it ready to draw lines or curves starting from this position.
  15996. After adding whatever lines and curves are needed, you can either
  15997. close the current sub-path using closeSubPath() or call startNewSubPath()
  15998. to move to a new sub-path, leaving the old one open-ended.
  15999. @see lineTo, quadraticTo, cubicTo, closeSubPath
  16000. */
  16001. void startNewSubPath (const Point<float>& start);
  16002. /** Closes a the current sub-path with a line back to its start-point.
  16003. When creating a closed shape such as a triangle, don't use 3 lineTo()
  16004. calls - instead use two lineTo() calls, followed by a closeSubPath()
  16005. to join the final point back to the start.
  16006. This ensures that closes shapes are recognised as such, and this is
  16007. important for tasks like drawing strokes, which needs to know whether to
  16008. draw end-caps or not.
  16009. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  16010. */
  16011. void closeSubPath();
  16012. /** Adds a line from the shape's last position to a new end-point.
  16013. This will connect the end-point of the last line or curve that was added
  16014. to a new point, using a straight line.
  16015. See the class description for an example of how to add lines and curves to a path.
  16016. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  16017. */
  16018. void lineTo (float endX, float endY);
  16019. /** Adds a line from the shape's last position to a new end-point.
  16020. This will connect the end-point of the last line or curve that was added
  16021. to a new point, using a straight line.
  16022. See the class description for an example of how to add lines and curves to a path.
  16023. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  16024. */
  16025. void lineTo (const Point<float>& end);
  16026. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  16027. This will connect the end-point of the last line or curve that was added
  16028. to a new point, using a quadratic spline with one control-point.
  16029. See the class description for an example of how to add lines and curves to a path.
  16030. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  16031. */
  16032. void quadraticTo (float controlPointX,
  16033. float controlPointY,
  16034. float endPointX,
  16035. float endPointY);
  16036. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  16037. This will connect the end-point of the last line or curve that was added
  16038. to a new point, using a quadratic spline with one control-point.
  16039. See the class description for an example of how to add lines and curves to a path.
  16040. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  16041. */
  16042. void quadraticTo (const Point<float>& controlPoint,
  16043. const Point<float>& endPoint);
  16044. /** Adds a cubic bezier curve from the shape's last position to a new position.
  16045. This will connect the end-point of the last line or curve that was added
  16046. to a new point, using a cubic spline with two control-points.
  16047. See the class description for an example of how to add lines and curves to a path.
  16048. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  16049. */
  16050. void cubicTo (float controlPoint1X,
  16051. float controlPoint1Y,
  16052. float controlPoint2X,
  16053. float controlPoint2Y,
  16054. float endPointX,
  16055. float endPointY);
  16056. /** Adds a cubic bezier curve from the shape's last position to a new position.
  16057. This will connect the end-point of the last line or curve that was added
  16058. to a new point, using a cubic spline with two control-points.
  16059. See the class description for an example of how to add lines and curves to a path.
  16060. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  16061. */
  16062. void cubicTo (const Point<float>& controlPoint1,
  16063. const Point<float>& controlPoint2,
  16064. const Point<float>& endPoint);
  16065. /** Returns the last point that was added to the path by one of the drawing methods.
  16066. */
  16067. const Point<float> getCurrentPosition() const;
  16068. /** Adds a rectangle to the path.
  16069. The rectangle is added as a new sub-path. (Any currently open paths will be
  16070. left open).
  16071. @see addRoundedRectangle, addTriangle
  16072. */
  16073. void addRectangle (float x, float y, float width, float height);
  16074. /** Adds a rectangle to the path.
  16075. The rectangle is added as a new sub-path. (Any currently open paths will be
  16076. left open).
  16077. @see addRoundedRectangle, addTriangle
  16078. */
  16079. void addRectangle (const Rectangle<int>& rectangle);
  16080. /** Adds a rectangle with rounded corners to the path.
  16081. The rectangle is added as a new sub-path. (Any currently open paths will be
  16082. left open).
  16083. @see addRectangle, addTriangle
  16084. */
  16085. void addRoundedRectangle (float x, float y, float width, float height,
  16086. float cornerSize);
  16087. /** Adds a rectangle with rounded corners to the path.
  16088. The rectangle is added as a new sub-path. (Any currently open paths will be
  16089. left open).
  16090. @see addRectangle, addTriangle
  16091. */
  16092. void addRoundedRectangle (float x, float y, float width, float height,
  16093. float cornerSizeX,
  16094. float cornerSizeY);
  16095. /** Adds a triangle to the path.
  16096. The triangle is added as a new closed sub-path. (Any currently open paths will be
  16097. left open).
  16098. Note that whether the vertices are specified in clockwise or anticlockwise
  16099. order will affect how the triangle is filled when it overlaps other
  16100. shapes (the winding order setting will affect this of course).
  16101. */
  16102. void addTriangle (float x1, float y1,
  16103. float x2, float y2,
  16104. float x3, float y3);
  16105. /** Adds a quadrilateral to the path.
  16106. The quad is added as a new closed sub-path. (Any currently open paths will be
  16107. left open).
  16108. Note that whether the vertices are specified in clockwise or anticlockwise
  16109. order will affect how the quad is filled when it overlaps other
  16110. shapes (the winding order setting will affect this of course).
  16111. */
  16112. void addQuadrilateral (float x1, float y1,
  16113. float x2, float y2,
  16114. float x3, float y3,
  16115. float x4, float y4);
  16116. /** Adds an ellipse to the path.
  16117. The shape is added as a new sub-path. (Any currently open paths will be
  16118. left open).
  16119. @see addArc
  16120. */
  16121. void addEllipse (float x, float y, float width, float height);
  16122. /** Adds an elliptical arc to the current path.
  16123. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  16124. or anti-clockwise according to whether the end angle is greater than the start. This means
  16125. that sometimes you may need to use values greater than 2*Pi for the end angle.
  16126. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  16127. @param y the top edge of the rectangle in which the elliptical outline fits
  16128. @param width the width of the rectangle in which the elliptical outline fits
  16129. @param height the height of the rectangle in which the elliptical outline fits
  16130. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  16131. top-centre of the ellipse)
  16132. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  16133. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  16134. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  16135. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  16136. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  16137. it will be added to the current sub-path, continuing from the current postition
  16138. @see addCentredArc, arcTo, addPieSegment, addEllipse
  16139. */
  16140. void addArc (float x, float y, float width, float height,
  16141. float fromRadians,
  16142. float toRadians,
  16143. bool startAsNewSubPath = false);
  16144. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  16145. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  16146. or anti-clockwise according to whether the end angle is greater than the start. This means
  16147. that sometimes you may need to use values greater than 2*Pi for the end angle.
  16148. @param centreX the centre x of the ellipse
  16149. @param centreY the centre y of the ellipse
  16150. @param radiusX the horizontal radius of the ellipse
  16151. @param radiusY the vertical radius of the ellipse
  16152. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  16153. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  16154. top-centre of the ellipse)
  16155. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  16156. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  16157. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  16158. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  16159. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  16160. it will be added to the current sub-path, continuing from the current postition
  16161. @see addArc, arcTo
  16162. */
  16163. void addCentredArc (float centreX, float centreY,
  16164. float radiusX, float radiusY,
  16165. float rotationOfEllipse,
  16166. float fromRadians,
  16167. float toRadians,
  16168. bool startAsNewSubPath = false);
  16169. /** Adds a "pie-chart" shape to the path.
  16170. The shape is added as a new sub-path. (Any currently open paths will be
  16171. left open).
  16172. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  16173. or anti-clockwise according to whether the end angle is greater than the start. This means
  16174. that sometimes you may need to use values greater than 2*Pi for the end angle.
  16175. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  16176. @param y the top edge of the rectangle in which the elliptical outline fits
  16177. @param width the width of the rectangle in which the elliptical outline fits
  16178. @param height the height of the rectangle in which the elliptical outline fits
  16179. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  16180. top-centre of the ellipse)
  16181. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  16182. top-centre of the ellipse)
  16183. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  16184. ellipse at its centre, where this value indicates the inner ellipse's size with
  16185. respect to the outer one.
  16186. @see addArc
  16187. */
  16188. void addPieSegment (float x, float y,
  16189. float width, float height,
  16190. float fromRadians,
  16191. float toRadians,
  16192. float innerCircleProportionalSize);
  16193. /** Adds a line with a specified thickness.
  16194. The line is added as a new closed sub-path. (Any currently open paths will be
  16195. left open).
  16196. @see addArrow
  16197. */
  16198. void addLineSegment (const Line<float>& line, float lineThickness);
  16199. /** Adds a line with an arrowhead on the end.
  16200. The arrow is added as a new closed sub-path. (Any currently open paths will be left open).
  16201. @see PathStrokeType::createStrokeWithArrowheads
  16202. */
  16203. void addArrow (const Line<float>& line,
  16204. float lineThickness,
  16205. float arrowheadWidth,
  16206. float arrowheadLength);
  16207. /** Adds a polygon shape to the path.
  16208. @see addStar
  16209. */
  16210. void addPolygon (const Point<float>& centre,
  16211. int numberOfSides,
  16212. float radius,
  16213. float startAngle = 0.0f);
  16214. /** Adds a star shape to the path.
  16215. @see addPolygon
  16216. */
  16217. void addStar (const Point<float>& centre,
  16218. int numberOfPoints,
  16219. float innerRadius,
  16220. float outerRadius,
  16221. float startAngle = 0.0f);
  16222. /** Adds a speech-bubble shape to the path.
  16223. @param bodyX the left of the main body area of the bubble
  16224. @param bodyY the top of the main body area of the bubble
  16225. @param bodyW the width of the main body area of the bubble
  16226. @param bodyH the height of the main body area of the bubble
  16227. @param cornerSize the amount by which to round off the corners of the main body rectangle
  16228. @param arrowTipX the x position that the tip of the arrow should connect to
  16229. @param arrowTipY the y position that the tip of the arrow should connect to
  16230. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  16231. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  16232. arrow's base should be - this is a proportional distance between 0 and 1.0
  16233. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  16234. */
  16235. void addBubble (float bodyX, float bodyY,
  16236. float bodyW, float bodyH,
  16237. float cornerSize,
  16238. float arrowTipX,
  16239. float arrowTipY,
  16240. int whichSide,
  16241. float arrowPositionAlongEdgeProportional,
  16242. float arrowWidth);
  16243. /** Adds another path to this one.
  16244. The new path is added as a new sub-path. (Any currently open paths in this
  16245. path will be left open).
  16246. @param pathToAppend the path to add
  16247. */
  16248. void addPath (const Path& pathToAppend);
  16249. /** Adds another path to this one, transforming it on the way in.
  16250. The new path is added as a new sub-path, its points being transformed by the given
  16251. matrix before being added.
  16252. @param pathToAppend the path to add
  16253. @param transformToApply an optional transform to apply to the incoming vertices
  16254. */
  16255. void addPath (const Path& pathToAppend,
  16256. const AffineTransform& transformToApply);
  16257. /** Swaps the contents of this path with another one.
  16258. The internal data of the two paths is swapped over, so this is much faster than
  16259. copying it to a temp variable and back.
  16260. */
  16261. void swapWithPath (Path& other) throw();
  16262. /** Applies a 2D transform to all the vertices in the path.
  16263. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  16264. */
  16265. void applyTransform (const AffineTransform& transform) throw();
  16266. /** Rescales this path to make it fit neatly into a given space.
  16267. This is effectively a quick way of calling
  16268. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  16269. @param x the x position of the rectangle to fit the path inside
  16270. @param y the y position of the rectangle to fit the path inside
  16271. @param width the width of the rectangle to fit the path inside
  16272. @param height the height of the rectangle to fit the path inside
  16273. @param preserveProportions if true, it will fit the path into the space without altering its
  16274. horizontal/vertical scale ratio; if false, it will distort the
  16275. path to fill the specified ratio both horizontally and vertically
  16276. @see applyTransform, getTransformToScaleToFit
  16277. */
  16278. void scaleToFit (float x, float y, float width, float height,
  16279. bool preserveProportions) throw();
  16280. /** Returns a transform that can be used to rescale the path to fit into a given space.
  16281. @param x the x position of the rectangle to fit the path inside
  16282. @param y the y position of the rectangle to fit the path inside
  16283. @param width the width of the rectangle to fit the path inside
  16284. @param height the height of the rectangle to fit the path inside
  16285. @param preserveProportions if true, it will fit the path into the space without altering its
  16286. horizontal/vertical scale ratio; if false, it will distort the
  16287. path to fill the specified ratio both horizontally and vertically
  16288. @param justificationType if the proportions are preseved, the resultant path may be smaller
  16289. than the available rectangle, so this describes how it should be
  16290. positioned within the space.
  16291. @returns an appropriate transformation
  16292. @see applyTransform, scaleToFit
  16293. */
  16294. const AffineTransform getTransformToScaleToFit (float x, float y, float width, float height,
  16295. bool preserveProportions,
  16296. const Justification& justificationType = Justification::centred) const;
  16297. /** Creates a version of this path where all sharp corners have been replaced by curves.
  16298. Wherever two lines meet at an angle, this will replace the corner with a curve
  16299. of the given radius.
  16300. */
  16301. const Path createPathWithRoundedCorners (float cornerRadius) const;
  16302. /** Changes the winding-rule to be used when filling the path.
  16303. If set to true (which is the default), then the path uses a non-zero-winding rule
  16304. to determine which points are inside the path. If set to false, it uses an
  16305. alternate-winding rule.
  16306. The winding-rule comes into play when areas of the shape overlap other
  16307. areas, and determines whether the overlapping regions are considered to be
  16308. inside or outside.
  16309. Changing this value just sets a flag - it doesn't affect the contents of the
  16310. path.
  16311. @see isUsingNonZeroWinding
  16312. */
  16313. void setUsingNonZeroWinding (bool isNonZeroWinding) throw();
  16314. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  16315. The default for a new path is true.
  16316. @see setUsingNonZeroWinding
  16317. */
  16318. bool isUsingNonZeroWinding() const { return useNonZeroWinding; }
  16319. /** Iterates the lines and curves that a path contains.
  16320. @see Path, PathFlatteningIterator
  16321. */
  16322. class JUCE_API Iterator
  16323. {
  16324. public:
  16325. Iterator (const Path& path);
  16326. ~Iterator();
  16327. /** Moves onto the next element in the path.
  16328. If this returns false, there are no more elements. If it returns true,
  16329. the elementType variable will be set to the type of the current element,
  16330. and some of the x and y variables will be filled in with values.
  16331. */
  16332. bool next();
  16333. enum PathElementType
  16334. {
  16335. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  16336. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  16337. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  16338. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  16339. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  16340. };
  16341. PathElementType elementType;
  16342. float x1, y1, x2, y2, x3, y3;
  16343. private:
  16344. const Path& path;
  16345. size_t index;
  16346. Iterator (const Iterator&);
  16347. Iterator& operator= (const Iterator&);
  16348. };
  16349. /** Loads a stored path from a data stream.
  16350. The data in the stream must have been written using writePathToStream().
  16351. Note that this will append the stored path to whatever is currently in
  16352. this path, so you might need to call clear() beforehand.
  16353. @see loadPathFromData, writePathToStream
  16354. */
  16355. void loadPathFromStream (InputStream& source);
  16356. /** Loads a stored path from a block of data.
  16357. This is similar to loadPathFromStream(), but just reads from a block
  16358. of data. Useful if you're including stored shapes in your code as a
  16359. block of static data.
  16360. @see loadPathFromStream, writePathToStream
  16361. */
  16362. void loadPathFromData (const void* data, int numberOfBytes);
  16363. /** Stores the path by writing it out to a stream.
  16364. After writing out a path, you can reload it using loadPathFromStream().
  16365. @see loadPathFromStream, loadPathFromData
  16366. */
  16367. void writePathToStream (OutputStream& destination) const;
  16368. /** Creates a string containing a textual representation of this path.
  16369. @see restoreFromString
  16370. */
  16371. const String toString() const;
  16372. /** Restores this path from a string that was created with the toString() method.
  16373. @see toString()
  16374. */
  16375. void restoreFromString (const String& stringVersion);
  16376. juce_UseDebuggingNewOperator
  16377. private:
  16378. friend class PathFlatteningIterator;
  16379. friend class Path::Iterator;
  16380. ArrayAllocationBase <float, DummyCriticalSection> data;
  16381. size_t numElements;
  16382. float pathXMin, pathXMax, pathYMin, pathYMax;
  16383. bool useNonZeroWinding;
  16384. static const float lineMarker;
  16385. static const float moveMarker;
  16386. static const float quadMarker;
  16387. static const float cubicMarker;
  16388. static const float closeSubPathMarker;
  16389. };
  16390. #endif // __JUCE_PATH_JUCEHEADER__
  16391. /*** End of inlined file: juce_Path.h ***/
  16392. class Font;
  16393. /** A typeface represents a size-independent font.
  16394. This base class is abstract, but calling createSystemTypefaceFor() will return
  16395. a platform-specific subclass that can be used.
  16396. The CustomTypeface subclass allow you to build your own typeface, and to
  16397. load and save it in the Juce typeface format.
  16398. Normally you should never need to deal directly with Typeface objects - the Font
  16399. class does everything you typically need for rendering text.
  16400. @see CustomTypeface, Font
  16401. */
  16402. class JUCE_API Typeface : public ReferenceCountedObject
  16403. {
  16404. public:
  16405. /** A handy typedef for a pointer to a typeface. */
  16406. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  16407. /** Returns the name of the typeface.
  16408. @see Font::getTypefaceName
  16409. */
  16410. const String getName() const throw() { return name; }
  16411. /** Creates a new system typeface. */
  16412. static const Ptr createSystemTypefaceFor (const Font& font);
  16413. /** Destructor. */
  16414. virtual ~Typeface();
  16415. /** Returns the ascent of the font, as a proportion of its height.
  16416. The height is considered to always be normalised as 1.0, so this will be a
  16417. value less that 1.0, indicating the proportion of the font that lies above
  16418. its baseline.
  16419. */
  16420. virtual float getAscent() const = 0;
  16421. /** Returns the descent of the font, as a proportion of its height.
  16422. The height is considered to always be normalised as 1.0, so this will be a
  16423. value less that 1.0, indicating the proportion of the font that lies below
  16424. its baseline.
  16425. */
  16426. virtual float getDescent() const = 0;
  16427. /** Measures the width of a line of text.
  16428. The distance returned is based on the font having an normalised height of 1.0.
  16429. You should never need to call this directly! Use Font::getStringWidth() instead!
  16430. */
  16431. virtual float getStringWidth (const String& text) = 0;
  16432. /** Converts a line of text into its glyph numbers and their positions.
  16433. The distances returned are based on the font having an normalised height of 1.0.
  16434. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  16435. */
  16436. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  16437. /** Returns the outline for a glyph.
  16438. The path returned will be normalised to a font height of 1.0.
  16439. */
  16440. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  16441. juce_UseDebuggingNewOperator
  16442. protected:
  16443. String name;
  16444. explicit Typeface (const String& name) throw();
  16445. private:
  16446. Typeface (const Typeface&);
  16447. Typeface& operator= (const Typeface&);
  16448. };
  16449. /** A typeface that can be populated with custom glyphs.
  16450. You can create a CustomTypeface if you need one that contains your own glyphs,
  16451. or if you need to load a typeface from a Juce-formatted binary stream.
  16452. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  16453. to copy glyphs into this face.
  16454. @see Typeface, Font
  16455. */
  16456. class JUCE_API CustomTypeface : public Typeface
  16457. {
  16458. public:
  16459. /** Creates a new, empty typeface. */
  16460. CustomTypeface();
  16461. /** Loads a typeface from a previously saved stream.
  16462. The stream must have been created by writeToStream().
  16463. @see writeToStream
  16464. */
  16465. explicit CustomTypeface (InputStream& serialisedTypefaceStream);
  16466. /** Destructor. */
  16467. ~CustomTypeface();
  16468. /** Resets this typeface, deleting all its glyphs and settings. */
  16469. void clear();
  16470. /** Sets the vital statistics for the typeface.
  16471. @param name the typeface's name
  16472. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  16473. the value that will be returned by Typeface::getAscent(). The
  16474. descent is assumed to be (1.0 - ascent)
  16475. @param isBold should be true if the typeface is bold
  16476. @param isItalic should be true if the typeface is italic
  16477. @param defaultCharacter the character to be used as a replacement if there's
  16478. no glyph available for the character that's being drawn
  16479. */
  16480. void setCharacteristics (const String& name, float ascent,
  16481. bool isBold, bool isItalic,
  16482. juce_wchar defaultCharacter) throw();
  16483. /** Adds a glyph to the typeface.
  16484. The path that is passed in is normalised so that the font height is 1.0, and its
  16485. origin is the anchor point of the character on its baseline.
  16486. The width is the nominal width of the character, and any extra kerning values that
  16487. are specified will be added to this width.
  16488. */
  16489. void addGlyph (juce_wchar character, const Path& path, float width) throw();
  16490. /** Specifies an extra kerning amount to be used between a pair of characters.
  16491. The amount will be added to the nominal width of the first character when laying out a string.
  16492. */
  16493. void addKerningPair (juce_wchar char1, juce_wchar char2, float extraAmount) throw();
  16494. /** Adds a range of glyphs from another typeface.
  16495. This will attempt to pull in the paths and kerning information from another typeface and
  16496. add it to this one.
  16497. */
  16498. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw();
  16499. /** Saves this typeface as a Juce-formatted font file.
  16500. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  16501. constructor.
  16502. */
  16503. bool writeToStream (OutputStream& outputStream);
  16504. // The following methods implement the basic Typeface behaviour.
  16505. float getAscent() const;
  16506. float getDescent() const;
  16507. float getStringWidth (const String& text);
  16508. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  16509. bool getOutlineForGlyph (int glyphNumber, Path& path);
  16510. int getGlyphForCharacter (juce_wchar character);
  16511. juce_UseDebuggingNewOperator
  16512. protected:
  16513. juce_wchar defaultCharacter;
  16514. float ascent;
  16515. bool isBold, isItalic;
  16516. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  16517. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  16518. particular character and there's no corresponding glyph, they'll call this
  16519. method so that a subclass can try to add that glyph, returning true if it
  16520. manages to do so.
  16521. */
  16522. virtual bool loadGlyphIfPossible (juce_wchar characterNeeded);
  16523. private:
  16524. class GlyphInfo;
  16525. friend class OwnedArray<GlyphInfo>;
  16526. OwnedArray <GlyphInfo> glyphs;
  16527. short lookupTable [128];
  16528. CustomTypeface (const CustomTypeface&);
  16529. CustomTypeface& operator= (const CustomTypeface&);
  16530. GlyphInfo* findGlyph (const juce_wchar character, bool loadIfNeeded) throw();
  16531. GlyphInfo* findGlyphSubstituting (juce_wchar character) throw();
  16532. };
  16533. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  16534. /*** End of inlined file: juce_Typeface.h ***/
  16535. class LowLevelGraphicsContext;
  16536. /**
  16537. Represents a particular font, including its size, style, etc.
  16538. Apart from the typeface to be used, a Font object also dictates whether
  16539. the font is bold, italic, underlined, how big it is, and its kerning and
  16540. horizontal scale factor.
  16541. @see Typeface
  16542. */
  16543. class JUCE_API Font
  16544. {
  16545. public:
  16546. /** A combination of these values is used by the constructor to specify the
  16547. style of font to use.
  16548. */
  16549. enum FontStyleFlags
  16550. {
  16551. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  16552. bold = 1, /**< boldens the font. @see setStyleFlags */
  16553. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  16554. underlined = 4 /**< underlines the font. @see setStyleFlags */
  16555. };
  16556. /** Creates a sans-serif font in a given size.
  16557. @param fontHeight the height in pixels (can be fractional)
  16558. @param styleFlags the style to use - this can be a combination of the
  16559. Font::bold, Font::italic and Font::underlined, or
  16560. just Font::plain for the normal style.
  16561. @see FontStyleFlags, getDefaultSansSerifFontName
  16562. */
  16563. Font (float fontHeight,
  16564. int styleFlags = plain) throw();
  16565. /** Creates a font with a given typeface and parameters.
  16566. @param typefaceName the name of the typeface to use
  16567. @param fontHeight the height in pixels (can be fractional)
  16568. @param styleFlags the style to use - this can be a combination of the
  16569. Font::bold, Font::italic and Font::underlined, or
  16570. just Font::plain for the normal style.
  16571. @see FontStyleFlags, getDefaultSansSerifFontName
  16572. */
  16573. Font (const String& typefaceName,
  16574. float fontHeight,
  16575. int styleFlags) throw();
  16576. /** Creates a copy of another Font object. */
  16577. Font (const Font& other) throw();
  16578. /** Creates a font for a typeface. */
  16579. Font (const Typeface::Ptr& typeface) throw();
  16580. /** Creates a basic sans-serif font at a default height.
  16581. You should use one of the other constructors for creating a font that you're planning
  16582. on drawing with - this constructor is here to help initialise objects before changing
  16583. the font's settings later.
  16584. */
  16585. Font() throw();
  16586. /** Copies this font from another one. */
  16587. Font& operator= (const Font& other) throw();
  16588. bool operator== (const Font& other) const throw();
  16589. bool operator!= (const Font& other) const throw();
  16590. /** Destructor. */
  16591. ~Font() throw();
  16592. /** Changes the name of the typeface family.
  16593. e.g. "Arial", "Courier", etc.
  16594. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  16595. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  16596. but are generic names that are used to represent the various default fonts.
  16597. If you need to know the exact typeface name being used, you can call
  16598. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  16599. If a suitable font isn't found on the machine, it'll just use a default instead.
  16600. */
  16601. void setTypefaceName (const String& faceName) throw();
  16602. /** Returns the name of the typeface family that this font uses.
  16603. e.g. "Arial", "Courier", etc.
  16604. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  16605. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  16606. but are generic names that are used to represent the various default fonts.
  16607. If you need to know the exact typeface name being used, you can call
  16608. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  16609. */
  16610. const String& getTypefaceName() const throw() { return font->typefaceName; }
  16611. /** Returns a typeface name that represents the default sans-serif font.
  16612. This is also the typeface that will be used when a font is created without
  16613. specifying any typeface details.
  16614. Note that this method just returns a generic placeholder string that means "the default
  16615. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  16616. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  16617. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  16618. */
  16619. static const String getDefaultSansSerifFontName() throw();
  16620. /** Returns a typeface name that represents the default sans-serif font.
  16621. Note that this method just returns a generic placeholder string that means "the default
  16622. serif font" - it's not the actual name of this font. To get the actual name, use
  16623. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  16624. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  16625. */
  16626. static const String getDefaultSerifFontName() throw();
  16627. /** Returns a typeface name that represents the default sans-serif font.
  16628. Note that this method just returns a generic placeholder string that means "the default
  16629. monospaced font" - it's not the actual name of this font. To get the actual name, use
  16630. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  16631. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  16632. */
  16633. static const String getDefaultMonospacedFontName() throw();
  16634. /** Returns the typeface names of the default fonts on the current platform. */
  16635. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed);
  16636. /** Returns the total height of this font.
  16637. This is the maximum height, from the top of the ascent to the bottom of the
  16638. descenders.
  16639. @see setHeight, setHeightWithoutChangingWidth, getAscent
  16640. */
  16641. float getHeight() const throw() { return font->height; }
  16642. /** Changes the font's height.
  16643. @see getHeight, setHeightWithoutChangingWidth
  16644. */
  16645. void setHeight (float newHeight) throw();
  16646. /** Changes the font's height without changing its width.
  16647. This alters the horizontal scale to compensate for the change in height.
  16648. */
  16649. void setHeightWithoutChangingWidth (float newHeight) throw();
  16650. /** Returns the height of the font above its baseline.
  16651. This is the maximum height from the baseline to the top.
  16652. @see getHeight, getDescent
  16653. */
  16654. float getAscent() const throw();
  16655. /** Returns the amount that the font descends below its baseline.
  16656. This is calculated as (getHeight() - getAscent()).
  16657. @see getAscent, getHeight
  16658. */
  16659. float getDescent() const throw();
  16660. /** Returns the font's style flags.
  16661. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  16662. enum, to describe whether the font is bold, italic, etc.
  16663. @see FontStyleFlags
  16664. */
  16665. int getStyleFlags() const throw() { return font->styleFlags; }
  16666. /** Changes the font's style.
  16667. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  16668. enum, to set the font's properties
  16669. @see FontStyleFlags
  16670. */
  16671. void setStyleFlags (int newFlags) throw();
  16672. /** Makes the font bold or non-bold. */
  16673. void setBold (bool shouldBeBold) throw();
  16674. /** Returns true if the font is bold. */
  16675. bool isBold() const throw();
  16676. /** Makes the font italic or non-italic. */
  16677. void setItalic (bool shouldBeItalic) throw();
  16678. /** Returns true if the font is italic. */
  16679. bool isItalic() const throw();
  16680. /** Makes the font underlined or non-underlined. */
  16681. void setUnderline (bool shouldBeUnderlined) throw();
  16682. /** Returns true if the font is underlined. */
  16683. bool isUnderlined() const throw();
  16684. /** Changes the font's horizontal scale factor.
  16685. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  16686. narrower, greater than 1.0 will be stretched out.
  16687. */
  16688. void setHorizontalScale (float scaleFactor) throw();
  16689. /** Returns the font's horizontal scale.
  16690. A value of 1.0 is the normal scale, less than this will be narrower, greater
  16691. than 1.0 will be stretched out.
  16692. @see setHorizontalScale
  16693. */
  16694. float getHorizontalScale() const throw() { return font->horizontalScale; }
  16695. /** Changes the font's kerning.
  16696. @param extraKerning a multiple of the font's height that will be added
  16697. to space between the characters. So a value of zero is
  16698. normal spacing, positive values spread the letters out,
  16699. negative values make them closer together.
  16700. */
  16701. void setExtraKerningFactor (float extraKerning) throw();
  16702. /** Returns the font's kerning.
  16703. This is the extra space added between adjacent characters, as a proportion
  16704. of the font's height.
  16705. A value of zero is normal spacing, positive values will spread the letters
  16706. out more, and negative values make them closer together.
  16707. */
  16708. float getExtraKerningFactor() const throw() { return font->kerning; }
  16709. /** Changes all the font's characteristics with one call. */
  16710. void setSizeAndStyle (float newHeight,
  16711. int newStyleFlags,
  16712. float newHorizontalScale,
  16713. float newKerningAmount) throw();
  16714. /** Returns the total width of a string as it would be drawn using this font.
  16715. For a more accurate floating-point result, use getStringWidthFloat().
  16716. */
  16717. int getStringWidth (const String& text) const throw();
  16718. /** Returns the total width of a string as it would be drawn using this font.
  16719. @see getStringWidth
  16720. */
  16721. float getStringWidthFloat (const String& text) const throw();
  16722. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  16723. An extra x offset is added at the end of the run, to indicate where the right hand
  16724. edge of the last character is.
  16725. */
  16726. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw();
  16727. /** Returns the typeface used by this font.
  16728. Note that the object returned may go out of scope if this font is deleted
  16729. or has its style changed.
  16730. */
  16731. Typeface* getTypeface() const throw();
  16732. /** Creates an array of Font objects to represent all the fonts on the system.
  16733. If you just need the names of the typefaces, you can also use
  16734. findAllTypefaceNames() instead.
  16735. @param results the array to which new Font objects will be added.
  16736. */
  16737. static void findFonts (Array<Font>& results) throw();
  16738. /** Returns a list of all the available typeface names.
  16739. The names returned can be passed into setTypefaceName().
  16740. You can use this instead of findFonts() if you only need their names, and not
  16741. font objects.
  16742. */
  16743. static const StringArray findAllTypefaceNames();
  16744. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  16745. in the requested typeface.
  16746. */
  16747. static const String getFallbackFontName() throw();
  16748. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  16749. available in whatever font you're trying to use.
  16750. */
  16751. static void setFallbackFontName (const String& name) throw();
  16752. /** Creates a string to describe this font.
  16753. The string will contain information to describe the font's typeface, size, and
  16754. style. To recreate the font from this string, use fromString().
  16755. */
  16756. const String toString() const;
  16757. /** Recreates a font from its stringified encoding.
  16758. This method takes a string that was created by toString(), and recreates the
  16759. original font.
  16760. */
  16761. static const Font fromString (const String& fontDescription);
  16762. juce_UseDebuggingNewOperator
  16763. private:
  16764. friend class FontGlyphAlphaMap;
  16765. friend class TypefaceCache;
  16766. class SharedFontInternal : public ReferenceCountedObject
  16767. {
  16768. public:
  16769. SharedFontInternal (const String& typefaceName, float height, float horizontalScale,
  16770. float kerning, float ascent, int styleFlags,
  16771. Typeface* typeface) throw();
  16772. SharedFontInternal (const SharedFontInternal& other) throw();
  16773. String typefaceName;
  16774. float height, horizontalScale, kerning, ascent;
  16775. int styleFlags;
  16776. Typeface::Ptr typeface;
  16777. };
  16778. ReferenceCountedObjectPtr <SharedFontInternal> font;
  16779. void dupeInternalIfShared() throw();
  16780. };
  16781. #endif // __JUCE_FONT_JUCEHEADER__
  16782. /*** End of inlined file: juce_Font.h ***/
  16783. /*** Start of inlined file: juce_PathStrokeType.h ***/
  16784. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  16785. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  16786. /**
  16787. Describes a type of stroke used to render a solid outline along a path.
  16788. A PathStrokeType object can be used directly to create the shape of an outline
  16789. around a path, and is used by Graphics::strokePath to specify the type of
  16790. stroke to draw.
  16791. @see Path, Graphics::strokePath
  16792. */
  16793. class JUCE_API PathStrokeType
  16794. {
  16795. public:
  16796. /** The type of shape to use for the corners between two adjacent line segments. */
  16797. enum JointStyle
  16798. {
  16799. mitered, /**< Indicates that corners should be drawn with sharp joints.
  16800. Note that for angles that curve back on themselves, drawing a
  16801. mitre could require extending the point too far away from the
  16802. path, so a mitre limit is imposed and any corners that exceed it
  16803. are drawn as bevelled instead. */
  16804. curved, /**< Indicates that corners should be drawn as rounded-off. */
  16805. beveled /**< Indicates that corners should be drawn with a line flattening their
  16806. outside edge. */
  16807. };
  16808. /** The type shape to use for the ends of lines. */
  16809. enum EndCapStyle
  16810. {
  16811. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  16812. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  16813. the thickness of the stroke. */
  16814. rounded /**< Ends of lines are rounded-off with a circular shape. */
  16815. };
  16816. /** Creates a stroke type.
  16817. @param strokeThickness the width of the line to use
  16818. @param jointStyle the type of joints to use for corners
  16819. @param endStyle the type of end-caps to use for the ends of open paths.
  16820. */
  16821. PathStrokeType (float strokeThickness,
  16822. JointStyle jointStyle = mitered,
  16823. EndCapStyle endStyle = butt) throw();
  16824. /** Createes a copy of another stroke type. */
  16825. PathStrokeType (const PathStrokeType& other) throw();
  16826. /** Copies another stroke onto this one. */
  16827. PathStrokeType& operator= (const PathStrokeType& other) throw();
  16828. /** Destructor. */
  16829. ~PathStrokeType() throw();
  16830. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  16831. @param destPath the resultant stroked outline shape will be copied into this path.
  16832. Note that it's ok for the source and destination Paths to be
  16833. the same object, so you can easily turn a path into a stroked version
  16834. of itself.
  16835. @param sourcePath the path to use as the source
  16836. @param transform an optional transform to apply to the points from the source path
  16837. as they are being used
  16838. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  16839. a higher resolution, which improved the quality if you'll later want
  16840. to enlarge the stroked path
  16841. @see createDashedStroke
  16842. */
  16843. void createStrokedPath (Path& destPath,
  16844. const Path& sourcePath,
  16845. const AffineTransform& transform = AffineTransform::identity,
  16846. float extraAccuracy = 1.0f) const;
  16847. /** Applies this stroke type to a path, creating a dashed line.
  16848. This is similar to createStrokedPath, but uses the array passed in to
  16849. break the stroke up into a series of dashes.
  16850. @param destPath the resultant stroked outline shape will be copied into this path.
  16851. Note that it's ok for the source and destination Paths to be
  16852. the same object, so you can easily turn a path into a stroked version
  16853. of itself.
  16854. @param sourcePath the path to use as the source
  16855. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  16856. a line of length 2, then skip a length of 3, then add a line of length 4,
  16857. skip 5, and keep repeating this pattern.
  16858. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  16859. an even number, otherwise the pattern will get out of step as it
  16860. repeats.
  16861. @param transform an optional transform to apply to the points from the source path
  16862. as they are being used
  16863. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  16864. a higher resolution, which improved the quality if you'll later want
  16865. to enlarge the stroked path
  16866. */
  16867. void createDashedStroke (Path& destPath,
  16868. const Path& sourcePath,
  16869. const float* dashLengths,
  16870. int numDashLengths,
  16871. const AffineTransform& transform = AffineTransform::identity,
  16872. float extraAccuracy = 1.0f) const;
  16873. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  16874. @param destPath the resultant stroked outline shape will be copied into this path.
  16875. Note that it's ok for the source and destination Paths to be
  16876. the same object, so you can easily turn a path into a stroked version
  16877. of itself.
  16878. @param sourcePath the path to use as the source
  16879. @param transform an optional transform to apply to the points from the source path
  16880. as they are being used
  16881. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  16882. a higher resolution, which improved the quality if you'll later want
  16883. to enlarge the stroked path
  16884. @see createDashedStroke
  16885. */
  16886. void createStrokeWithArrowheads (Path& destPath,
  16887. const Path& sourcePath,
  16888. float arrowheadStartWidth, float arrowheadStartLength,
  16889. float arrowheadEndWidth, float arrowheadEndLength,
  16890. const AffineTransform& transform = AffineTransform::identity,
  16891. float extraAccuracy = 1.0f) const;
  16892. /** Returns the stroke thickness. */
  16893. float getStrokeThickness() const throw() { return thickness; }
  16894. /** Sets the stroke thickness. */
  16895. void setStrokeThickness (float newThickness) throw() { thickness = newThickness; }
  16896. /** Returns the joint style. */
  16897. JointStyle getJointStyle() const throw() { return jointStyle; }
  16898. /** Sets the joint style. */
  16899. void setJointStyle (JointStyle newStyle) throw() { jointStyle = newStyle; }
  16900. /** Returns the end-cap style. */
  16901. EndCapStyle getEndStyle() const throw() { return endStyle; }
  16902. /** Sets the end-cap style. */
  16903. void setEndStyle (EndCapStyle newStyle) throw() { endStyle = newStyle; }
  16904. juce_UseDebuggingNewOperator
  16905. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  16906. bool operator== (const PathStrokeType& other) const throw();
  16907. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  16908. bool operator!= (const PathStrokeType& other) const throw();
  16909. private:
  16910. float thickness;
  16911. JointStyle jointStyle;
  16912. EndCapStyle endStyle;
  16913. };
  16914. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  16915. /*** End of inlined file: juce_PathStrokeType.h ***/
  16916. /*** Start of inlined file: juce_Colours.h ***/
  16917. #ifndef __JUCE_COLOURS_JUCEHEADER__
  16918. #define __JUCE_COLOURS_JUCEHEADER__
  16919. /*** Start of inlined file: juce_Colour.h ***/
  16920. #ifndef __JUCE_COLOUR_JUCEHEADER__
  16921. #define __JUCE_COLOUR_JUCEHEADER__
  16922. /*** Start of inlined file: juce_PixelFormats.h ***/
  16923. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  16924. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  16925. #if JUCE_MSVC
  16926. #pragma pack (push, 1)
  16927. #define PACKED
  16928. #elif JUCE_GCC
  16929. #define PACKED __attribute__((packed))
  16930. #else
  16931. #define PACKED
  16932. #endif
  16933. class PixelRGB;
  16934. class PixelAlpha;
  16935. /**
  16936. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  16937. operations with it.
  16938. This is used internally by the imaging classes.
  16939. @see PixelRGB
  16940. */
  16941. class JUCE_API PixelARGB
  16942. {
  16943. public:
  16944. /** Creates a pixel without defining its colour. */
  16945. PixelARGB() throw() {}
  16946. ~PixelARGB() throw() {}
  16947. /** Creates a pixel from a 32-bit argb value.
  16948. */
  16949. PixelARGB (const uint32 argb_) throw()
  16950. : argb (argb_)
  16951. {
  16952. }
  16953. forcedinline uint32 getARGB() const throw() { return argb; }
  16954. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  16955. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  16956. forcedinline uint8 getAlpha() const throw() { return components.a; }
  16957. forcedinline uint8 getRed() const throw() { return components.r; }
  16958. forcedinline uint8 getGreen() const throw() { return components.g; }
  16959. forcedinline uint8 getBlue() const throw() { return components.b; }
  16960. /** Blends another pixel onto this one.
  16961. This takes into account the opacity of the pixel being overlaid, and blends
  16962. it accordingly.
  16963. */
  16964. forcedinline void blend (const PixelARGB& src) throw()
  16965. {
  16966. uint32 sargb = src.getARGB();
  16967. const uint32 alpha = 0x100 - (sargb >> 24);
  16968. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  16969. sargb += 0xff00ff00 & (getAG() * alpha);
  16970. argb = sargb;
  16971. }
  16972. /** Blends another pixel onto this one.
  16973. This takes into account the opacity of the pixel being overlaid, and blends
  16974. it accordingly.
  16975. */
  16976. forcedinline void blend (const PixelAlpha& src) throw();
  16977. /** Blends another pixel onto this one.
  16978. This takes into account the opacity of the pixel being overlaid, and blends
  16979. it accordingly.
  16980. */
  16981. forcedinline void blend (const PixelRGB& src) throw();
  16982. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  16983. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  16984. being used, so this can blend semi-transparently from a PixelRGB argument.
  16985. */
  16986. template <class Pixel>
  16987. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  16988. {
  16989. ++extraAlpha;
  16990. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  16991. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  16992. const uint32 alpha = 0x100 - (sargb >> 24);
  16993. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  16994. sargb += 0xff00ff00 & (getAG() * alpha);
  16995. argb = sargb;
  16996. }
  16997. /** Blends another pixel with this one, creating a colour that is somewhere
  16998. between the two, as specified by the amount.
  16999. */
  17000. template <class Pixel>
  17001. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  17002. {
  17003. uint32 drb = getRB();
  17004. drb += (((src.getRB() - drb) * amount) >> 8);
  17005. drb &= 0x00ff00ff;
  17006. uint32 dag = getAG();
  17007. dag += (((src.getAG() - dag) * amount) >> 8);
  17008. dag &= 0x00ff00ff;
  17009. dag <<= 8;
  17010. dag |= drb;
  17011. argb = dag;
  17012. }
  17013. /** Copies another pixel colour over this one.
  17014. This doesn't blend it - this colour is simply replaced by the other one.
  17015. */
  17016. template <class Pixel>
  17017. forcedinline void set (const Pixel& src) throw()
  17018. {
  17019. argb = src.getARGB();
  17020. }
  17021. /** Replaces the colour's alpha value with another one. */
  17022. forcedinline void setAlpha (const uint8 newAlpha) throw()
  17023. {
  17024. components.a = newAlpha;
  17025. }
  17026. /** Multiplies the colour's alpha value with another one. */
  17027. forcedinline void multiplyAlpha (int multiplier) throw()
  17028. {
  17029. ++multiplier;
  17030. argb = ((multiplier * getAG()) & 0xff00ff00)
  17031. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  17032. }
  17033. forcedinline void multiplyAlpha (const float multiplier) throw()
  17034. {
  17035. multiplyAlpha ((int) (multiplier * 256.0f));
  17036. }
  17037. /** Sets the pixel's colour from individual components. */
  17038. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  17039. {
  17040. components.b = b;
  17041. components.g = g;
  17042. components.r = r;
  17043. components.a = a;
  17044. }
  17045. /** Premultiplies the pixel's RGB values by its alpha. */
  17046. forcedinline void premultiply() throw()
  17047. {
  17048. const uint32 alpha = components.a;
  17049. if (alpha < 0xff)
  17050. {
  17051. if (alpha == 0)
  17052. {
  17053. components.b = 0;
  17054. components.g = 0;
  17055. components.r = 0;
  17056. }
  17057. else
  17058. {
  17059. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  17060. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  17061. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  17062. }
  17063. }
  17064. }
  17065. /** Unpremultiplies the pixel's RGB values. */
  17066. forcedinline void unpremultiply() throw()
  17067. {
  17068. const uint32 alpha = components.a;
  17069. if (alpha < 0xff)
  17070. {
  17071. if (alpha == 0)
  17072. {
  17073. components.b = 0;
  17074. components.g = 0;
  17075. components.r = 0;
  17076. }
  17077. else
  17078. {
  17079. components.b = (uint8) jmin ((uint32) 0xff, (components.b * 0xff) / alpha);
  17080. components.g = (uint8) jmin ((uint32) 0xff, (components.g * 0xff) / alpha);
  17081. components.r = (uint8) jmin ((uint32) 0xff, (components.r * 0xff) / alpha);
  17082. }
  17083. }
  17084. }
  17085. forcedinline void desaturate() throw()
  17086. {
  17087. if (components.a < 0xff && components.a > 0)
  17088. {
  17089. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  17090. components.r = components.g = components.b
  17091. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  17092. }
  17093. else
  17094. {
  17095. components.r = components.g = components.b
  17096. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  17097. }
  17098. }
  17099. /** The indexes of the different components in the byte layout of this type of colour. */
  17100. #if JUCE_BIG_ENDIAN
  17101. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  17102. #else
  17103. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  17104. #endif
  17105. private:
  17106. union
  17107. {
  17108. uint32 argb;
  17109. struct
  17110. {
  17111. #if JUCE_BIG_ENDIAN
  17112. uint8 a : 8, r : 8, g : 8, b : 8;
  17113. #else
  17114. uint8 b, g, r, a;
  17115. #endif
  17116. } PACKED components;
  17117. };
  17118. } PACKED;
  17119. /**
  17120. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  17121. This is used internally by the imaging classes.
  17122. @see PixelARGB
  17123. */
  17124. class JUCE_API PixelRGB
  17125. {
  17126. public:
  17127. /** Creates a pixel without defining its colour. */
  17128. PixelRGB() throw() {}
  17129. ~PixelRGB() throw() {}
  17130. /** Creates a pixel from a 32-bit argb value.
  17131. (The argb format is that used by PixelARGB)
  17132. */
  17133. PixelRGB (const uint32 argb) throw()
  17134. {
  17135. r = (uint8) (argb >> 16);
  17136. g = (uint8) (argb >> 8);
  17137. b = (uint8) (argb);
  17138. }
  17139. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  17140. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  17141. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  17142. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  17143. forcedinline uint8 getRed() const throw() { return r; }
  17144. forcedinline uint8 getGreen() const throw() { return g; }
  17145. forcedinline uint8 getBlue() const throw() { return b; }
  17146. /** Blends another pixel onto this one.
  17147. This takes into account the opacity of the pixel being overlaid, and blends
  17148. it accordingly.
  17149. */
  17150. forcedinline void blend (const PixelARGB& src) throw()
  17151. {
  17152. uint32 sargb = src.getARGB();
  17153. const uint32 alpha = 0x100 - (sargb >> 24);
  17154. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17155. sargb += 0x0000ff00 & (g * alpha);
  17156. r = (uint8) (sargb >> 16);
  17157. g = (uint8) (sargb >> 8);
  17158. b = (uint8) sargb;
  17159. }
  17160. forcedinline void blend (const PixelRGB& src) throw()
  17161. {
  17162. set (src);
  17163. }
  17164. forcedinline void blend (const PixelAlpha& src) throw();
  17165. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  17166. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  17167. being used, so this can blend semi-transparently from a PixelRGB argument.
  17168. */
  17169. template <class Pixel>
  17170. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  17171. {
  17172. ++extraAlpha;
  17173. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  17174. const uint32 sag = extraAlpha * src.getAG();
  17175. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  17176. const uint32 alpha = 0x100 - (sargb >> 24);
  17177. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17178. sargb += 0x0000ff00 & (g * alpha);
  17179. b = (uint8) sargb;
  17180. g = (uint8) (sargb >> 8);
  17181. r = (uint8) (sargb >> 16);
  17182. }
  17183. /** Blends another pixel with this one, creating a colour that is somewhere
  17184. between the two, as specified by the amount.
  17185. */
  17186. template <class Pixel>
  17187. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  17188. {
  17189. uint32 drb = getRB();
  17190. drb += (((src.getRB() - drb) * amount) >> 8);
  17191. uint32 dag = getAG();
  17192. dag += (((src.getAG() - dag) * amount) >> 8);
  17193. b = (uint8) drb;
  17194. g = (uint8) dag;
  17195. r = (uint8) (drb >> 16);
  17196. }
  17197. /** Copies another pixel colour over this one.
  17198. This doesn't blend it - this colour is simply replaced by the other one.
  17199. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  17200. is thrown away.
  17201. */
  17202. template <class Pixel>
  17203. forcedinline void set (const Pixel& src) throw()
  17204. {
  17205. b = src.getBlue();
  17206. g = src.getGreen();
  17207. r = src.getRed();
  17208. }
  17209. /** This method is included for compatibility with the PixelARGB class. */
  17210. forcedinline void setAlpha (const uint8) throw() {}
  17211. /** Multiplies the colour's alpha value with another one. */
  17212. forcedinline void multiplyAlpha (int) throw() {}
  17213. /** Sets the pixel's colour from individual components. */
  17214. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  17215. {
  17216. r = r_;
  17217. g = g_;
  17218. b = b_;
  17219. }
  17220. /** Premultiplies the pixel's RGB values by its alpha. */
  17221. forcedinline void premultiply() throw() {}
  17222. /** Unpremultiplies the pixel's RGB values. */
  17223. forcedinline void unpremultiply() throw() {}
  17224. forcedinline void desaturate() throw()
  17225. {
  17226. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  17227. }
  17228. /** The indexes of the different components in the byte layout of this type of colour. */
  17229. #if JUCE_MAC
  17230. enum { indexR = 0, indexG = 1, indexB = 2 };
  17231. #else
  17232. enum { indexR = 2, indexG = 1, indexB = 0 };
  17233. #endif
  17234. private:
  17235. #if JUCE_MAC
  17236. uint8 r, g, b;
  17237. #else
  17238. uint8 b, g, r;
  17239. #endif
  17240. } PACKED;
  17241. forcedinline void PixelARGB::blend (const PixelRGB& src) throw()
  17242. {
  17243. set (src);
  17244. }
  17245. /**
  17246. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  17247. This is used internally by the imaging classes.
  17248. @see PixelARGB, PixelRGB
  17249. */
  17250. class JUCE_API PixelAlpha
  17251. {
  17252. public:
  17253. /** Creates a pixel without defining its colour. */
  17254. PixelAlpha() throw() {}
  17255. ~PixelAlpha() throw() {}
  17256. /** Creates a pixel from a 32-bit argb value.
  17257. (The argb format is that used by PixelARGB)
  17258. */
  17259. PixelAlpha (const uint32 argb) throw()
  17260. {
  17261. a = (uint8) (argb >> 24);
  17262. }
  17263. forcedinline uint32 getARGB() const throw() { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  17264. forcedinline uint32 getRB() const throw() { return (((uint32) a) << 16) | a; }
  17265. forcedinline uint32 getAG() const throw() { return (((uint32) a) << 16) | a; }
  17266. forcedinline uint8 getAlpha() const throw() { return a; }
  17267. forcedinline uint8 getRed() const throw() { return 0; }
  17268. forcedinline uint8 getGreen() const throw() { return 0; }
  17269. forcedinline uint8 getBlue() const throw() { return 0; }
  17270. /** Blends another pixel onto this one.
  17271. This takes into account the opacity of the pixel being overlaid, and blends
  17272. it accordingly.
  17273. */
  17274. template <class Pixel>
  17275. forcedinline void blend (const Pixel& src) throw()
  17276. {
  17277. const int srcA = src.getAlpha();
  17278. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  17279. }
  17280. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  17281. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  17282. being used, so this can blend semi-transparently from a PixelRGB argument.
  17283. */
  17284. template <class Pixel>
  17285. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  17286. {
  17287. ++extraAlpha;
  17288. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  17289. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  17290. }
  17291. /** Blends another pixel with this one, creating a colour that is somewhere
  17292. between the two, as specified by the amount.
  17293. */
  17294. template <class Pixel>
  17295. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  17296. {
  17297. a += ((src,getAlpha() - a) * amount) >> 8;
  17298. }
  17299. /** Copies another pixel colour over this one.
  17300. This doesn't blend it - this colour is simply replaced by the other one.
  17301. */
  17302. template <class Pixel>
  17303. forcedinline void set (const Pixel& src) throw()
  17304. {
  17305. a = src.getAlpha();
  17306. }
  17307. /** Replaces the colour's alpha value with another one. */
  17308. forcedinline void setAlpha (const uint8 newAlpha) throw()
  17309. {
  17310. a = newAlpha;
  17311. }
  17312. /** Multiplies the colour's alpha value with another one. */
  17313. forcedinline void multiplyAlpha (int multiplier) throw()
  17314. {
  17315. ++multiplier;
  17316. a = (uint8) ((a * multiplier) >> 8);
  17317. }
  17318. forcedinline void multiplyAlpha (const float multiplier) throw()
  17319. {
  17320. a = (uint8) (a * multiplier);
  17321. }
  17322. /** Sets the pixel's colour from individual components. */
  17323. forcedinline void setARGB (const uint8 a_, const uint8 /*r*/, const uint8 /*g*/, const uint8 /*b*/) throw()
  17324. {
  17325. a = a_;
  17326. }
  17327. /** Premultiplies the pixel's RGB values by its alpha. */
  17328. forcedinline void premultiply() throw()
  17329. {
  17330. }
  17331. /** Unpremultiplies the pixel's RGB values. */
  17332. forcedinline void unpremultiply() throw()
  17333. {
  17334. }
  17335. forcedinline void desaturate() throw()
  17336. {
  17337. }
  17338. /** The indexes of the different components in the byte layout of this type of colour. */
  17339. enum { indexA = 0 };
  17340. private:
  17341. uint8 a : 8;
  17342. } PACKED;
  17343. forcedinline void PixelRGB::blend (const PixelAlpha& src) throw()
  17344. {
  17345. blend (PixelARGB (src.getARGB()));
  17346. }
  17347. forcedinline void PixelARGB::blend (const PixelAlpha& src) throw()
  17348. {
  17349. uint32 sargb = src.getARGB();
  17350. const uint32 alpha = 0x100 - (sargb >> 24);
  17351. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17352. sargb += 0xff00ff00 & (getAG() * alpha);
  17353. argb = sargb;
  17354. }
  17355. #if JUCE_MSVC
  17356. #pragma pack (pop)
  17357. #endif
  17358. #undef PACKED
  17359. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  17360. /*** End of inlined file: juce_PixelFormats.h ***/
  17361. /**
  17362. Represents a colour, also including a transparency value.
  17363. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  17364. */
  17365. class JUCE_API Colour
  17366. {
  17367. public:
  17368. /** Creates a transparent black colour. */
  17369. Colour() throw();
  17370. /** Creates a copy of another Colour object. */
  17371. Colour (const Colour& other) throw();
  17372. /** Creates a colour from a 32-bit ARGB value.
  17373. The format of this number is:
  17374. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  17375. All components in the range 0x00 to 0xff.
  17376. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  17377. @see getPixelARGB
  17378. */
  17379. explicit Colour (uint32 argb) throw();
  17380. /** Creates an opaque colour using 8-bit red, green and blue values */
  17381. Colour (uint8 red,
  17382. uint8 green,
  17383. uint8 blue) throw();
  17384. /** Creates an opaque colour using 8-bit red, green and blue values */
  17385. static const Colour fromRGB (uint8 red,
  17386. uint8 green,
  17387. uint8 blue) throw();
  17388. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  17389. Colour (uint8 red,
  17390. uint8 green,
  17391. uint8 blue,
  17392. uint8 alpha) throw();
  17393. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  17394. static const Colour fromRGBA (uint8 red,
  17395. uint8 green,
  17396. uint8 blue,
  17397. uint8 alpha) throw();
  17398. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  17399. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  17400. Values outside the valid range will be clipped.
  17401. */
  17402. Colour (uint8 red,
  17403. uint8 green,
  17404. uint8 blue,
  17405. float alpha) throw();
  17406. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  17407. static const Colour fromRGBAFloat (uint8 red,
  17408. uint8 green,
  17409. uint8 blue,
  17410. float alpha) throw();
  17411. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  17412. The floating point values must be between 0.0 and 1.0.
  17413. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  17414. Values outside the valid range will be clipped.
  17415. */
  17416. Colour (float hue,
  17417. float saturation,
  17418. float brightness,
  17419. uint8 alpha) throw();
  17420. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  17421. All values must be between 0.0 and 1.0.
  17422. Numbers outside the valid range will be clipped.
  17423. */
  17424. Colour (float hue,
  17425. float saturation,
  17426. float brightness,
  17427. float alpha) throw();
  17428. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  17429. The floating point values must be between 0.0 and 1.0.
  17430. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  17431. Values outside the valid range will be clipped.
  17432. */
  17433. static const Colour fromHSV (float hue,
  17434. float saturation,
  17435. float brightness,
  17436. float alpha) throw();
  17437. /** Destructor. */
  17438. ~Colour() throw();
  17439. /** Copies another Colour object. */
  17440. Colour& operator= (const Colour& other) throw();
  17441. /** Compares two colours. */
  17442. bool operator== (const Colour& other) const throw();
  17443. /** Compares two colours. */
  17444. bool operator!= (const Colour& other) const throw();
  17445. /** Returns the red component of this colour.
  17446. @returns a value between 0x00 and 0xff.
  17447. */
  17448. uint8 getRed() const throw() { return argb.getRed(); }
  17449. /** Returns the green component of this colour.
  17450. @returns a value between 0x00 and 0xff.
  17451. */
  17452. uint8 getGreen() const throw() { return argb.getGreen(); }
  17453. /** Returns the blue component of this colour.
  17454. @returns a value between 0x00 and 0xff.
  17455. */
  17456. uint8 getBlue() const throw() { return argb.getBlue(); }
  17457. /** Returns the red component of this colour as a floating point value.
  17458. @returns a value between 0.0 and 1.0
  17459. */
  17460. float getFloatRed() const throw();
  17461. /** Returns the green component of this colour as a floating point value.
  17462. @returns a value between 0.0 and 1.0
  17463. */
  17464. float getFloatGreen() const throw();
  17465. /** Returns the blue component of this colour as a floating point value.
  17466. @returns a value between 0.0 and 1.0
  17467. */
  17468. float getFloatBlue() const throw();
  17469. /** Returns a premultiplied ARGB pixel object that represents this colour.
  17470. */
  17471. const PixelARGB getPixelARGB() const throw();
  17472. /** Returns a 32-bit integer that represents this colour.
  17473. The format of this number is:
  17474. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  17475. */
  17476. uint32 getARGB() const throw();
  17477. /** Returns the colour's alpha (opacity).
  17478. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  17479. */
  17480. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  17481. /** Returns the colour's alpha (opacity) as a floating point value.
  17482. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  17483. */
  17484. float getFloatAlpha() const throw();
  17485. /** Returns true if this colour is completely opaque.
  17486. Equivalent to (getAlpha() == 0xff).
  17487. */
  17488. bool isOpaque() const throw();
  17489. /** Returns true if this colour is completely transparent.
  17490. Equivalent to (getAlpha() == 0x00).
  17491. */
  17492. bool isTransparent() const throw();
  17493. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  17494. const Colour withAlpha (uint8 newAlpha) const throw();
  17495. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  17496. const Colour withAlpha (float newAlpha) const throw();
  17497. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  17498. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  17499. */
  17500. const Colour withMultipliedAlpha (float alphaMultiplier) const throw();
  17501. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  17502. If the foreground colour is semi-transparent, it is blended onto this colour
  17503. accordingly.
  17504. */
  17505. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  17506. /** Returns a colour that lies somewhere between this one and another.
  17507. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  17508. is 1.0, the result is 100% of the other colour.
  17509. */
  17510. const Colour interpolatedWith (const Colour& other, float proportionOfOther) const throw();
  17511. /** Returns the colour's hue component.
  17512. The value returned is in the range 0.0 to 1.0
  17513. */
  17514. float getHue() const throw();
  17515. /** Returns the colour's saturation component.
  17516. The value returned is in the range 0.0 to 1.0
  17517. */
  17518. float getSaturation() const throw();
  17519. /** Returns the colour's brightness component.
  17520. The value returned is in the range 0.0 to 1.0
  17521. */
  17522. float getBrightness() const throw();
  17523. /** Returns the colour's hue, saturation and brightness components all at once.
  17524. The values returned are in the range 0.0 to 1.0
  17525. */
  17526. void getHSB (float& hue,
  17527. float& saturation,
  17528. float& brightness) const throw();
  17529. /** Returns a copy of this colour with a different hue. */
  17530. const Colour withHue (float newHue) const throw();
  17531. /** Returns a copy of this colour with a different saturation. */
  17532. const Colour withSaturation (float newSaturation) const throw();
  17533. /** Returns a copy of this colour with a different brightness.
  17534. @see brighter, darker, withMultipliedBrightness
  17535. */
  17536. const Colour withBrightness (float newBrightness) const throw();
  17537. /** Returns a copy of this colour with it hue rotated.
  17538. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  17539. @see brighter, darker, withMultipliedBrightness
  17540. */
  17541. const Colour withRotatedHue (float amountToRotate) const throw();
  17542. /** Returns a copy of this colour with its saturation multiplied by the given value.
  17543. The new colour's saturation is (this->getSaturation() * multiplier)
  17544. (the result is clipped to legal limits).
  17545. */
  17546. const Colour withMultipliedSaturation (float multiplier) const throw();
  17547. /** Returns a copy of this colour with its brightness multiplied by the given value.
  17548. The new colour's saturation is (this->getBrightness() * multiplier)
  17549. (the result is clipped to legal limits).
  17550. */
  17551. const Colour withMultipliedBrightness (float amount) const throw();
  17552. /** Returns a brighter version of this colour.
  17553. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  17554. unchanged, and higher values make it brighter
  17555. @see withMultipliedBrightness
  17556. */
  17557. const Colour brighter (float amountBrighter = 0.4f) const throw();
  17558. /** Returns a darker version of this colour.
  17559. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  17560. unchanged, and higher values make it darker
  17561. @see withMultipliedBrightness
  17562. */
  17563. const Colour darker (float amountDarker = 0.4f) const throw();
  17564. /** Returns a colour that will be clearly visible against this colour.
  17565. The amount parameter indicates how contrasting the new colour should
  17566. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  17567. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  17568. return white; Colours::white.contrasting (1.0f) will return black, etc.
  17569. */
  17570. const Colour contrasting (float amount = 1.0f) const throw();
  17571. /** Returns a colour that contrasts against two colours.
  17572. Looks for a colour that contrasts with both of the colours passed-in.
  17573. Handy for things like choosing a highlight colour in text editors, etc.
  17574. */
  17575. static const Colour contrasting (const Colour& colour1,
  17576. const Colour& colour2) throw();
  17577. /** Returns an opaque shade of grey.
  17578. @param brightness the level of grey to return - 0 is black, 1.0 is white
  17579. */
  17580. static const Colour greyLevel (float brightness) throw();
  17581. /** Returns a stringified version of this colour.
  17582. The string can be turned back into a colour using the fromString() method.
  17583. */
  17584. const String toString() const;
  17585. /** Reads the colour from a string that was created with toString().
  17586. */
  17587. static const Colour fromString (const String& encodedColourString);
  17588. /** Returns the colour as a hex string in the form RRGGBB or AARRGGBB. */
  17589. const String toDisplayString (bool includeAlphaValue) const;
  17590. juce_UseDebuggingNewOperator
  17591. private:
  17592. PixelARGB argb;
  17593. };
  17594. #endif // __JUCE_COLOUR_JUCEHEADER__
  17595. /*** End of inlined file: juce_Colour.h ***/
  17596. /**
  17597. Contains a set of predefined named colours (mostly standard HTML colours)
  17598. @see Colour, Colours::greyLevel
  17599. */
  17600. class Colours
  17601. {
  17602. public:
  17603. static JUCE_API const Colour
  17604. transparentBlack, /**< ARGB = 0x00000000 */
  17605. transparentWhite, /**< ARGB = 0x00ffffff */
  17606. black, /**< ARGB = 0xff000000 */
  17607. white, /**< ARGB = 0xffffffff */
  17608. blue, /**< ARGB = 0xff0000ff */
  17609. grey, /**< ARGB = 0xff808080 */
  17610. green, /**< ARGB = 0xff008000 */
  17611. red, /**< ARGB = 0xffff0000 */
  17612. yellow, /**< ARGB = 0xffffff00 */
  17613. aliceblue, antiquewhite, aqua, aquamarine,
  17614. azure, beige, bisque, blanchedalmond,
  17615. blueviolet, brown, burlywood, cadetblue,
  17616. chartreuse, chocolate, coral, cornflowerblue,
  17617. cornsilk, crimson, cyan, darkblue,
  17618. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  17619. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  17620. darkorchid, darkred, darksalmon, darkseagreen,
  17621. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  17622. deeppink, deepskyblue, dimgrey, dodgerblue,
  17623. firebrick, floralwhite, forestgreen, fuchsia,
  17624. gainsboro, gold, goldenrod, greenyellow,
  17625. honeydew, hotpink, indianred, indigo,
  17626. ivory, khaki, lavender, lavenderblush,
  17627. lemonchiffon, lightblue, lightcoral, lightcyan,
  17628. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  17629. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  17630. lightsteelblue, lightyellow, lime, limegreen,
  17631. linen, magenta, maroon, mediumaquamarine,
  17632. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  17633. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  17634. midnightblue, mintcream, mistyrose, navajowhite,
  17635. navy, oldlace, olive, olivedrab,
  17636. orange, orangered, orchid, palegoldenrod,
  17637. palegreen, paleturquoise, palevioletred, papayawhip,
  17638. peachpuff, peru, pink, plum,
  17639. powderblue, purple, rosybrown, royalblue,
  17640. saddlebrown, salmon, sandybrown, seagreen,
  17641. seashell, sienna, silver, skyblue,
  17642. slateblue, slategrey, snow, springgreen,
  17643. steelblue, tan, teal, thistle,
  17644. tomato, turquoise, violet, wheat,
  17645. whitesmoke, yellowgreen;
  17646. /** Attempts to look up a string in the list of known colour names, and return
  17647. the appropriate colour.
  17648. A non-case-sensitive search is made of the list of predefined colours, and
  17649. if a match is found, that colour is returned. If no match is found, the
  17650. colour passed in as the defaultColour parameter is returned.
  17651. */
  17652. static JUCE_API const Colour findColourForName (const String& colourName,
  17653. const Colour& defaultColour);
  17654. private:
  17655. // this isn't a class you should ever instantiate - it's just here for the
  17656. // static values in it.
  17657. Colours();
  17658. Colours (const Colours&);
  17659. Colours& operator= (const Colours&);
  17660. };
  17661. #endif // __JUCE_COLOURS_JUCEHEADER__
  17662. /*** End of inlined file: juce_Colours.h ***/
  17663. /*** Start of inlined file: juce_ColourGradient.h ***/
  17664. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  17665. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  17666. /**
  17667. Describes the layout and colours that should be used to paint a colour gradient.
  17668. @see Graphics::setGradientFill
  17669. */
  17670. class JUCE_API ColourGradient
  17671. {
  17672. public:
  17673. /** Creates a gradient object.
  17674. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  17675. colour2 should be. In between them there's a gradient.
  17676. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  17677. its centre.
  17678. The alpha transparencies of the colours are used, so note that
  17679. if you blend from transparent to a solid colour, the RGB of the transparent
  17680. colour will become visible in parts of the gradient. e.g. blending
  17681. from Colour::transparentBlack to Colours::white will produce a
  17682. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  17683. will be white all the way across.
  17684. @see ColourGradient
  17685. */
  17686. ColourGradient (const Colour& colour1, float x1, float y1,
  17687. const Colour& colour2, float x2, float y2,
  17688. bool isRadial);
  17689. /** Creates an uninitialised gradient.
  17690. If you use this constructor instead of the other one, be sure to set all the
  17691. object's public member variables before using it!
  17692. */
  17693. ColourGradient() throw();
  17694. /** Destructor */
  17695. ~ColourGradient();
  17696. /** Removes any colours that have been added.
  17697. This will also remove any start and end colours, so the gradient won't work. You'll
  17698. need to add more colours with addColour().
  17699. */
  17700. void clearColours();
  17701. /** Adds a colour at a point along the length of the gradient.
  17702. This allows the gradient to go through a spectrum of colours, instead of just a
  17703. start and end colour.
  17704. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  17705. of the distance along the line between the two points
  17706. at which the colour should occur.
  17707. @param colour the colour that should be used at this point
  17708. @returns the index at which the new point was added
  17709. */
  17710. int addColour (double proportionAlongGradient,
  17711. const Colour& colour);
  17712. /** Removes one of the colours from the gradient. */
  17713. void removeColour (int index);
  17714. /** Multiplies the alpha value of all the colours by the given scale factor */
  17715. void multiplyOpacity (float multiplier) throw();
  17716. /** Returns the number of colour-stops that have been added. */
  17717. int getNumColours() const throw();
  17718. /** Returns the position along the length of the gradient of the colour with this index.
  17719. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  17720. */
  17721. double getColourPosition (int index) const throw();
  17722. /** Returns the colour that was added with a given index.
  17723. The index is from 0 to getNumColours() - 1.
  17724. */
  17725. const Colour getColour (int index) const throw();
  17726. /** Changes the colour at a given index.
  17727. The index is from 0 to getNumColours() - 1.
  17728. */
  17729. void setColour (int index, const Colour& newColour) throw();
  17730. /** Returns the an interpolated colour at any position along the gradient.
  17731. @param position the position along the gradient, between 0 and 1
  17732. */
  17733. const Colour getColourAtPosition (double position) const throw();
  17734. /** Creates a set of interpolated premultiplied ARGB values.
  17735. This will resize the HeapBlock, fill it with the colours, and will return the number of
  17736. colours that it added.
  17737. */
  17738. int createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& resultLookupTable) const;
  17739. /** Returns true if all colours are opaque. */
  17740. bool isOpaque() const throw();
  17741. /** Returns true if all colours are completely transparent. */
  17742. bool isInvisible() const throw();
  17743. Point<float> point1, point2;
  17744. /** If true, the gradient should be filled circularly, centred around
  17745. point1, with point2 defining a point on the circumference.
  17746. If false, the gradient is linear between the two points.
  17747. */
  17748. bool isRadial;
  17749. bool operator== (const ColourGradient& other) const throw();
  17750. bool operator!= (const ColourGradient& other) const throw();
  17751. juce_UseDebuggingNewOperator
  17752. private:
  17753. struct ColourPoint
  17754. {
  17755. ColourPoint() throw() {}
  17756. ColourPoint (const double position_, const Colour& colour_) throw()
  17757. : position (position_), colour (colour_)
  17758. {}
  17759. bool operator== (const ColourPoint& other) const throw() { return position == other.position && colour == other.colour; }
  17760. bool operator!= (const ColourPoint& other) const throw() { return position != other.position || colour != other.colour; }
  17761. double position;
  17762. Colour colour;
  17763. };
  17764. Array <ColourPoint> colours;
  17765. };
  17766. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  17767. /*** End of inlined file: juce_ColourGradient.h ***/
  17768. /*** Start of inlined file: juce_RectanglePlacement.h ***/
  17769. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  17770. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  17771. /**
  17772. Defines the method used to postion some kind of rectangular object within
  17773. a rectangular viewport.
  17774. Although similar to Justification, this is more specific, and has some extra
  17775. options.
  17776. */
  17777. class JUCE_API RectanglePlacement
  17778. {
  17779. public:
  17780. /** Creates a RectanglePlacement object using a combination of flags. */
  17781. inline RectanglePlacement (int flags_) throw() : flags (flags_) {}
  17782. /** Creates a copy of another RectanglePlacement object. */
  17783. RectanglePlacement (const RectanglePlacement& other) throw();
  17784. /** Copies another RectanglePlacement object. */
  17785. RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  17786. /** Flag values that can be combined and used in the constructor. */
  17787. enum
  17788. {
  17789. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  17790. xLeft = 1,
  17791. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  17792. xRight = 2,
  17793. /** Indicates that the source should be placed in the centre between the left and right
  17794. sides of the available space. */
  17795. xMid = 4,
  17796. /** Indicates that the source's top edge should be aligned with the top edge of the
  17797. destination rectangle. */
  17798. yTop = 8,
  17799. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  17800. destination rectangle. */
  17801. yBottom = 16,
  17802. /** Indicates that the source should be placed in the centre between the top and bottom
  17803. sides of the available space. */
  17804. yMid = 32,
  17805. /** If this flag is set, then the source rectangle will be resized to completely fill
  17806. the destination rectangle, and all other flags are ignored.
  17807. */
  17808. stretchToFit = 64,
  17809. /** If this flag is set, then the source rectangle will be resized so that it is the
  17810. minimum size to completely fill the destination rectangle, without changing its
  17811. aspect ratio. This means that some of the source rectangle may fall outside
  17812. the destination.
  17813. If this flag is not set, the source will be given the maximum size at which none
  17814. of it falls outside the destination rectangle.
  17815. */
  17816. fillDestination = 128,
  17817. /** Indicates that the source rectangle can be reduced in size if required, but should
  17818. never be made larger than its original size.
  17819. */
  17820. onlyReduceInSize = 256,
  17821. /** Indicates that the source rectangle can be enlarged if required, but should
  17822. never be made smaller than its original size.
  17823. */
  17824. onlyIncreaseInSize = 512,
  17825. /** Indicates that the source rectangle's size should be left unchanged.
  17826. */
  17827. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  17828. /** A shorthand value that is equivalent to (xMid | yMid). */
  17829. centred = 4 + 32
  17830. };
  17831. /** Returns the raw flags that are set for this object. */
  17832. inline int getFlags() const throw() { return flags; }
  17833. /** Tests a set of flags for this object.
  17834. @returns true if any of the flags passed in are set on this object.
  17835. */
  17836. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  17837. /** Adjusts the position and size of a rectangle to fit it into a space.
  17838. The source rectangle co-ordinates will be adjusted so that they fit into
  17839. the destination rectangle based on this object's flags.
  17840. */
  17841. void applyTo (double& sourceX,
  17842. double& sourceY,
  17843. double& sourceW,
  17844. double& sourceH,
  17845. double destinationX,
  17846. double destinationY,
  17847. double destinationW,
  17848. double destinationH) const throw();
  17849. /** Returns the transform that should be applied to these source co-ordinates to fit them
  17850. into the destination rectangle using the current flags.
  17851. */
  17852. const AffineTransform getTransformToFit (float sourceX,
  17853. float sourceY,
  17854. float sourceW,
  17855. float sourceH,
  17856. float destinationX,
  17857. float destinationY,
  17858. float destinationW,
  17859. float destinationH) const throw();
  17860. private:
  17861. int flags;
  17862. };
  17863. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  17864. /*** End of inlined file: juce_RectanglePlacement.h ***/
  17865. class LowLevelGraphicsContext;
  17866. class Image;
  17867. class FillType;
  17868. class RectangleList;
  17869. /**
  17870. A graphics context, used for drawing a component or image.
  17871. When a Component needs painting, a Graphics context is passed to its
  17872. Component::paint() method, and this you then call methods within this
  17873. object to actually draw the component's content.
  17874. A Graphics can also be created from an image, to allow drawing directly onto
  17875. that image.
  17876. @see Component::paint
  17877. */
  17878. class JUCE_API Graphics
  17879. {
  17880. public:
  17881. /** Creates a Graphics object to draw directly onto the given image.
  17882. The graphics object that is created will be set up to draw onto the image,
  17883. with the context's clipping area being the entire size of the image, and its
  17884. origin being the image's origin. To draw into a subsection of an image, use the
  17885. reduceClipRegion() and setOrigin() methods.
  17886. Obviously you shouldn't delete the image before this context is deleted.
  17887. */
  17888. explicit Graphics (const Image& imageToDrawOnto);
  17889. /** Destructor. */
  17890. ~Graphics();
  17891. /** Changes the current drawing colour.
  17892. This sets the colour that will now be used for drawing operations - it also
  17893. sets the opacity to that of the colour passed-in.
  17894. If a brush is being used when this method is called, the brush will be deselected,
  17895. and any subsequent drawing will be done with a solid colour brush instead.
  17896. @see setOpacity
  17897. */
  17898. void setColour (const Colour& newColour);
  17899. /** Changes the opacity to use with the current colour.
  17900. If a solid colour is being used for drawing, this changes its opacity
  17901. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  17902. If a gradient is being used, this will have no effect on it.
  17903. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  17904. */
  17905. void setOpacity (const float newOpacity);
  17906. /** Sets the context to use a gradient for its fill pattern.
  17907. */
  17908. void setGradientFill (const ColourGradient& gradient);
  17909. /** Sets the context to use a tiled image pattern for filling.
  17910. Make sure that you don't delete this image while it's still being used by
  17911. this context!
  17912. */
  17913. void setTiledImageFill (const Image& imageToUse,
  17914. int anchorX, int anchorY,
  17915. float opacity);
  17916. /** Changes the current fill settings.
  17917. @see setColour, setGradientFill, setTiledImageFill
  17918. */
  17919. void setFillType (const FillType& newFill);
  17920. /** Changes the font to use for subsequent text-drawing functions.
  17921. Note there's also a setFont (float, int) method to quickly change the size and
  17922. style of the current font.
  17923. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  17924. */
  17925. void setFont (const Font& newFont);
  17926. /** Changes the size and style of the currently-selected font.
  17927. This is a convenient shortcut that changes the context's current font to a
  17928. different size or style. The typeface won't be changed.
  17929. @see Font
  17930. */
  17931. void setFont (float newFontHeight, int fontStyleFlags = Font::plain);
  17932. /** Returns the currently selected font. */
  17933. const Font getCurrentFont() const;
  17934. /** Draws a one-line text string.
  17935. This will use the current colour (or brush) to fill the text. The font is the last
  17936. one specified by setFont().
  17937. @param text the string to draw
  17938. @param startX the position to draw the left-hand edge of the text
  17939. @param baselineY the position of the text's baseline
  17940. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  17941. */
  17942. void drawSingleLineText (const String& text,
  17943. int startX, int baselineY) const;
  17944. /** Draws text across multiple lines.
  17945. This will break the text onto a new line where there's a new-line or
  17946. carriage-return character, or at a word-boundary when the text becomes wider
  17947. than the size specified by the maximumLineWidth parameter.
  17948. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  17949. */
  17950. void drawMultiLineText (const String& text,
  17951. int startX, int baselineY,
  17952. int maximumLineWidth) const;
  17953. /** Renders a string of text as a vector path.
  17954. This allows a string to be transformed with an arbitrary AffineTransform and
  17955. rendered using the current colour/brush. It's much slower than the normal text methods
  17956. but more accurate.
  17957. @see setFont
  17958. */
  17959. void drawTextAsPath (const String& text,
  17960. const AffineTransform& transform) const;
  17961. /** Draws a line of text within a specified rectangle.
  17962. The text will be positioned within the rectangle based on the justification
  17963. flags passed-in. If the string is too long to fit inside the rectangle, it will
  17964. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  17965. flag is true).
  17966. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  17967. */
  17968. void drawText (const String& text,
  17969. int x, int y, int width, int height,
  17970. const Justification& justificationType,
  17971. bool useEllipsesIfTooBig) const;
  17972. /** Tries to draw a text string inside a given space.
  17973. This does its best to make the given text readable within the specified rectangle,
  17974. so it useful for labelling things.
  17975. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  17976. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  17977. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  17978. it's been truncated.
  17979. A Justification parameter lets you specify how the text is laid out within the rectangle,
  17980. both horizontally and vertically.
  17981. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  17982. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  17983. can set this value to 1.0f.
  17984. @see GlyphArrangement::addFittedText
  17985. */
  17986. void drawFittedText (const String& text,
  17987. int x, int y, int width, int height,
  17988. const Justification& justificationFlags,
  17989. int maximumNumberOfLines,
  17990. float minimumHorizontalScale = 0.7f) const;
  17991. /** Fills the context's entire clip region with the current colour or brush.
  17992. (See also the fillAll (const Colour&) method which is a quick way of filling
  17993. it with a given colour).
  17994. */
  17995. void fillAll() const;
  17996. /** Fills the context's entire clip region with a given colour.
  17997. This leaves the context's current colour and brush unchanged, it just
  17998. uses the specified colour temporarily.
  17999. */
  18000. void fillAll (const Colour& colourToUse) const;
  18001. /** Fills a rectangle with the current colour or brush.
  18002. @see drawRect, fillRoundedRectangle
  18003. */
  18004. void fillRect (int x, int y, int width, int height) const;
  18005. /** Fills a rectangle with the current colour or brush. */
  18006. void fillRect (const Rectangle<int>& rectangle) const;
  18007. /** Fills a rectangle with the current colour or brush.
  18008. This uses sub-pixel positioning so is slower than the fillRect method which
  18009. takes integer co-ordinates.
  18010. */
  18011. void fillRect (float x, float y, float width, float height) const;
  18012. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  18013. @see drawRoundedRectangle, Path::addRoundedRectangle
  18014. */
  18015. void fillRoundedRectangle (float x, float y, float width, float height,
  18016. float cornerSize) const;
  18017. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  18018. @see drawRoundedRectangle, Path::addRoundedRectangle
  18019. */
  18020. void fillRoundedRectangle (const Rectangle<float>& rectangle,
  18021. float cornerSize) const;
  18022. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  18023. */
  18024. void fillCheckerBoard (int x, int y, int width, int height,
  18025. int checkWidth, int checkHeight,
  18026. const Colour& colour1, const Colour& colour2) const;
  18027. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  18028. The lines are drawn inside the given rectangle, and greater line thicknesses
  18029. extend inwards.
  18030. @see fillRect
  18031. */
  18032. void drawRect (int x, int y, int width, int height,
  18033. int lineThickness = 1) const;
  18034. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  18035. The lines are drawn inside the given rectangle, and greater line thicknesses
  18036. extend inwards.
  18037. @see fillRect
  18038. */
  18039. void drawRect (float x, float y, float width, float height,
  18040. float lineThickness = 1.0f) const;
  18041. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  18042. The lines are drawn inside the given rectangle, and greater line thicknesses
  18043. extend inwards.
  18044. @see fillRect
  18045. */
  18046. void drawRect (const Rectangle<int>& rectangle,
  18047. int lineThickness = 1) const;
  18048. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  18049. @see fillRoundedRectangle, Path::addRoundedRectangle
  18050. */
  18051. void drawRoundedRectangle (float x, float y, float width, float height,
  18052. float cornerSize, float lineThickness) const;
  18053. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  18054. @see fillRoundedRectangle, Path::addRoundedRectangle
  18055. */
  18056. void drawRoundedRectangle (const Rectangle<float>& rectangle,
  18057. float cornerSize, float lineThickness) const;
  18058. /** Draws a 3D raised (or indented) bevel using two colours.
  18059. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  18060. extend inwards.
  18061. The top-left colour is used for the top- and left-hand edges of the
  18062. bevel; the bottom-right colour is used for the bottom- and right-hand
  18063. edges.
  18064. If useGradient is true, then the bevel fades out to make it look more curved
  18065. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  18066. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  18067. the centre edges are sharp and it fades towards the outside.
  18068. */
  18069. void drawBevel (int x, int y, int width, int height,
  18070. int bevelThickness,
  18071. const Colour& topLeftColour = Colours::white,
  18072. const Colour& bottomRightColour = Colours::black,
  18073. bool useGradient = true,
  18074. bool sharpEdgeOnOutside = true) const;
  18075. /** Draws a pixel using the current colour or brush.
  18076. */
  18077. void setPixel (int x, int y) const;
  18078. /** Fills an ellipse with the current colour or brush.
  18079. The ellipse is drawn to fit inside the given rectangle.
  18080. @see drawEllipse, Path::addEllipse
  18081. */
  18082. void fillEllipse (float x, float y, float width, float height) const;
  18083. /** Draws an elliptical stroke using the current colour or brush.
  18084. @see fillEllipse, Path::addEllipse
  18085. */
  18086. void drawEllipse (float x, float y, float width, float height,
  18087. float lineThickness) const;
  18088. /** Draws a line between two points.
  18089. The line is 1 pixel wide and drawn with the current colour or brush.
  18090. */
  18091. void drawLine (float startX, float startY, float endX, float endY) const;
  18092. /** Draws a line between two points with a given thickness.
  18093. @see Path::addLineSegment
  18094. */
  18095. void drawLine (float startX, float startY, float endX, float endY,
  18096. float lineThickness) const;
  18097. /** Draws a line between two points.
  18098. The line is 1 pixel wide and drawn with the current colour or brush.
  18099. */
  18100. void drawLine (const Line<float>& line) const;
  18101. /** Draws a line between two points with a given thickness.
  18102. @see Path::addLineSegment
  18103. */
  18104. void drawLine (const Line<float>& line, float lineThickness) const;
  18105. /** Draws a dashed line using a custom set of dash-lengths.
  18106. @param startX the line's start x co-ordinate
  18107. @param startY the line's start y co-ordinate
  18108. @param endX the line's end x co-ordinate
  18109. @param endY the line's end y co-ordinate
  18110. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  18111. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  18112. draw 6 pixels, skip 7 pixels, and then repeat.
  18113. @param numDashLengths the number of elements in the array (this must be an even number).
  18114. @param lineThickness the thickness of the line to draw
  18115. @see PathStrokeType::createDashedStroke
  18116. */
  18117. void drawDashedLine (float startX, float startY,
  18118. float endX, float endY,
  18119. const float* dashLengths, int numDashLengths,
  18120. float lineThickness = 1.0f) const;
  18121. /** Draws a vertical line of pixels at a given x position.
  18122. The x position is an integer, but the top and bottom of the line can be sub-pixel
  18123. positions, and these will be anti-aliased if necessary.
  18124. */
  18125. void drawVerticalLine (int x, float top, float bottom) const;
  18126. /** Draws a horizontal line of pixels at a given y position.
  18127. The y position is an integer, but the left and right ends of the line can be sub-pixel
  18128. positions, and these will be anti-aliased if necessary.
  18129. */
  18130. void drawHorizontalLine (int y, float left, float right) const;
  18131. /** Fills a path using the currently selected colour or brush.
  18132. */
  18133. void fillPath (const Path& path,
  18134. const AffineTransform& transform = AffineTransform::identity) const;
  18135. /** Draws a path's outline using the currently selected colour or brush.
  18136. */
  18137. void strokePath (const Path& path,
  18138. const PathStrokeType& strokeType,
  18139. const AffineTransform& transform = AffineTransform::identity) const;
  18140. /** Draws a line with an arrowhead at its end.
  18141. @param line the line to draw
  18142. @param lineThickness the thickness of the line
  18143. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  18144. @param arrowheadLength the length of the arrow head (along the length of the line)
  18145. */
  18146. void drawArrow (const Line<float>& line,
  18147. float lineThickness,
  18148. float arrowheadWidth,
  18149. float arrowheadLength) const;
  18150. /** Types of rendering quality that can be specified when drawing images.
  18151. @see blendImage, Graphics::setImageResamplingQuality
  18152. */
  18153. enum ResamplingQuality
  18154. {
  18155. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  18156. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  18157. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  18158. };
  18159. /** Changes the quality that will be used when resampling images.
  18160. By default a Graphics object will be set to mediumRenderingQuality.
  18161. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  18162. */
  18163. void setImageResamplingQuality (const ResamplingQuality newQuality);
  18164. /** Draws an image.
  18165. This will draw the whole of an image, positioning its top-left corner at the
  18166. given co-ordinates, and keeping its size the same. This is the simplest image
  18167. drawing method - the others give more control over the scaling and clipping
  18168. of the images.
  18169. Images are composited using the context's current opacity, so if you
  18170. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  18171. (or setColour() with an opaque colour) before drawing images.
  18172. */
  18173. void drawImageAt (const Image& imageToDraw, int topLeftX, int topLeftY,
  18174. bool fillAlphaChannelWithCurrentBrush = false) const;
  18175. /** Draws part of an image, rescaling it to fit in a given target region.
  18176. The specified area of the source image is rescaled and drawn to fill the
  18177. specifed destination rectangle.
  18178. Images are composited using the context's current opacity, so if you
  18179. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  18180. (or setColour() with an opaque colour) before drawing images.
  18181. @param imageToDraw the image to overlay
  18182. @param destX the left of the destination rectangle
  18183. @param destY the top of the destination rectangle
  18184. @param destWidth the width of the destination rectangle
  18185. @param destHeight the height of the destination rectangle
  18186. @param sourceX the left of the rectangle to copy from the source image
  18187. @param sourceY the top of the rectangle to copy from the source image
  18188. @param sourceWidth the width of the rectangle to copy from the source image
  18189. @param sourceHeight the height of the rectangle to copy from the source image
  18190. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  18191. the source image's alpha channel is used as a mask with
  18192. which to fill the destination using the current colour
  18193. or brush. (If the source is has no alpha channel, then
  18194. it will just fill the target with a solid rectangle)
  18195. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  18196. */
  18197. void drawImage (const Image& imageToDraw,
  18198. int destX, int destY, int destWidth, int destHeight,
  18199. int sourceX, int sourceY, int sourceWidth, int sourceHeight,
  18200. bool fillAlphaChannelWithCurrentBrush = false) const;
  18201. /** Draws part of an image, having applied an affine transform to it.
  18202. This lets you throw the image around in some wacky ways, rotate it, shear,
  18203. scale it, etc.
  18204. A subregion is specified within the source image, and all transformations
  18205. will be treated as relative to the origin of this sub-region. So, for example if
  18206. your subregion is (50, 50, 100, 100), and your transform is a translation of (20, 20),
  18207. the resulting pixel drawn at (20, 20) in the destination context is from (50, 50) in
  18208. your image. If you want to use the whole image, then Image::getBounds() returns a
  18209. suitable rectangle to use as the imageSubRegion parameter.
  18210. Images are composited using the context's current opacity, so if you
  18211. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  18212. (or setColour() with an opaque colour) before drawing images.
  18213. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  18214. are ignored and it is filled with the current brush, masked by its alpha channel.
  18215. @see setImageResamplingQuality, drawImage
  18216. */
  18217. void drawImageTransformed (const Image& imageToDraw,
  18218. const Rectangle<int>& imageSubRegion,
  18219. const AffineTransform& transform,
  18220. bool fillAlphaChannelWithCurrentBrush = false) const;
  18221. /** Draws an image to fit within a designated rectangle.
  18222. If the image is too big or too small for the space, it will be rescaled
  18223. to fit as nicely as it can do without affecting its aspect ratio. It will
  18224. then be placed within the target rectangle according to the justification flags
  18225. specified.
  18226. @param imageToDraw the source image to draw
  18227. @param destX top-left of the target rectangle to fit it into
  18228. @param destY top-left of the target rectangle to fit it into
  18229. @param destWidth size of the target rectangle to fit the image into
  18230. @param destHeight size of the target rectangle to fit the image into
  18231. @param placementWithinTarget this specifies how the image should be positioned
  18232. within the target rectangle - see the RectanglePlacement
  18233. class for more details about this.
  18234. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  18235. alpha channel will be used as a mask with which to
  18236. draw with the current brush or colour. This is
  18237. similar to fillAlphaMap(), and see also drawImage()
  18238. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  18239. */
  18240. void drawImageWithin (const Image& imageToDraw,
  18241. int destX, int destY, int destWidth, int destHeight,
  18242. const RectanglePlacement& placementWithinTarget,
  18243. bool fillAlphaChannelWithCurrentBrush = false) const;
  18244. /** Returns the position of the bounding box for the current clipping region.
  18245. @see getClipRegion, clipRegionIntersects
  18246. */
  18247. const Rectangle<int> getClipBounds() const;
  18248. /** Checks whether a rectangle overlaps the context's clipping region.
  18249. If this returns false, no part of the given area can be drawn onto, so this
  18250. method can be used to optimise a component's paint() method, by letting it
  18251. avoid drawing complex objects that aren't within the region being repainted.
  18252. */
  18253. bool clipRegionIntersects (int x, int y, int width, int height) const;
  18254. /** Intersects the current clipping region with another region.
  18255. @returns true if the resulting clipping region is non-zero in size
  18256. @see setOrigin, clipRegionIntersects
  18257. */
  18258. bool reduceClipRegion (int x, int y, int width, int height);
  18259. /** Intersects the current clipping region with a rectangle list region.
  18260. @returns true if the resulting clipping region is non-zero in size
  18261. @see setOrigin, clipRegionIntersects
  18262. */
  18263. bool reduceClipRegion (const RectangleList& clipRegion);
  18264. /** Intersects the current clipping region with a path.
  18265. @returns true if the resulting clipping region is non-zero in size
  18266. @see reduceClipRegion
  18267. */
  18268. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity);
  18269. /** Intersects the current clipping region with an image's alpha-channel.
  18270. The current clipping path is intersected with the area covered by this image's
  18271. alpha-channel, after the image has been transformed by the specified matrix.
  18272. @param image the image whose alpha-channel should be used. If the image doesn't
  18273. have an alpha-channel, it is treated as entirely opaque.
  18274. @param sourceClipRegion a subsection of the image that should be used. To use the
  18275. entire image, just pass a rectangle of bounds
  18276. (0, 0, image.getWidth(), image.getHeight()).
  18277. @param transform a matrix to apply to the image
  18278. @returns true if the resulting clipping region is non-zero in size
  18279. @see reduceClipRegion
  18280. */
  18281. bool reduceClipRegion (const Image& image, const Rectangle<int>& sourceClipRegion,
  18282. const AffineTransform& transform);
  18283. /** Excludes a rectangle to stop it being drawn into. */
  18284. void excludeClipRegion (const Rectangle<int>& rectangleToExclude);
  18285. /** Returns true if no drawing can be done because the clip region is zero. */
  18286. bool isClipEmpty() const;
  18287. /** Saves the current graphics state on an internal stack.
  18288. To restore the state, use restoreState().
  18289. */
  18290. void saveState();
  18291. /** Restores a graphics state that was previously saved with saveState().
  18292. */
  18293. void restoreState();
  18294. /** Moves the position of the context's origin.
  18295. This changes the position that the context considers to be (0, 0) to
  18296. the specified position.
  18297. So if you call setOrigin (100, 100), then the position that was previously
  18298. referred to as (100, 100) will subsequently be considered to be (0, 0).
  18299. @see reduceClipRegion
  18300. */
  18301. void setOrigin (int newOriginX, int newOriginY);
  18302. /** Resets the current colour, brush, and font to default settings. */
  18303. void resetToDefaultState();
  18304. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  18305. bool isVectorDevice() const;
  18306. juce_UseDebuggingNewOperator
  18307. /** Create a graphics that uses a given low-level renderer.
  18308. For internal use only.
  18309. NB. The context will NOT be deleted by this object when it is deleted.
  18310. */
  18311. Graphics (LowLevelGraphicsContext* const internalContext) throw();
  18312. /** @internal */
  18313. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  18314. private:
  18315. LowLevelGraphicsContext* const context;
  18316. ScopedPointer <LowLevelGraphicsContext> contextToDelete;
  18317. bool saveStatePending;
  18318. void saveStateIfPending();
  18319. Graphics (const Graphics&);
  18320. Graphics& operator= (const Graphics& other);
  18321. };
  18322. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  18323. /*** End of inlined file: juce_Graphics.h ***/
  18324. /**
  18325. A graphical effect filter that can be applied to components.
  18326. An ImageEffectFilter can be applied to the image that a component
  18327. paints before it hits the screen.
  18328. This is used for adding effects like shadows, blurs, etc.
  18329. @see Component::setComponentEffect
  18330. */
  18331. class JUCE_API ImageEffectFilter
  18332. {
  18333. public:
  18334. /** Overridden to render the effect.
  18335. The implementation of this method must use the image that is passed in
  18336. as its source, and should render its output to the graphics context passed in.
  18337. @param sourceImage the image that the source component has just rendered with
  18338. its paint() method. The image may or may not have an alpha
  18339. channel, depending on whether the component is opaque.
  18340. @param destContext the graphics context to use to draw the resultant image.
  18341. */
  18342. virtual void applyEffect (Image& sourceImage,
  18343. Graphics& destContext) = 0;
  18344. /** Destructor. */
  18345. virtual ~ImageEffectFilter() {}
  18346. };
  18347. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  18348. /*** End of inlined file: juce_ImageEffectFilter.h ***/
  18349. /*** Start of inlined file: juce_Image.h ***/
  18350. #ifndef __JUCE_IMAGE_JUCEHEADER__
  18351. #define __JUCE_IMAGE_JUCEHEADER__
  18352. /**
  18353. Holds a fixed-size bitmap.
  18354. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  18355. To draw into an image, create a Graphics object for it.
  18356. e.g. @code
  18357. // create a transparent 500x500 image..
  18358. Image myImage (Image::RGB, 500, 500, true);
  18359. Graphics g (myImage);
  18360. g.setColour (Colours::red);
  18361. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  18362. @endcode
  18363. Other useful ways to create an image are with the ImageCache class, or the
  18364. ImageFileFormat, which provides a way to load common image files.
  18365. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  18366. */
  18367. class JUCE_API Image
  18368. {
  18369. public:
  18370. /**
  18371. */
  18372. enum PixelFormat
  18373. {
  18374. UnknownFormat,
  18375. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  18376. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  18377. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  18378. };
  18379. /**
  18380. */
  18381. enum ImageType
  18382. {
  18383. SoftwareImage = 0,
  18384. NativeImage
  18385. };
  18386. /** Creates a null image. */
  18387. Image();
  18388. /** Creates an image with a specified size and format.
  18389. @param format the number of colour channels in the image
  18390. @param imageWidth the desired width of the image, in pixels - this value must be
  18391. greater than zero (otherwise a width of 1 will be used)
  18392. @param imageHeight the desired width of the image, in pixels - this value must be
  18393. greater than zero (otherwise a height of 1 will be used)
  18394. @param clearImage if true, the image will initially be cleared to black (if it's RGB)
  18395. or transparent black (if it's ARGB). If false, the image may contain
  18396. junk initially, so you need to make sure you overwrite it thoroughly.
  18397. @param type the type of image - this lets you specify whether you want a purely
  18398. memory-based image, or one that may be managed by the OS if possible.
  18399. */
  18400. Image (PixelFormat format,
  18401. int imageWidth,
  18402. int imageHeight,
  18403. bool clearImage,
  18404. ImageType type = NativeImage);
  18405. /** Creates a shared reference to another image.
  18406. This won't create a duplicate of the image - when Image objects are copied, they simply
  18407. point to the same shared image data. To make sure that an Image object has its own unique,
  18408. unshared internal data, call duplicateIfShared().
  18409. */
  18410. Image (const Image& other);
  18411. /** Makes this image refer to the same underlying image as another object.
  18412. This won't create a duplicate of the image - when Image objects are copied, they simply
  18413. point to the same shared image data. To make sure that an Image object has its own unique,
  18414. unshared internal data, call duplicateIfShared().
  18415. */
  18416. Image& operator= (const Image&);
  18417. /** Destructor. */
  18418. ~Image();
  18419. /** Returns true if the two images are referring to the same internal, shared image. */
  18420. bool operator== (const Image& other) const throw() { return image == other.image; }
  18421. /** Returns true if the two images are not referring to the same internal, shared image. */
  18422. bool operator!= (const Image& other) const throw() { return image != other.image; }
  18423. /** Returns true if this image isn't null.
  18424. If you create an Image with the default constructor, it has no size or content, and is null
  18425. until you reassign it to an Image which contains some actual data.
  18426. The isNull() method is the opposite of isValid().
  18427. @see isNull
  18428. */
  18429. inline bool isValid() const throw() { return image != 0; }
  18430. /** Returns true if this image is not valid.
  18431. If you create an Image with the default constructor, it has no size or content, and is null
  18432. until you reassign it to an Image which contains some actual data.
  18433. The isNull() method is the opposite of isValid().
  18434. @see isValid
  18435. */
  18436. inline bool isNull() const throw() { return image == 0; }
  18437. /** Returns the image's width (in pixels). */
  18438. int getWidth() const throw() { return image == 0 ? 0 : image->width; }
  18439. /** Returns the image's height (in pixels). */
  18440. int getHeight() const throw() { return image == 0 ? 0 : image->height; }
  18441. /** Returns a rectangle with the same size as this image.
  18442. The rectangle's origin is always (0, 0).
  18443. */
  18444. const Rectangle<int> getBounds() const throw() { return image == 0 ? Rectangle<int>() : Rectangle<int> (0, 0, image->width, image->height); }
  18445. /** Returns the image's pixel format. */
  18446. PixelFormat getFormat() const throw() { return image == 0 ? UnknownFormat : image->format; }
  18447. /** True if the image's format is ARGB. */
  18448. bool isARGB() const throw() { return getFormat() == ARGB; }
  18449. /** True if the image's format is RGB. */
  18450. bool isRGB() const throw() { return getFormat() == RGB; }
  18451. /** True if the image's format is a single-channel alpha map. */
  18452. bool isSingleChannel() const throw() { return getFormat() == SingleChannel; }
  18453. /** True if the image contains an alpha-channel. */
  18454. bool hasAlphaChannel() const throw() { return getFormat() != RGB; }
  18455. /** Clears a section of the image with a given colour.
  18456. This won't do any alpha-blending - it just sets all pixels in the image to
  18457. the given colour (which may be non-opaque if the image has an alpha channel).
  18458. */
  18459. void clear (const Rectangle<int>& area, const Colour& colourToClearTo = Colour (0x00000000));
  18460. /** Returns a rescaled version of this image.
  18461. A new image is returned which is a copy of this one, rescaled to the given size.
  18462. Note that if the new size is identical to the existing image, this will just return
  18463. a reference to the original image, and won't actually create a duplicate.
  18464. */
  18465. const Image rescaled (int newWidth, int newHeight,
  18466. Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  18467. /** Returns a version of this image with a different image format.
  18468. A new image is returned which has been converted to the specified format.
  18469. Note that if the new format is no different to the current one, this will just return
  18470. a reference to the original image, and won't actually create a copy.
  18471. */
  18472. const Image convertedToFormat (PixelFormat newFormat) const;
  18473. /** Makes sure that no other Image objects share the same underlying data as this one.
  18474. If no other Image objects refer to the same shared data as this one, this method has no
  18475. effect. But if there are other references to the data, this will create a new copy of
  18476. the data internally.
  18477. Call this if you want to draw onto the image, but want to make sure that this doesn't
  18478. affect any other code that may be sharing the same data.
  18479. @see getReferenceCount
  18480. */
  18481. void duplicateIfShared();
  18482. /** Returns the colour of one of the pixels in the image.
  18483. If the co-ordinates given are beyond the image's boundaries, this will
  18484. return Colours::transparentBlack.
  18485. @see setPixelAt, Image::BitmapData::getPixelColour
  18486. */
  18487. const Colour getPixelAt (int x, int y) const;
  18488. /** Sets the colour of one of the image's pixels.
  18489. If the co-ordinates are beyond the image's boundaries, then nothing will happen.
  18490. Note that this won't do any alpha-blending, it'll just replace the existing pixel
  18491. with the given one. The colour's opacity will be ignored if this image doesn't have
  18492. an alpha-channel.
  18493. @see getPixelAt, Image::BitmapData::setPixelColour
  18494. */
  18495. void setPixelAt (int x, int y, const Colour& colour);
  18496. /** Changes the opacity of a pixel.
  18497. This only has an effect if the image has an alpha channel and if the
  18498. given co-ordinates are inside the image's boundary.
  18499. The multiplier must be in the range 0 to 1.0, and the current alpha
  18500. at the given co-ordinates will be multiplied by this value.
  18501. @see setPixelAt
  18502. */
  18503. void multiplyAlphaAt (int x, int y, float multiplier);
  18504. /** Changes the overall opacity of the image.
  18505. This will multiply the alpha value of each pixel in the image by the given
  18506. amount (limiting the resulting alpha values between 0 and 255). This allows
  18507. you to make an image more or less transparent.
  18508. If the image doesn't have an alpha channel, this won't have any effect.
  18509. */
  18510. void multiplyAllAlphas (float amountToMultiplyBy);
  18511. /** Changes all the colours to be shades of grey, based on their current luminosity.
  18512. */
  18513. void desaturate();
  18514. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  18515. You should only use this class as a last resort - messing about with the internals of
  18516. an image is only recommended for people who really know what they're doing!
  18517. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  18518. hanging around while the image is being used elsewhere.
  18519. Depending on the way the image class is implemented, this may create a temporary buffer
  18520. which is copied back to the image when the object is deleted, or it may just get a pointer
  18521. directly into the image's raw data.
  18522. You can use the stride and data values in this class directly, but don't alter them!
  18523. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  18524. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  18525. */
  18526. class BitmapData
  18527. {
  18528. public:
  18529. BitmapData (Image& image, int x, int y, int w, int h, bool needsToBeWritable);
  18530. BitmapData (const Image& image, int x, int y, int w, int h);
  18531. ~BitmapData();
  18532. /** Returns a pointer to the start of a line in the image.
  18533. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  18534. sure it's not out-of-range.
  18535. */
  18536. inline uint8* getLinePointer (int y) const throw() { return data + y * lineStride; }
  18537. /** Returns a pointer to a pixel in the image.
  18538. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  18539. not out-of-range.
  18540. */
  18541. inline uint8* getPixelPointer (int x, int y) const throw() { return data + y * lineStride + x * pixelStride; }
  18542. /** Returns the colour of a given pixel.
  18543. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  18544. repsonsibility to make sure they're within the image's size.
  18545. */
  18546. const Colour getPixelColour (int x, int y) const throw();
  18547. /** Sets the colour of a given pixel.
  18548. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  18549. repsonsibility to make sure they're within the image's size.
  18550. */
  18551. void setPixelColour (int x, int y, const Colour& colour) const throw();
  18552. uint8* data;
  18553. const PixelFormat pixelFormat;
  18554. int lineStride, pixelStride, width, height;
  18555. private:
  18556. BitmapData (const BitmapData&);
  18557. BitmapData& operator= (const BitmapData&);
  18558. };
  18559. /** Copies some pixel values to a rectangle of the image.
  18560. The format of the pixel data must match that of the image itself, and the
  18561. rectangle supplied must be within the image's bounds.
  18562. */
  18563. void setPixelData (int destX, int destY, int destW, int destH,
  18564. const uint8* sourcePixelData, int sourceLineStride);
  18565. /** Copies a section of the image to somewhere else within itself. */
  18566. void moveImageSection (int destX, int destY,
  18567. int sourceX, int sourceY,
  18568. int width, int height);
  18569. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  18570. of the image.
  18571. @param result the list that will have the area added to it
  18572. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  18573. above this level will be considered opaque
  18574. */
  18575. void createSolidAreaMask (RectangleList& result,
  18576. float alphaThreshold = 0.5f) const;
  18577. /** Returns a user-specified data item that was set with setTag().
  18578. setTag() and getTag() allow you to attach an arbitrary identifier value to an
  18579. image. The value is shared between all Image object that are referring to the
  18580. same underlying image data object.
  18581. */
  18582. const var getTag() const;
  18583. /** Attaches a user-specified data item to this image, which can be retrieved using getTag().
  18584. setTag() and getTag() allow you to attach an arbitrary identifier value to an
  18585. image. The value is shared between all Image object that are referring to the
  18586. same underlying image data object.
  18587. Note that if this Image is null, this method will fail to store the data.
  18588. */
  18589. void setTag (const var& newTag);
  18590. /** Creates a context suitable for drawing onto this image.
  18591. Don't call this method directly! It's used internally by the Graphics class.
  18592. */
  18593. LowLevelGraphicsContext* createLowLevelContext() const;
  18594. /** Returns the number of Image objects which are currently referring to the same internal
  18595. shared image data.
  18596. @see duplicateIfShared
  18597. */
  18598. int getReferenceCount() const throw() { return image == 0 ? 0 : image->getReferenceCount(); }
  18599. /** This is a base class for task-specific types of image.
  18600. Don't use this class directly! It's used internally by the Image class.
  18601. */
  18602. class SharedImage : public ReferenceCountedObject
  18603. {
  18604. public:
  18605. SharedImage (PixelFormat format, int width, int height);
  18606. ~SharedImage();
  18607. virtual LowLevelGraphicsContext* createLowLevelContext() = 0;
  18608. virtual SharedImage* clone() = 0;
  18609. virtual ImageType getType() const = 0;
  18610. static SharedImage* createNativeImage (PixelFormat format, int width, int height, bool clearImage);
  18611. static SharedImage* createSoftwareImage (PixelFormat format, int width, int height, bool clearImage);
  18612. protected:
  18613. friend class Image;
  18614. friend class Image::BitmapData;
  18615. const PixelFormat format;
  18616. const int width, height;
  18617. int pixelStride, lineStride;
  18618. uint8* imageData;
  18619. var userTag;
  18620. uint8* getPixelData (int x, int y) const throw();
  18621. SharedImage (const SharedImage&);
  18622. SharedImage& operator= (const SharedImage&);
  18623. };
  18624. /** @internal */
  18625. SharedImage* getSharedImage() const throw() { return image; }
  18626. /** @internal */
  18627. explicit Image (SharedImage* instance);
  18628. juce_UseDebuggingNewOperator
  18629. private:
  18630. ReferenceCountedObjectPtr<SharedImage> image;
  18631. };
  18632. #endif // __JUCE_IMAGE_JUCEHEADER__
  18633. /*** End of inlined file: juce_Image.h ***/
  18634. /*** Start of inlined file: juce_RectangleList.h ***/
  18635. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  18636. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  18637. /**
  18638. Maintains a set of rectangles as a complex region.
  18639. This class allows a set of rectangles to be treated as a solid shape, and can
  18640. add and remove rectangular sections of it, and simplify overlapping or
  18641. adjacent rectangles.
  18642. @see Rectangle
  18643. */
  18644. class JUCE_API RectangleList
  18645. {
  18646. public:
  18647. /** Creates an empty RectangleList */
  18648. RectangleList() throw();
  18649. /** Creates a copy of another list */
  18650. RectangleList (const RectangleList& other);
  18651. /** Creates a list containing just one rectangle. */
  18652. RectangleList (const Rectangle<int>& rect);
  18653. /** Copies this list from another one. */
  18654. RectangleList& operator= (const RectangleList& other);
  18655. /** Destructor. */
  18656. ~RectangleList();
  18657. /** Returns true if the region is empty. */
  18658. bool isEmpty() const throw();
  18659. /** Returns the number of rectangles in the list. */
  18660. int getNumRectangles() const throw() { return rects.size(); }
  18661. /** Returns one of the rectangles at a particular index.
  18662. @returns the rectangle at the index, or an empty rectangle if the
  18663. index is out-of-range.
  18664. */
  18665. const Rectangle<int> getRectangle (int index) const throw();
  18666. /** Removes all rectangles to leave an empty region. */
  18667. void clear();
  18668. /** Merges a new rectangle into the list.
  18669. The rectangle being added will first be clipped to remove any parts of it
  18670. that overlap existing rectangles in the list.
  18671. */
  18672. void add (int x, int y, int width, int height);
  18673. /** Merges a new rectangle into the list.
  18674. The rectangle being added will first be clipped to remove any parts of it
  18675. that overlap existing rectangles in the list, and adjacent rectangles will be
  18676. merged into it.
  18677. */
  18678. void add (const Rectangle<int>& rect);
  18679. /** Dumbly adds a rectangle to the list without checking for overlaps.
  18680. This simply adds the rectangle to the end, it doesn't merge it or remove
  18681. any overlapping bits.
  18682. */
  18683. void addWithoutMerging (const Rectangle<int>& rect);
  18684. /** Merges another rectangle list into this one.
  18685. Any overlaps between the two lists will be clipped, so that the result is
  18686. the union of both lists.
  18687. */
  18688. void add (const RectangleList& other);
  18689. /** Removes a rectangular region from the list.
  18690. Any rectangles in the list which overlap this will be clipped and subdivided
  18691. if necessary.
  18692. */
  18693. void subtract (const Rectangle<int>& rect);
  18694. /** Removes all areas in another RectangleList from this one.
  18695. Any rectangles in the list which overlap this will be clipped and subdivided
  18696. if necessary.
  18697. @returns true if the resulting list is non-empty.
  18698. */
  18699. bool subtract (const RectangleList& otherList);
  18700. /** Removes any areas of the region that lie outside a given rectangle.
  18701. Any rectangles in the list which overlap this will be clipped and subdivided
  18702. if necessary.
  18703. Returns true if the resulting region is not empty, false if it is empty.
  18704. @see getIntersectionWith
  18705. */
  18706. bool clipTo (const Rectangle<int>& rect);
  18707. /** Removes any areas of the region that lie outside a given rectangle list.
  18708. Any rectangles in this object which overlap the specified list will be clipped
  18709. and subdivided if necessary.
  18710. Returns true if the resulting region is not empty, false if it is empty.
  18711. @see getIntersectionWith
  18712. */
  18713. bool clipTo (const RectangleList& other);
  18714. /** Creates a region which is the result of clipping this one to a given rectangle.
  18715. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  18716. resulting region into the list whose reference is passed-in.
  18717. Returns true if the resulting region is not empty, false if it is empty.
  18718. @see clipTo
  18719. */
  18720. bool getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const;
  18721. /** Swaps the contents of this and another list.
  18722. This swaps their internal pointers, so is hugely faster than using copy-by-value
  18723. to swap them.
  18724. */
  18725. void swapWith (RectangleList& otherList) throw();
  18726. /** Checks whether the region contains a given point.
  18727. @returns true if the point lies within one of the rectangles in the list
  18728. */
  18729. bool containsPoint (int x, int y) const throw();
  18730. /** Checks whether the region contains the whole of a given rectangle.
  18731. @returns true all parts of the rectangle passed in lie within the region
  18732. defined by this object
  18733. @see intersectsRectangle, containsPoint
  18734. */
  18735. bool containsRectangle (const Rectangle<int>& rectangleToCheck) const;
  18736. /** Checks whether the region contains any part of a given rectangle.
  18737. @returns true if any part of the rectangle passed in lies within the region
  18738. defined by this object
  18739. @see containsRectangle
  18740. */
  18741. bool intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw();
  18742. /** Checks whether this region intersects any part of another one.
  18743. @see intersectsRectangle
  18744. */
  18745. bool intersects (const RectangleList& other) const throw();
  18746. /** Returns the smallest rectangle that can enclose the whole of this region. */
  18747. const Rectangle<int> getBounds() const throw();
  18748. /** Optimises the list into a minimum number of constituent rectangles.
  18749. This will try to combine any adjacent rectangles into larger ones where
  18750. possible, to simplify lists that might have been fragmented by repeated
  18751. add/subtract calls.
  18752. */
  18753. void consolidate();
  18754. /** Adds an x and y value to all the co-ordinates. */
  18755. void offsetAll (int dx, int dy) throw();
  18756. /** Creates a Path object to represent this region. */
  18757. const Path toPath() const;
  18758. /** An iterator for accessing all the rectangles in a RectangleList. */
  18759. class Iterator
  18760. {
  18761. public:
  18762. Iterator (const RectangleList& list) throw();
  18763. ~Iterator();
  18764. /** Advances to the next rectangle, and returns true if it's not finished.
  18765. Call this before using getRectangle() to find the rectangle that was returned.
  18766. */
  18767. bool next() throw();
  18768. /** Returns the current rectangle. */
  18769. const Rectangle<int>* getRectangle() const throw() { return current; }
  18770. juce_UseDebuggingNewOperator
  18771. private:
  18772. const Rectangle<int>* current;
  18773. const RectangleList& owner;
  18774. int index;
  18775. Iterator (const Iterator&);
  18776. Iterator& operator= (const Iterator&);
  18777. };
  18778. juce_UseDebuggingNewOperator
  18779. private:
  18780. friend class Iterator;
  18781. Array <Rectangle<int> > rects;
  18782. };
  18783. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  18784. /*** End of inlined file: juce_RectangleList.h ***/
  18785. /*** Start of inlined file: juce_BorderSize.h ***/
  18786. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  18787. #define __JUCE_BORDERSIZE_JUCEHEADER__
  18788. /**
  18789. Specifies a set of gaps to be left around the sides of a rectangle.
  18790. This is basically the size of the spaces at the top, bottom, left and right of
  18791. a rectangle. It's used by various component classes to specify borders.
  18792. @see Rectangle
  18793. */
  18794. class JUCE_API BorderSize
  18795. {
  18796. public:
  18797. /** Creates a null border.
  18798. All sizes are left as 0.
  18799. */
  18800. BorderSize() throw();
  18801. /** Creates a copy of another border. */
  18802. BorderSize (const BorderSize& other) throw();
  18803. /** Creates a border with the given gaps. */
  18804. BorderSize (int topGap,
  18805. int leftGap,
  18806. int bottomGap,
  18807. int rightGap) throw();
  18808. /** Creates a border with the given gap on all sides. */
  18809. explicit BorderSize (int allGaps) throw();
  18810. /** Destructor. */
  18811. ~BorderSize() throw();
  18812. /** Returns the gap that should be left at the top of the region. */
  18813. int getTop() const throw() { return top; }
  18814. /** Returns the gap that should be left at the top of the region. */
  18815. int getLeft() const throw() { return left; }
  18816. /** Returns the gap that should be left at the top of the region. */
  18817. int getBottom() const throw() { return bottom; }
  18818. /** Returns the gap that should be left at the top of the region. */
  18819. int getRight() const throw() { return right; }
  18820. /** Returns the sum of the top and bottom gaps. */
  18821. int getTopAndBottom() const throw() { return top + bottom; }
  18822. /** Returns the sum of the left and right gaps. */
  18823. int getLeftAndRight() const throw() { return left + right; }
  18824. /** Changes the top gap. */
  18825. void setTop (int newTopGap) throw();
  18826. /** Changes the left gap. */
  18827. void setLeft (int newLeftGap) throw();
  18828. /** Changes the bottom gap. */
  18829. void setBottom (int newBottomGap) throw();
  18830. /** Changes the right gap. */
  18831. void setRight (int newRightGap) throw();
  18832. /** Returns a rectangle with these borders removed from it. */
  18833. const Rectangle<int> subtractedFrom (const Rectangle<int>& original) const throw();
  18834. /** Removes this border from a given rectangle. */
  18835. void subtractFrom (Rectangle<int>& rectangle) const throw();
  18836. /** Returns a rectangle with these borders added around it. */
  18837. const Rectangle<int> addedTo (const Rectangle<int>& original) const throw();
  18838. /** Adds this border around a given rectangle. */
  18839. void addTo (Rectangle<int>& original) const throw();
  18840. bool operator== (const BorderSize& other) const throw();
  18841. bool operator!= (const BorderSize& other) const throw();
  18842. juce_UseDebuggingNewOperator
  18843. private:
  18844. int top, left, bottom, right;
  18845. };
  18846. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  18847. /*** End of inlined file: juce_BorderSize.h ***/
  18848. class LookAndFeel;
  18849. class MouseInputSource;
  18850. class MouseInputSourceInternal;
  18851. class ComponentPeer;
  18852. /**
  18853. The base class for all JUCE user-interface objects.
  18854. */
  18855. class JUCE_API Component : public MouseListener,
  18856. public MessageListener
  18857. {
  18858. public:
  18859. /** Creates a component.
  18860. To get it to actually appear, you'll also need to:
  18861. - Either add it to a parent component or use the addToDesktop() method to
  18862. make it a desktop window
  18863. - Set its size and position to something sensible
  18864. - Use setVisible() to make it visible
  18865. And for it to serve any useful purpose, you'll need to write a
  18866. subclass of Component or use one of the other types of component from
  18867. the library.
  18868. */
  18869. Component();
  18870. /** Destructor.
  18871. Note that when a component is deleted, any child components it might
  18872. contain are NOT deleted unless you explicitly call deleteAllChildren() first.
  18873. */
  18874. virtual ~Component();
  18875. /** Creates a component, setting its name at the same time.
  18876. @see getName, setName
  18877. */
  18878. explicit Component (const String& componentName);
  18879. /** Returns the name of this component.
  18880. @see setName
  18881. */
  18882. const String& getName() const throw() { return componentName_; }
  18883. /** Sets the name of this component.
  18884. When the name changes, all registered ComponentListeners will receive a
  18885. ComponentListener::componentNameChanged() callback.
  18886. @see getName
  18887. */
  18888. virtual void setName (const String& newName);
  18889. /** Checks whether this Component object has been deleted.
  18890. This will check whether this object is still a valid component, or whether
  18891. it's been deleted.
  18892. It's safe to call this on null or dangling pointers, but note that there is a
  18893. small risk if another new (but different) component has been created at the
  18894. same memory address which this one occupied, this methods can return a
  18895. false positive.
  18896. */
  18897. bool isValidComponent() const;
  18898. /** Makes the component visible or invisible.
  18899. This method will show or hide the component.
  18900. Note that components default to being non-visible when first created.
  18901. Also note that visible components won't be seen unless all their parent components
  18902. are also visible.
  18903. This method will call visibilityChanged() and also componentVisibilityChanged()
  18904. for any component listeners that are interested in this component.
  18905. @param shouldBeVisible whether to show or hide the component
  18906. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  18907. */
  18908. virtual void setVisible (bool shouldBeVisible);
  18909. /** Tests whether the component is visible or not.
  18910. this doesn't necessarily tell you whether this comp is actually on the screen
  18911. because this depends on whether all the parent components are also visible - use
  18912. isShowing() to find this out.
  18913. @see isShowing, setVisible
  18914. */
  18915. bool isVisible() const throw() { return flags.visibleFlag; }
  18916. /** Called when this component's visiblility changes.
  18917. @see setVisible, isVisible
  18918. */
  18919. virtual void visibilityChanged();
  18920. /** Tests whether this component and all its parents are visible.
  18921. @returns true only if this component and all its parents are visible.
  18922. @see isVisible
  18923. */
  18924. bool isShowing() const;
  18925. /** Makes a component invisible using a groovy fade-out and animated zoom effect.
  18926. To do this, this function will cunningly:
  18927. - take a snapshot of the component as it currently looks
  18928. - call setVisible(false) on the component
  18929. - replace it with a special component that will continue drawing the
  18930. snapshot, animating it and gradually making it more transparent
  18931. - when it's gone, the special component will also be deleted
  18932. As soon as this method returns, the component can be safely removed and deleted
  18933. leaving the proxy to do the fade-out, so it's even ok to call this in a
  18934. component's destructor.
  18935. Passing non-zero x and y values will cause the ghostly component image to
  18936. also whizz off by this distance while fading out. If the scale factor is
  18937. not 1.0, it will also zoom from the component's current size to this new size.
  18938. One thing to be careful about is that the parent component must be able to cope
  18939. with this unknown component type being added to it.
  18940. */
  18941. void fadeOutComponent (int lengthOfFadeOutInMilliseconds,
  18942. int deltaXToMove = 0,
  18943. int deltaYToMove = 0,
  18944. float scaleFactorAtEnd = 1.0f);
  18945. /** Makes this component appear as a window on the desktop.
  18946. Note that before calling this, you should make sure that the component's opacity is
  18947. set correctly using setOpaque(). If the component is non-opaque, the windowing
  18948. system will try to create a special transparent window for it, which will generally take
  18949. a lot more CPU to operate (and might not even be possible on some platforms).
  18950. If the component is inside a parent component at the time this method is called, it
  18951. will be first be removed from that parent. Likewise if a component on the desktop
  18952. is subsequently added to another component, it'll be removed from the desktop.
  18953. @param windowStyleFlags a combination of the flags specified in the
  18954. ComponentPeer::StyleFlags enum, which define the
  18955. window's characteristics.
  18956. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  18957. in which the juce component should place itself. On Windows,
  18958. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  18959. supported on all platforms, and best left as 0 unless you know
  18960. what you're doing
  18961. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  18962. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  18963. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  18964. */
  18965. virtual void addToDesktop (int windowStyleFlags,
  18966. void* nativeWindowToAttachTo = 0);
  18967. /** If the component is currently showing on the desktop, this will hide it.
  18968. You can also use setVisible() to hide a desktop window temporarily, but
  18969. removeFromDesktop() will free any system resources that are being used up.
  18970. @see addToDesktop, isOnDesktop
  18971. */
  18972. void removeFromDesktop();
  18973. /** Returns true if this component is currently showing on the desktop.
  18974. @see addToDesktop, removeFromDesktop
  18975. */
  18976. bool isOnDesktop() const throw();
  18977. /** Returns the heavyweight window that contains this component.
  18978. If this component is itself on the desktop, this will return the window
  18979. object that it is using. Otherwise, it will return the window of
  18980. its top-level parent component.
  18981. This may return 0 if there isn't a desktop component.
  18982. @see addToDesktop, isOnDesktop
  18983. */
  18984. ComponentPeer* getPeer() const;
  18985. /** For components on the desktop, this is called if the system wants to close the window.
  18986. This is a signal that either the user or the system wants the window to close. The
  18987. default implementation of this method will trigger an assertion to warn you that your
  18988. component should do something about it, but you can override this to ignore the event
  18989. if you want.
  18990. */
  18991. virtual void userTriedToCloseWindow();
  18992. /** Called for a desktop component which has just been minimised or un-minimised.
  18993. This will only be called for components on the desktop.
  18994. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  18995. */
  18996. virtual void minimisationStateChanged (bool isNowMinimised);
  18997. /** Brings the component to the front of its siblings.
  18998. If some of the component's siblings have had their 'always-on-top' flag set,
  18999. then they will still be kept in front of this one (unless of course this
  19000. one is also 'always-on-top').
  19001. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  19002. to the component (see grabKeyboardFocus() for more details)
  19003. @see toBack, toBehind, setAlwaysOnTop
  19004. */
  19005. void toFront (bool shouldAlsoGainFocus);
  19006. /** Changes this component's z-order to be at the back of all its siblings.
  19007. If the component is set to be 'always-on-top', it will only be moved to the
  19008. back of the other other 'always-on-top' components.
  19009. @see toFront, toBehind, setAlwaysOnTop
  19010. */
  19011. void toBack();
  19012. /** Changes this component's z-order so that it's just behind another component.
  19013. @see toFront, toBack
  19014. */
  19015. void toBehind (Component* other);
  19016. /** Sets whether the component should always be kept at the front of its siblings.
  19017. @see isAlwaysOnTop
  19018. */
  19019. void setAlwaysOnTop (bool shouldStayOnTop);
  19020. /** Returns true if this component is set to always stay in front of its siblings.
  19021. @see setAlwaysOnTop
  19022. */
  19023. bool isAlwaysOnTop() const throw();
  19024. /** Returns the x co-ordinate of the component's left edge.
  19025. This is a distance in pixels from the left edge of the component's parent.
  19026. @see getScreenX
  19027. */
  19028. inline int getX() const throw() { return bounds_.getX(); }
  19029. /** Returns the y co-ordinate of the top of this component.
  19030. This is a distance in pixels from the top edge of the component's parent.
  19031. @see getScreenY
  19032. */
  19033. inline int getY() const throw() { return bounds_.getY(); }
  19034. /** Returns the component's width in pixels. */
  19035. inline int getWidth() const throw() { return bounds_.getWidth(); }
  19036. /** Returns the component's height in pixels. */
  19037. inline int getHeight() const throw() { return bounds_.getHeight(); }
  19038. /** Returns the x co-ordinate of the component's right-hand edge.
  19039. This is a distance in pixels from the left edge of the component's parent.
  19040. */
  19041. int getRight() const throw() { return bounds_.getRight(); }
  19042. /** Returns the component's top-left position as a Point. */
  19043. const Point<int> getPosition() const throw() { return bounds_.getPosition(); }
  19044. /** Returns the y co-ordinate of the bottom edge of this component.
  19045. This is a distance in pixels from the top edge of the component's parent.
  19046. */
  19047. int getBottom() const throw() { return bounds_.getBottom(); }
  19048. /** Returns this component's bounding box.
  19049. The rectangle returned is relative to the top-left of the component's parent.
  19050. */
  19051. const Rectangle<int>& getBounds() const throw() { return bounds_; }
  19052. /** Returns the component's bounds, relative to its own origin.
  19053. This is like getBounds(), but returns the rectangle in local co-ordinates, In practice, it'll
  19054. return a rectangle with position (0, 0), and the same size as this component.
  19055. */
  19056. const Rectangle<int> getLocalBounds() const throw();
  19057. /** Returns the region of this component that's not obscured by other, opaque components.
  19058. The RectangleList that is returned represents the area of this component
  19059. which isn't covered by opaque child components.
  19060. If includeSiblings is true, it will also take into account any siblings
  19061. that may be overlapping the component.
  19062. */
  19063. void getVisibleArea (RectangleList& result,
  19064. bool includeSiblings) const;
  19065. /** Returns this component's x co-ordinate relative the the screen's top-left origin.
  19066. @see getX, relativePositionToGlobal
  19067. */
  19068. int getScreenX() const;
  19069. /** Returns this component's y co-ordinate relative the the screen's top-left origin.
  19070. @see getY, relativePositionToGlobal
  19071. */
  19072. int getScreenY() const;
  19073. /** Returns the position of this component's top-left corner relative to the screen's top-left.
  19074. @see getScreenBounds
  19075. */
  19076. const Point<int> getScreenPosition() const;
  19077. /** Returns the bounds of this component, relative to the screen's top-left.
  19078. @see getScreenPosition
  19079. */
  19080. const Rectangle<int> getScreenBounds() const;
  19081. /** Converts a position relative to this component's top-left into a screen co-ordinate.
  19082. @see globalPositionToRelative, relativePositionToOtherComponent
  19083. */
  19084. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition) const;
  19085. /** Converts a screen co-ordinate into a position relative to this component's top-left.
  19086. @see relativePositionToGlobal, relativePositionToOtherComponent
  19087. */
  19088. const Point<int> globalPositionToRelative (const Point<int>& screenPosition) const;
  19089. /** Converts a position relative to this component's top-left into a position
  19090. relative to another component's top-left.
  19091. @see relativePositionToGlobal, globalPositionToRelative
  19092. */
  19093. const Point<int> relativePositionToOtherComponent (const Component* targetComponent,
  19094. const Point<int>& positionRelativeToThis) const;
  19095. /** Moves the component to a new position.
  19096. Changes the component's top-left position (without changing its size).
  19097. The position is relative to the top-left of the component's parent.
  19098. If the component actually moves, this method will make a synchronous call to moved().
  19099. @see setBounds, ComponentListener::componentMovedOrResized
  19100. */
  19101. void setTopLeftPosition (int x, int y);
  19102. /** Moves the component to a new position.
  19103. Changes the position of the component's top-right corner (keeping it the same size).
  19104. The position is relative to the top-left of the component's parent.
  19105. If the component actually moves, this method will make a synchronous call to moved().
  19106. */
  19107. void setTopRightPosition (int x, int y);
  19108. /** Changes the size of the component.
  19109. A synchronous call to resized() will be occur if the size actually changes.
  19110. */
  19111. void setSize (int newWidth, int newHeight);
  19112. /** Changes the component's position and size.
  19113. The co-ordinates are relative to the top-left of the component's parent, or relative
  19114. to the origin of the screen is the component is on the desktop.
  19115. If this method changes the component's top-left position, it will make a synchronous
  19116. call to moved(). If it changes the size, it will also make a call to resized().
  19117. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  19118. */
  19119. void setBounds (int x, int y, int width, int height);
  19120. /** Changes the component's position and size.
  19121. @see setBounds
  19122. */
  19123. void setBounds (const Rectangle<int>& newBounds);
  19124. /** Changes the component's position and size in terms of fractions of its parent's size.
  19125. The values are factors of the parent's size, so for example
  19126. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  19127. width and height of the parent, with its top-left position 20% of
  19128. the way across and down the parent.
  19129. */
  19130. void setBoundsRelative (float proportionalX, float proportionalY,
  19131. float proportionalWidth, float proportionalHeight);
  19132. /** Changes the component's position and size based on the amount of space to leave around it.
  19133. This will position the component within its parent, leaving the specified number of
  19134. pixels around each edge.
  19135. */
  19136. void setBoundsInset (const BorderSize& borders);
  19137. /** Positions the component within a given rectangle, keeping its proportions
  19138. unchanged.
  19139. If onlyReduceInSize is false, the component will be resized to fill as much of the
  19140. rectangle as possible without changing its aspect ratio (the component's
  19141. current size is used to determine its aspect ratio, so a zero-size component
  19142. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  19143. too big to fit inside the rectangle.
  19144. It will then be positioned within the rectangle according to the justification flags
  19145. specified.
  19146. */
  19147. void setBoundsToFit (int x, int y, int width, int height,
  19148. const Justification& justification,
  19149. bool onlyReduceInSize);
  19150. /** Changes the position of the component's centre.
  19151. Leaves the component's size unchanged, but sets the position of its centre
  19152. relative to its parent's top-left.
  19153. */
  19154. void setCentrePosition (int x, int y);
  19155. /** Changes the position of the component's centre.
  19156. Leaves the position unchanged, but positions its centre relative to its
  19157. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  19158. its parent.
  19159. */
  19160. void setCentreRelative (float x, float y);
  19161. /** Changes the component's size and centres it within its parent.
  19162. After changing the size, the component will be moved so that it's
  19163. centred within its parent.
  19164. */
  19165. void centreWithSize (int width, int height);
  19166. /** Returns a proportion of the component's width.
  19167. This is a handy equivalent of (getWidth() * proportion).
  19168. */
  19169. int proportionOfWidth (float proportion) const throw();
  19170. /** Returns a proportion of the component's height.
  19171. This is a handy equivalent of (getHeight() * proportion).
  19172. */
  19173. int proportionOfHeight (float proportion) const throw();
  19174. /** Returns the width of the component's parent.
  19175. If the component has no parent (i.e. if it's on the desktop), this will return
  19176. the width of the screen.
  19177. */
  19178. int getParentWidth() const throw();
  19179. /** Returns the height of the component's parent.
  19180. If the component has no parent (i.e. if it's on the desktop), this will return
  19181. the height of the screen.
  19182. */
  19183. int getParentHeight() const throw();
  19184. /** Returns the screen co-ordinates of the monitor that contains this component.
  19185. If there's only one monitor, this will return its size - if there are multiple
  19186. monitors, it will return the area of the monitor that contains the component's
  19187. centre.
  19188. */
  19189. const Rectangle<int> getParentMonitorArea() const;
  19190. /** Returns the number of child components that this component contains.
  19191. @see getChildComponent, getIndexOfChildComponent
  19192. */
  19193. int getNumChildComponents() const throw();
  19194. /** Returns one of this component's child components, by it index.
  19195. The component with index 0 is at the back of the z-order, the one at the
  19196. front will have index (getNumChildComponents() - 1).
  19197. If the index is out-of-range, this will return a null pointer.
  19198. @see getNumChildComponents, getIndexOfChildComponent
  19199. */
  19200. Component* getChildComponent (int index) const throw();
  19201. /** Returns the index of this component in the list of child components.
  19202. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  19203. values are further towards the front.
  19204. Returns -1 if the component passed-in is not a child of this component.
  19205. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  19206. */
  19207. int getIndexOfChildComponent (const Component* child) const throw();
  19208. /** Adds a child component to this one.
  19209. @param child the new component to add. If the component passed-in is already
  19210. the child of another component, it'll first be removed from that.
  19211. @param zOrder The index in the child-list at which this component should be inserted.
  19212. A value of -1 will insert it in front of the others, 0 is the back.
  19213. @see removeChildComponent, addAndMakeVisible, getChild,
  19214. ComponentListener::componentChildrenChanged
  19215. */
  19216. void addChildComponent (Component* child, int zOrder = -1);
  19217. /** Adds a child component to this one, and also makes the child visible if it isn't.
  19218. Quite a useful function, this is just the same as calling addChildComponent()
  19219. followed by setVisible (true) on the child.
  19220. */
  19221. void addAndMakeVisible (Component* child, int zOrder = -1);
  19222. /** Removes one of this component's child-components.
  19223. If the child passed-in isn't actually a child of this component (either because
  19224. it's invalid or is the child of a different parent), then nothing is done.
  19225. Note that removing a child will not delete it!
  19226. @see addChildComponent, ComponentListener::componentChildrenChanged
  19227. */
  19228. void removeChildComponent (Component* childToRemove);
  19229. /** Removes one of this component's child-components by index.
  19230. This will return a pointer to the component that was removed, or null if
  19231. the index was out-of-range.
  19232. Note that removing a child will not delete it!
  19233. @see addChildComponent, ComponentListener::componentChildrenChanged
  19234. */
  19235. Component* removeChildComponent (int childIndexToRemove);
  19236. /** Removes all this component's children.
  19237. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  19238. */
  19239. void removeAllChildren();
  19240. /** Removes all this component's children, and deletes them.
  19241. @see removeAllChildren
  19242. */
  19243. void deleteAllChildren();
  19244. /** Returns the component which this component is inside.
  19245. If this is the highest-level component or hasn't yet been added to
  19246. a parent, this will return null.
  19247. */
  19248. Component* getParentComponent() const throw() { return parentComponent_; }
  19249. /** Searches the parent components for a component of a specified class.
  19250. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  19251. component that can be dynamically cast to a MyComp, or will return 0 if none
  19252. of the parents are suitable.
  19253. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  19254. */
  19255. template <class TargetClass>
  19256. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  19257. {
  19258. (void) dummyParameter;
  19259. Component* p = parentComponent_;
  19260. while (p != 0)
  19261. {
  19262. TargetClass* target = dynamic_cast <TargetClass*> (p);
  19263. if (target != 0)
  19264. return target;
  19265. p = p->parentComponent_;
  19266. }
  19267. return 0;
  19268. }
  19269. /** Returns the highest-level component which contains this one or its parents.
  19270. This will search upwards in the parent-hierarchy from this component, until it
  19271. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  19272. not yet added to a parent), and will return that.
  19273. */
  19274. Component* getTopLevelComponent() const throw();
  19275. /** Checks whether a component is anywhere inside this component or its children.
  19276. This will recursively check through this components children to see if the
  19277. given component is anywhere inside.
  19278. */
  19279. bool isParentOf (const Component* possibleChild) const throw();
  19280. /** Called to indicate that the component's parents have changed.
  19281. When a component is added or removed from its parent, this method will
  19282. be called on all of its children (recursively - so all children of its
  19283. children will also be called as well).
  19284. Subclasses can override this if they need to react to this in some way.
  19285. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  19286. */
  19287. virtual void parentHierarchyChanged();
  19288. /** Subclasses can use this callback to be told when children are added or removed.
  19289. @see parentHierarchyChanged
  19290. */
  19291. virtual void childrenChanged();
  19292. /** Tests whether a given point inside the component.
  19293. Overriding this method allows you to create components which only intercept
  19294. mouse-clicks within a user-defined area.
  19295. This is called to find out whether a particular x, y co-ordinate is
  19296. considered to be inside the component or not, and is used by methods such
  19297. as contains() and getComponentAt() to work out which component
  19298. the mouse is clicked on.
  19299. Components with custom shapes will probably want to override it to perform
  19300. some more complex hit-testing.
  19301. The default implementation of this method returns either true or false,
  19302. depending on the value that was set by calling setInterceptsMouseClicks() (true
  19303. is the default return value).
  19304. Note that the hit-test region is not related to the opacity with which
  19305. areas of a component are painted.
  19306. Applications should never call hitTest() directly - instead use the
  19307. contains() method, because this will also test for occlusion by the
  19308. component's parent.
  19309. Note that for components on the desktop, this method will be ignored, because it's
  19310. not always possible to implement this behaviour on all platforms.
  19311. @param x the x co-ordinate to test, relative to the left hand edge of this
  19312. component. This value is guaranteed to be greater than or equal to
  19313. zero, and less than the component's width
  19314. @param y the y co-ordinate to test, relative to the top edge of this
  19315. component. This value is guaranteed to be greater than or equal to
  19316. zero, and less than the component's height
  19317. @returns true if the click is considered to be inside the component
  19318. @see setInterceptsMouseClicks, contains
  19319. */
  19320. virtual bool hitTest (int x, int y);
  19321. /** Changes the default return value for the hitTest() method.
  19322. Setting this to false is an easy way to make a component pass its mouse-clicks
  19323. through to the components behind it.
  19324. When a component is created, the default setting for this is true.
  19325. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  19326. return false (or true for child components if allowClicksOnChildComponents
  19327. is true)
  19328. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  19329. components can be clicked on as normal but clicks on this component pass
  19330. straight through; if this is false and allowClicksOnThisComponent
  19331. is false, then neither this component nor any child components can
  19332. be clicked on
  19333. @see hitTest, getInterceptsMouseClicks
  19334. */
  19335. void setInterceptsMouseClicks (bool allowClicksOnThisComponent,
  19336. bool allowClicksOnChildComponents) throw();
  19337. /** Retrieves the current state of the mouse-click interception flags.
  19338. On return, the two parameters are set to the state used in the last call to
  19339. setInterceptsMouseClicks().
  19340. @see setInterceptsMouseClicks
  19341. */
  19342. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  19343. bool& allowsClicksOnChildComponents) const throw();
  19344. /** Returns true if a given point lies within this component or one of its children.
  19345. Never override this method! Use hitTest to create custom hit regions.
  19346. @param x the x co-ordinate to test, relative to this component's left hand edge.
  19347. @param y the y co-ordinate to test, relative to this component's top edge.
  19348. @returns true if the point is within the component's hit-test area, but only if
  19349. that part of the component isn't clipped by its parent component. Note
  19350. that this won't take into account any overlapping sibling components
  19351. which might be in the way - for that, see reallyContains()
  19352. @see hitTest, reallyContains, getComponentAt
  19353. */
  19354. virtual bool contains (int x, int y);
  19355. /** Returns true if a given point lies in this component, taking any overlapping
  19356. siblings into account.
  19357. @param x the x co-ordinate to test, relative to this component's left hand edge.
  19358. @param y the y co-ordinate to test, relative to this component's top edge.
  19359. @param returnTrueIfWithinAChild if the point actually lies within a child of this
  19360. component, this determines the value that will
  19361. be returned.
  19362. @see contains, getComponentAt
  19363. */
  19364. bool reallyContains (int x, int y, bool returnTrueIfWithinAChild);
  19365. /** Returns the component at a certain point within this one.
  19366. @param x the x co-ordinate to test, relative to this component's left hand edge.
  19367. @param y the y co-ordinate to test, relative to this component's top edge.
  19368. @returns the component that is at this position - which may be 0, this component,
  19369. or one of its children. Note that overlapping siblings that might actually
  19370. be in the way are not taken into account by this method - to account for these,
  19371. instead call getComponentAt on the top-level parent of this component.
  19372. @see hitTest, contains, reallyContains
  19373. */
  19374. Component* getComponentAt (int x, int y);
  19375. /** Returns the component at a certain point within this one.
  19376. @param position the co-ordinates to test, relative to this component's top-left.
  19377. @returns the component that is at this position - which may be 0, this component,
  19378. or one of its children. Note that overlapping siblings that might actually
  19379. be in the way are not taken into account by this method - to account for these,
  19380. instead call getComponentAt on the top-level parent of this component.
  19381. @see hitTest, contains, reallyContains
  19382. */
  19383. Component* getComponentAt (const Point<int>& position);
  19384. /** Marks the whole component as needing to be redrawn.
  19385. Calling this will not do any repainting immediately, but will mark the component
  19386. as 'dirty'. At some point in the near future the operating system will send a paint
  19387. message, which will redraw all the dirty regions of all components.
  19388. There's no guarantee about how soon after calling repaint() the redraw will actually
  19389. happen, and other queued events may be delivered before a redraw is done.
  19390. If the setBufferedToImage() method has been used to cause this component
  19391. to use a buffer, the repaint() call will invalidate the component's buffer.
  19392. To redraw just a subsection of the component rather than the whole thing,
  19393. use the repaint (int, int, int, int) method.
  19394. @see paint
  19395. */
  19396. void repaint();
  19397. /** Marks a subsection of this component as needing to be redrawn.
  19398. Calling this will not do any repainting immediately, but will mark the given region
  19399. of the component as 'dirty'. At some point in the near future the operating system
  19400. will send a paint message, which will redraw all the dirty regions of all components.
  19401. There's no guarantee about how soon after calling repaint() the redraw will actually
  19402. happen, and other queued events may be delivered before a redraw is done.
  19403. The region that is passed in will be clipped to keep it within the bounds of this
  19404. component.
  19405. @see repaint()
  19406. */
  19407. void repaint (int x, int y, int width, int height);
  19408. /** Marks a subsection of this component as needing to be redrawn.
  19409. Calling this will not do any repainting immediately, but will mark the given region
  19410. of the component as 'dirty'. At some point in the near future the operating system
  19411. will send a paint message, which will redraw all the dirty regions of all components.
  19412. There's no guarantee about how soon after calling repaint() the redraw will actually
  19413. happen, and other queued events may be delivered before a redraw is done.
  19414. The region that is passed in will be clipped to keep it within the bounds of this
  19415. component.
  19416. @see repaint()
  19417. */
  19418. void repaint (const Rectangle<int>& area);
  19419. /** Makes the component use an internal buffer to optimise its redrawing.
  19420. Setting this flag to true will cause the component to allocate an
  19421. internal buffer into which it paints itself, so that when asked to
  19422. redraw itself, it can use this buffer rather than actually calling the
  19423. paint() method.
  19424. The buffer is kept until the repaint() method is called directly on
  19425. this component (or until it is resized), when the image is invalidated
  19426. and then redrawn the next time the component is painted.
  19427. Note that only the drawing that happens within the component's paint()
  19428. method is drawn into the buffer, it's child components are not buffered, and
  19429. nor is the paintOverChildren() method.
  19430. @see repaint, paint, createComponentSnapshot
  19431. */
  19432. void setBufferedToImage (bool shouldBeBuffered);
  19433. /** Generates a snapshot of part of this component.
  19434. This will return a new Image, the size of the rectangle specified,
  19435. containing a snapshot of the specified area of the component and all
  19436. its children.
  19437. The image may or may not have an alpha-channel, depending on whether the
  19438. image is opaque or not.
  19439. If the clipImageToComponentBounds parameter is true and the area is greater than
  19440. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  19441. then parts of the component beyond its bounds can be drawn.
  19442. @see paintEntireComponent
  19443. */
  19444. const Image createComponentSnapshot (const Rectangle<int>& areaToGrab,
  19445. bool clipImageToComponentBounds = true);
  19446. /** Draws this component and all its subcomponents onto the specified graphics
  19447. context.
  19448. You should very rarely have to use this method, it's simply there in case you need
  19449. to draw a component with a custom graphics context for some reason, e.g. for
  19450. creating a snapshot of the component.
  19451. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  19452. on its children in order to render the entire tree.
  19453. The graphics context may be left in an undefined state after this method returns,
  19454. so you may need to reset it if you're going to use it again.
  19455. */
  19456. void paintEntireComponent (Graphics& context);
  19457. /** Adds an effect filter to alter the component's appearance.
  19458. When a component has an effect filter set, then this is applied to the
  19459. results of its paint() method. There are a few preset effects, such as
  19460. a drop-shadow or glow, but they can be user-defined as well.
  19461. The effect that is passed in will not be deleted by the component - the
  19462. caller must take care of deleting it.
  19463. To remove an effect from a component, pass a null pointer in as the parameter.
  19464. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  19465. */
  19466. void setComponentEffect (ImageEffectFilter* newEffect);
  19467. /** Returns the current component effect.
  19468. @see setComponentEffect
  19469. */
  19470. ImageEffectFilter* getComponentEffect() const throw() { return effect_; }
  19471. /** Finds the appropriate look-and-feel to use for this component.
  19472. If the component hasn't had a look-and-feel explicitly set, this will
  19473. return the parent's look-and-feel, or just the default one if there's no
  19474. parent.
  19475. @see setLookAndFeel, lookAndFeelChanged
  19476. */
  19477. LookAndFeel& getLookAndFeel() const throw();
  19478. /** Sets the look and feel to use for this component.
  19479. This will also change the look and feel for any child components that haven't
  19480. had their look set explicitly.
  19481. The object passed in will not be deleted by the component, so it's the caller's
  19482. responsibility to manage it. It may be used at any time until this component
  19483. has been deleted.
  19484. Calling this method will also invoke the sendLookAndFeelChange() method.
  19485. @see getLookAndFeel, lookAndFeelChanged
  19486. */
  19487. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  19488. /** Called to let the component react to a change in the look-and-feel setting.
  19489. When the look-and-feel is changed for a component, this will be called in
  19490. all its child components, recursively.
  19491. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  19492. an application uses a LookAndFeel class that might have changed internally.
  19493. @see sendLookAndFeelChange, getLookAndFeel
  19494. */
  19495. virtual void lookAndFeelChanged();
  19496. /** Calls the lookAndFeelChanged() method in this component and all its children.
  19497. This will recurse through the children and their children, calling lookAndFeelChanged()
  19498. on them all.
  19499. @see lookAndFeelChanged
  19500. */
  19501. void sendLookAndFeelChange();
  19502. /** Indicates whether any parts of the component might be transparent.
  19503. Components that always paint all of their contents with solid colour and
  19504. thus completely cover any components behind them should use this method
  19505. to tell the repaint system that they are opaque.
  19506. This information is used to optimise drawing, because it means that
  19507. objects underneath opaque windows don't need to be painted.
  19508. By default, components are considered transparent, unless this is used to
  19509. make it otherwise.
  19510. @see isOpaque, getVisibleArea
  19511. */
  19512. void setOpaque (bool shouldBeOpaque);
  19513. /** Returns true if no parts of this component are transparent.
  19514. @returns the value that was set by setOpaque, (the default being false)
  19515. @see setOpaque
  19516. */
  19517. bool isOpaque() const throw();
  19518. /** Indicates whether the component should be brought to the front when clicked.
  19519. Setting this flag to true will cause the component to be brought to the front
  19520. when the mouse is clicked somewhere inside it or its child components.
  19521. Note that a top-level desktop window might still be brought to the front by the
  19522. operating system when it's clicked, depending on how the OS works.
  19523. By default this is set to false.
  19524. @see setMouseClickGrabsKeyboardFocus
  19525. */
  19526. void setBroughtToFrontOnMouseClick (bool shouldBeBroughtToFront) throw();
  19527. /** Indicates whether the component should be brought to the front when clicked-on.
  19528. @see setBroughtToFrontOnMouseClick
  19529. */
  19530. bool isBroughtToFrontOnMouseClick() const throw();
  19531. // Keyboard focus methods
  19532. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  19533. By default components aren't actually interested in gaining the
  19534. focus, but this method can be used to turn this on.
  19535. See the grabKeyboardFocus() method for details about the way a component
  19536. is chosen to receive the focus.
  19537. @see grabKeyboardFocus, getWantsKeyboardFocus
  19538. */
  19539. void setWantsKeyboardFocus (bool wantsFocus) throw();
  19540. /** Returns true if the component is interested in getting keyboard focus.
  19541. This returns the flag set by setWantsKeyboardFocus(). The default
  19542. setting is false.
  19543. @see setWantsKeyboardFocus
  19544. */
  19545. bool getWantsKeyboardFocus() const throw();
  19546. /** Chooses whether a click on this component automatically grabs the focus.
  19547. By default this is set to true, but you might want a component which can
  19548. be focused, but where you don't want the user to be able to affect it directly
  19549. by clicking.
  19550. */
  19551. void setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus);
  19552. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  19553. See setMouseClickGrabsKeyboardFocus() for more info.
  19554. */
  19555. bool getMouseClickGrabsKeyboardFocus() const throw();
  19556. /** Tries to give keyboard focus to this component.
  19557. When the user clicks on a component or its grabKeyboardFocus()
  19558. method is called, the following procedure is used to work out which
  19559. component should get it:
  19560. - if the component that was clicked on actually wants focus (as indicated
  19561. by calling getWantsKeyboardFocus), it gets it.
  19562. - if the component itself doesn't want focus, it will try to pass it
  19563. on to whichever of its children is the default component, as determined by
  19564. KeyboardFocusTraverser::getDefaultComponent()
  19565. - if none of its children want focus at all, it will pass it up to its
  19566. parent instead, unless it's a top-level component without a parent,
  19567. in which case it just takes the focus itself.
  19568. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  19569. getCurrentlyFocusedComponent, focusGained, focusLost,
  19570. keyPressed, keyStateChanged
  19571. */
  19572. void grabKeyboardFocus();
  19573. /** Returns true if this component currently has the keyboard focus.
  19574. @param trueIfChildIsFocused if this is true, then the method returns true if
  19575. either this component or any of its children (recursively)
  19576. have the focus. If false, the method only returns true if
  19577. this component has the focus.
  19578. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  19579. focusGained, focusLost
  19580. */
  19581. bool hasKeyboardFocus (bool trueIfChildIsFocused) const;
  19582. /** Returns the component that currently has the keyboard focus.
  19583. @returns the focused component, or null if nothing is focused.
  19584. */
  19585. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  19586. /** Tries to move the keyboard focus to one of this component's siblings.
  19587. This will try to move focus to either the next or previous component. (This
  19588. is the method that is used when shifting focus by pressing the tab key).
  19589. Components for which getWantsKeyboardFocus() returns false are not looked at.
  19590. @param moveToNext if true, the focus will move forwards; if false, it will
  19591. move backwards
  19592. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  19593. */
  19594. void moveKeyboardFocusToSibling (bool moveToNext);
  19595. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  19596. which focus should be passed from this component.
  19597. The default implementation of this method will return a default
  19598. KeyboardFocusTraverser if this component is a focus container (as determined
  19599. by the setFocusContainer() method). If the component isn't a focus
  19600. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  19601. If you overrride this to return a custom KeyboardFocusTraverser, then
  19602. this component and all its sub-components will use the new object to
  19603. make their focusing decisions.
  19604. The method should return a new object, which the caller is required to
  19605. delete when no longer needed.
  19606. */
  19607. virtual KeyboardFocusTraverser* createFocusTraverser();
  19608. /** Returns the focus order of this component, if one has been specified.
  19609. By default components don't have a focus order - in that case, this
  19610. will return 0. Lower numbers indicate that the component will be
  19611. earlier in the focus traversal order.
  19612. To change the order, call setExplicitFocusOrder().
  19613. The focus order may be used by the KeyboardFocusTraverser class as part of
  19614. its algorithm for deciding the order in which components should be traversed.
  19615. See the KeyboardFocusTraverser class for more details on this.
  19616. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  19617. */
  19618. int getExplicitFocusOrder() const;
  19619. /** Sets the index used in determining the order in which focusable components
  19620. should be traversed.
  19621. A value of 0 or less is taken to mean that no explicit order is wanted, and
  19622. that traversal should use other factors, like the component's position.
  19623. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  19624. */
  19625. void setExplicitFocusOrder (int newFocusOrderIndex);
  19626. /** Indicates whether this component is a parent for components that can have
  19627. their focus traversed.
  19628. This flag is used by the default implementation of the createFocusTraverser()
  19629. method, which uses the flag to find the first parent component (of the currently
  19630. focused one) which wants to be a focus container.
  19631. So using this method to set the flag to 'true' causes this component to
  19632. act as the top level within which focus is passed around.
  19633. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  19634. */
  19635. void setFocusContainer (bool shouldBeFocusContainer) throw();
  19636. /** Returns true if this component has been marked as a focus container.
  19637. See setFocusContainer() for more details.
  19638. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  19639. */
  19640. bool isFocusContainer() const throw();
  19641. /** Returns true if the component (and all its parents) are enabled.
  19642. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  19643. what difference this makes to the component depends on the type. E.g. buttons
  19644. and sliders will choose to draw themselves differently, etc.
  19645. Note that if one of this component's parents is disabled, this will always
  19646. return false, even if this component itself is enabled.
  19647. @see setEnabled, enablementChanged
  19648. */
  19649. bool isEnabled() const throw();
  19650. /** Enables or disables this component.
  19651. Disabling a component will also cause all of its child components to become
  19652. disabled.
  19653. Similarly, enabling a component which is inside a disabled parent
  19654. component won't make any difference until the parent is re-enabled.
  19655. @see isEnabled, enablementChanged
  19656. */
  19657. void setEnabled (bool shouldBeEnabled);
  19658. /** Callback to indicate that this component has been enabled or disabled.
  19659. This can be triggered by one of the component's parent components
  19660. being enabled or disabled, as well as changes to the component itself.
  19661. The default implementation of this method does nothing; your class may
  19662. wish to repaint itself or something when this happens.
  19663. @see setEnabled, isEnabled
  19664. */
  19665. virtual void enablementChanged();
  19666. /** Changes the mouse cursor shape to use when the mouse is over this component.
  19667. Note that the cursor set by this method can be overridden by the getMouseCursor
  19668. method.
  19669. @see MouseCursor
  19670. */
  19671. void setMouseCursor (const MouseCursor& cursorType);
  19672. /** Returns the mouse cursor shape to use when the mouse is over this component.
  19673. The default implementation will return the cursor that was set by setCursor()
  19674. but can be overridden for more specialised purposes, e.g. returning different
  19675. cursors depending on the mouse position.
  19676. @see MouseCursor
  19677. */
  19678. virtual const MouseCursor getMouseCursor();
  19679. /** Forces the current mouse cursor to be updated.
  19680. If you're overriding the getMouseCursor() method to control which cursor is
  19681. displayed, then this will only be checked each time the user moves the mouse. So
  19682. if you want to force the system to check that the cursor being displayed is
  19683. up-to-date (even if the mouse is just sitting there), call this method.
  19684. This isn't needed if you're only using setMouseCursor().
  19685. */
  19686. void updateMouseCursor() const;
  19687. /** Components can override this method to draw their content.
  19688. The paint() method gets called when a region of a component needs redrawing,
  19689. either because the component's repaint() method has been called, or because
  19690. something has happened on the screen that means a section of a window needs
  19691. to be redrawn.
  19692. Any child components will draw themselves over whatever this method draws. If
  19693. you need to paint over the top of your child components, you can also implement
  19694. the paintOverChildren() method to do this.
  19695. If you want to cause a component to redraw itself, this is done asynchronously -
  19696. calling the repaint() method marks a region of the component as "dirty", and the
  19697. paint() method will automatically be called sometime later, by the message thread,
  19698. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  19699. you never redraw something synchronously.
  19700. You should never need to call this method directly - to take a snapshot of the
  19701. component you could use createComponentSnapshot() or paintEntireComponent().
  19702. @param g the graphics context that must be used to do the drawing operations.
  19703. @see repaint, paintOverChildren, Graphics
  19704. */
  19705. virtual void paint (Graphics& g);
  19706. /** Components can override this method to draw over the top of their children.
  19707. For most drawing operations, it's better to use the normal paint() method,
  19708. but if you need to overlay something on top of the children, this can be
  19709. used.
  19710. @see paint, Graphics
  19711. */
  19712. virtual void paintOverChildren (Graphics& g);
  19713. /** Called when the mouse moves inside this component.
  19714. If the mouse button isn't pressed and the mouse moves over a component,
  19715. this will be called to let the component react to this.
  19716. A component will always get a mouseEnter callback before a mouseMove.
  19717. @param e details about the position and status of the mouse event
  19718. @see mouseEnter, mouseExit, mouseDrag, contains
  19719. */
  19720. virtual void mouseMove (const MouseEvent& e);
  19721. /** Called when the mouse first enters this component.
  19722. If the mouse button isn't pressed and the mouse moves into a component,
  19723. this will be called to let the component react to this.
  19724. When the mouse button is pressed and held down while being moved in
  19725. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  19726. mouseDrag messages are sent to the component that the mouse was originally
  19727. clicked on, until the button is released.
  19728. If you're writing a component that needs to repaint itself when the mouse
  19729. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  19730. method.
  19731. @param e details about the position and status of the mouse event
  19732. @see mouseExit, mouseDrag, mouseMove, contains
  19733. */
  19734. virtual void mouseEnter (const MouseEvent& e);
  19735. /** Called when the mouse moves out of this component.
  19736. This will be called when the mouse moves off the edge of this
  19737. component.
  19738. If the mouse button was pressed, and it was then dragged off the
  19739. edge of the component and released, then this callback will happen
  19740. when the button is released, after the mouseUp callback.
  19741. If you're writing a component that needs to repaint itself when the mouse
  19742. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  19743. method.
  19744. @param e details about the position and status of the mouse event
  19745. @see mouseEnter, mouseDrag, mouseMove, contains
  19746. */
  19747. virtual void mouseExit (const MouseEvent& e);
  19748. /** Called when a mouse button is pressed while it's over this component.
  19749. The MouseEvent object passed in contains lots of methods for finding out
  19750. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  19751. were held down at the time.
  19752. Once a button is held down, the mouseDrag method will be called when the
  19753. mouse moves, until the button is released.
  19754. @param e details about the position and status of the mouse event
  19755. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  19756. */
  19757. virtual void mouseDown (const MouseEvent& e);
  19758. /** Called when the mouse is moved while a button is held down.
  19759. When a mouse button is pressed inside a component, that component
  19760. receives mouseDrag callbacks each time the mouse moves, even if the
  19761. mouse strays outside the component's bounds.
  19762. If you want to be able to drag things off the edge of a component
  19763. and have the component scroll when you get to the edges, the
  19764. beginDragAutoRepeat() method might be useful.
  19765. @param e details about the position and status of the mouse event
  19766. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  19767. */
  19768. virtual void mouseDrag (const MouseEvent& e);
  19769. /** Called when a mouse button is released.
  19770. A mouseUp callback is sent to the component in which a button was pressed
  19771. even if the mouse is actually over a different component when the
  19772. button is released.
  19773. The MouseEvent object passed in contains lots of methods for finding out
  19774. which buttons were down just before they were released.
  19775. @param e details about the position and status of the mouse event
  19776. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  19777. */
  19778. virtual void mouseUp (const MouseEvent& e);
  19779. /** Called when a mouse button has been double-clicked in this component.
  19780. The MouseEvent object passed in contains lots of methods for finding out
  19781. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  19782. were held down at the time.
  19783. For altering the time limit used to detect double-clicks,
  19784. see MouseEvent::setDoubleClickTimeout.
  19785. @param e details about the position and status of the mouse event
  19786. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  19787. MouseEvent::getDoubleClickTimeout
  19788. */
  19789. virtual void mouseDoubleClick (const MouseEvent& e);
  19790. /** Called when the mouse-wheel is moved.
  19791. This callback is sent to the component that the mouse is over when the
  19792. wheel is moved.
  19793. If not overridden, the component will forward this message to its parent, so
  19794. that parent components can collect mouse-wheel messages that happen to
  19795. child components which aren't interested in them.
  19796. @param e details about the position and status of the mouse event
  19797. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  19798. value means the wheel has been pushed to the right, negative means it
  19799. was pushed to the left
  19800. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  19801. value means the wheel has been pushed upwards, negative means it
  19802. was pushed downwards
  19803. */
  19804. virtual void mouseWheelMove (const MouseEvent& e,
  19805. float wheelIncrementX,
  19806. float wheelIncrementY);
  19807. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  19808. next mouse-drag operation.
  19809. This allows you to make sure that mouseDrag() events sent continuously, even
  19810. when the mouse isn't moving. This can be useful for things like auto-scrolling
  19811. components when the mouse is near an edge.
  19812. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  19813. minimum interval between consecutive mouse drag callbacks. The callbacks
  19814. will continue until the mouse is released, and then the interval will be reset,
  19815. so you need to make sure it's called every time you begin a drag event. If it
  19816. is called when the mouse isn't actually being pressed, it will apply to the next
  19817. mouse-drag operation that happens.
  19818. Passing an interval of 0 or less will cancel the auto-repeat.
  19819. @see mouseDrag
  19820. */
  19821. static void beginDragAutoRepeat (int millisecondIntervalBetweenCallbacks);
  19822. /** Causes automatic repaints when the mouse enters or exits this component.
  19823. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  19824. on the component, it will trigger a repaint.
  19825. This is handy for things like buttons that need to draw themselves differently when
  19826. the mouse moves over them, and it avoids having to override all the different mouse
  19827. callbacks and call repaint().
  19828. @see mouseEnter, mouseExit, mouseDown, mouseUp
  19829. */
  19830. void setRepaintsOnMouseActivity (bool shouldRepaint) throw();
  19831. /** Registers a listener to be told when mouse events occur in this component.
  19832. If you need to get informed about mouse events in a component but can't or
  19833. don't want to override its methods, you can attach any number of listeners
  19834. to the component, and these will get told about the events in addition to
  19835. the component's own callbacks being called.
  19836. Note that a MouseListener can also be attached to more than one component.
  19837. @param newListener the listener to register
  19838. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  19839. for events that happen to any child component
  19840. within this component, including deeply-nested
  19841. child components. If false, it will only be
  19842. told about events that this component handles.
  19843. @see MouseListener, removeMouseListener
  19844. */
  19845. void addMouseListener (MouseListener* newListener,
  19846. bool wantsEventsForAllNestedChildComponents);
  19847. /** Deregisters a mouse listener.
  19848. @see addMouseListener, MouseListener
  19849. */
  19850. void removeMouseListener (MouseListener* listenerToRemove);
  19851. /** Adds a listener that wants to hear about keypresses that this component receives.
  19852. The listeners that are registered with a component are called by its keyPressed() or
  19853. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  19854. If you add an object as a key listener, be careful to remove it when the object
  19855. is deleted, or the component will be left with a dangling pointer.
  19856. @see keyPressed, keyStateChanged, removeKeyListener
  19857. */
  19858. void addKeyListener (KeyListener* newListener);
  19859. /** Removes a previously-registered key listener.
  19860. @see addKeyListener
  19861. */
  19862. void removeKeyListener (KeyListener* listenerToRemove);
  19863. /** Called when a key is pressed.
  19864. When a key is pressed, the component that has the keyboard focus will have this
  19865. method called. Remember that a component will only be given the focus if its
  19866. setWantsKeyboardFocus() method has been used to enable this.
  19867. If your implementation returns true, the event will be consumed and not passed
  19868. on to any other listeners. If it returns false, the key will be passed to any
  19869. KeyListeners that have been registered with this component. As soon as one of these
  19870. returns true, the process will stop, but if they all return false, the event will
  19871. be passed upwards to this component's parent, and so on.
  19872. The default implementation of this method does nothing and returns false.
  19873. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  19874. */
  19875. virtual bool keyPressed (const KeyPress& key);
  19876. /** Called when a key is pressed or released.
  19877. Whenever a key on the keyboard is pressed or released (including modifier keys
  19878. like shift and ctrl), this method will be called on the component that currently
  19879. has the keyboard focus. Remember that a component will only be given the focus if
  19880. its setWantsKeyboardFocus() method has been used to enable this.
  19881. If your implementation returns true, the event will be consumed and not passed
  19882. on to any other listeners. If it returns false, then any KeyListeners that have
  19883. been registered with this component will have their keyStateChanged methods called.
  19884. As soon as one of these returns true, the process will stop, but if they all return
  19885. false, the event will be passed upwards to this component's parent, and so on.
  19886. The default implementation of this method does nothing and returns false.
  19887. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  19888. method.
  19889. @param isKeyDown true if a key has been pressed; false if it has been released
  19890. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  19891. */
  19892. virtual bool keyStateChanged (bool isKeyDown);
  19893. /** Called when a modifier key is pressed or released.
  19894. Whenever the shift, control, alt or command keys are pressed or released,
  19895. this method will be called on the component that currently has the keyboard focus.
  19896. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  19897. method has been used to enable this.
  19898. The default implementation of this method actually calls its parent's modifierKeysChanged
  19899. method, so that focused components which aren't interested in this will give their
  19900. parents a chance to act on the event instead.
  19901. @see keyStateChanged, ModifierKeys
  19902. */
  19903. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  19904. /** Enumeration used by the focusChanged() and focusLost() methods. */
  19905. enum FocusChangeType
  19906. {
  19907. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  19908. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  19909. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  19910. };
  19911. /** Called to indicate that this component has just acquired the keyboard focus.
  19912. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  19913. */
  19914. virtual void focusGained (FocusChangeType cause);
  19915. /** Called to indicate that this component has just lost the keyboard focus.
  19916. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  19917. */
  19918. virtual void focusLost (FocusChangeType cause);
  19919. /** Called to indicate that one of this component's children has been focused or unfocused.
  19920. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  19921. changed. It happens when focus moves from one of this component's children (at any depth)
  19922. to a component that isn't contained in this one, (or vice-versa).
  19923. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  19924. */
  19925. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  19926. /** Returns true if the mouse is currently over this component.
  19927. If the mouse isn't over the component, this will return false, even if the
  19928. mouse is currently being dragged - so you can use this in your mouseDrag
  19929. method to find out whether it's really over the component or not.
  19930. Note that when the mouse button is being held down, then the only component
  19931. for which this method will return true is the one that was originally
  19932. clicked on.
  19933. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  19934. */
  19935. bool isMouseOver() const throw();
  19936. /** Returns true if the mouse button is currently held down in this component.
  19937. Note that this is a test to see whether the mouse is being pressed in this
  19938. component, so it'll return false if called on component A when the mouse
  19939. is actually being dragged in component B.
  19940. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  19941. */
  19942. bool isMouseButtonDown() const throw();
  19943. /** True if the mouse is over this component, or if it's being dragged in this component.
  19944. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  19945. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  19946. */
  19947. bool isMouseOverOrDragging() const throw();
  19948. /** Returns true if a mouse button is currently down.
  19949. Unlike isMouseButtonDown, this will test the current state of the
  19950. buttons without regard to which component (if any) it has been
  19951. pressed in.
  19952. @see isMouseButtonDown, ModifierKeys
  19953. */
  19954. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  19955. /** Returns the mouse's current position, relative to this component.
  19956. The co-ordinates are relative to the component's top-left corner.
  19957. */
  19958. const Point<int> getMouseXYRelative() const;
  19959. /** Called when this component's size has been changed.
  19960. A component can implement this method to do things such as laying out its
  19961. child components when its width or height changes.
  19962. The method is called synchronously as a result of the setBounds or setSize
  19963. methods, so repeatedly changing a components size will repeatedly call its
  19964. resized method (unlike things like repainting, where multiple calls to repaint
  19965. are coalesced together).
  19966. If the component is a top-level window on the desktop, its size could also
  19967. be changed by operating-system factors beyond the application's control.
  19968. @see moved, setSize
  19969. */
  19970. virtual void resized();
  19971. /** Called when this component's position has been changed.
  19972. This is called when the position relative to its parent changes, not when
  19973. its absolute position on the screen changes (so it won't be called for
  19974. all child components when a parent component is moved).
  19975. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  19976. or any of the other repositioning methods, and like resized(), it will be
  19977. called each time those methods are called.
  19978. If the component is a top-level window on the desktop, its position could also
  19979. be changed by operating-system factors beyond the application's control.
  19980. @see resized, setBounds
  19981. */
  19982. virtual void moved();
  19983. /** Called when one of this component's children is moved or resized.
  19984. If the parent wants to know about changes to its immediate children (not
  19985. to children of its children), this is the method to override.
  19986. @see moved, resized, parentSizeChanged
  19987. */
  19988. virtual void childBoundsChanged (Component* child);
  19989. /** Called when this component's immediate parent has been resized.
  19990. If the component is a top-level window, this indicates that the screen size
  19991. has changed.
  19992. @see childBoundsChanged, moved, resized
  19993. */
  19994. virtual void parentSizeChanged();
  19995. /** Called when this component has been moved to the front of its siblings.
  19996. The component may have been brought to the front by the toFront() method, or
  19997. by the operating system if it's a top-level window.
  19998. @see toFront
  19999. */
  20000. virtual void broughtToFront();
  20001. /** Adds a listener to be told about changes to the component hierarchy or position.
  20002. Component listeners get called when this component's size, position or children
  20003. change - see the ComponentListener class for more details.
  20004. @param newListener the listener to register - if this is already registered, it
  20005. will be ignored.
  20006. @see ComponentListener, removeComponentListener
  20007. */
  20008. void addComponentListener (ComponentListener* newListener);
  20009. /** Removes a component listener.
  20010. @see addComponentListener
  20011. */
  20012. void removeComponentListener (ComponentListener* listenerToRemove);
  20013. /** Dispatches a numbered message to this component.
  20014. This is a quick and cheap way of allowing simple asynchronous messages to
  20015. be sent to components. It's also safe, because if the component that you
  20016. send the message to is a null or dangling pointer, this won't cause an error.
  20017. The command ID is later delivered to the component's handleCommandMessage() method by
  20018. the application's message queue.
  20019. @see handleCommandMessage
  20020. */
  20021. void postCommandMessage (int commandId);
  20022. /** Called to handle a command that was sent by postCommandMessage().
  20023. This is called by the message thread when a command message arrives, and
  20024. the component can override this method to process it in any way it needs to.
  20025. @see postCommandMessage
  20026. */
  20027. virtual void handleCommandMessage (int commandId);
  20028. /** Runs a component modally, waiting until the loop terminates.
  20029. This method first makes the component visible, brings it to the front and
  20030. gives it the keyboard focus.
  20031. It then runs a loop, dispatching messages from the system message queue, but
  20032. blocking all mouse or keyboard messages from reaching any components other
  20033. than this one and its children.
  20034. This loop continues until the component's exitModalState() method is called (or
  20035. the component is deleted), and then this method returns, returning the value
  20036. passed into exitModalState().
  20037. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  20038. isCurrentlyBlockedByAnotherModalComponent, MessageManager::dispatchNextMessage
  20039. */
  20040. int runModalLoop();
  20041. /** Puts the component into a modal state.
  20042. This makes the component modal, so that messages are blocked from reaching
  20043. any components other than this one and its children, but unlike runModalLoop(),
  20044. this method returns immediately.
  20045. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  20046. get the focus, which is usually what you'll want it to do. If not, it will leave
  20047. the focus unchanged.
  20048. @see exitModalState, runModalLoop
  20049. */
  20050. void enterModalState (bool takeKeyboardFocus = true);
  20051. /** Ends a component's modal state.
  20052. If this component is currently modal, this will turn of its modalness, and return
  20053. a value to the runModalLoop() method that might have be running its modal loop.
  20054. @see runModalLoop, enterModalState, isCurrentlyModal
  20055. */
  20056. void exitModalState (int returnValue);
  20057. /** Returns true if this component is the modal one.
  20058. It's possible to have nested modal components, e.g. a pop-up dialog box
  20059. that launches another pop-up, but this will only return true for
  20060. the one at the top of the stack.
  20061. @see getCurrentlyModalComponent
  20062. */
  20063. bool isCurrentlyModal() const throw();
  20064. /** Returns the number of components that are currently in a modal state.
  20065. @see getCurrentlyModalComponent
  20066. */
  20067. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() throw();
  20068. /** Returns one of the components that are currently modal.
  20069. The index specifies which of the possible modal components to return. The order
  20070. of the components in this list is the reverse of the order in which they became
  20071. modal - so the component at index 0 is always the active component, and the others
  20072. are progressively earlier ones that are themselves now blocked by later ones.
  20073. @returns the modal component, or null if no components are modal (or if the
  20074. index is out of range)
  20075. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  20076. */
  20077. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) throw();
  20078. /** Checks whether there's a modal component somewhere that's stopping this one
  20079. from receiving messages.
  20080. If there is a modal component, its canModalEventBeSentToComponent() method
  20081. will be called to see if it will still allow this component to receive events.
  20082. @see runModalLoop, getCurrentlyModalComponent
  20083. */
  20084. bool isCurrentlyBlockedByAnotherModalComponent() const;
  20085. /** When a component is modal, this callback allows it to choose which other
  20086. components can still receive events.
  20087. When a modal component is active and the user clicks on a non-modal component,
  20088. this method is called on the modal component, and if it returns true, the
  20089. event is allowed to reach its target. If it returns false, the event is blocked
  20090. and the inputAttemptWhenModal() callback is made.
  20091. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  20092. implementation just returns false in all cases.
  20093. */
  20094. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  20095. /** Called when the user tries to click on a component that is blocked by another
  20096. modal component.
  20097. When a component is modal and the user clicks on one of the other components,
  20098. the modal component will receive this callback.
  20099. The default implementation of this method will play a beep, and bring the currently
  20100. modal component to the front, but it can be overridden to do other tasks.
  20101. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  20102. */
  20103. virtual void inputAttemptWhenModal();
  20104. /** Returns the set of properties that belong to this component.
  20105. Each component has a NamedValueSet object which you can use to attach arbitrary
  20106. items of data to it.
  20107. */
  20108. NamedValueSet& getProperties() throw() { return properties; }
  20109. /** Returns the set of properties that belong to this component.
  20110. Each component has a NamedValueSet object which you can use to attach arbitrary
  20111. items of data to it.
  20112. */
  20113. const NamedValueSet& getProperties() const throw() { return properties; }
  20114. /** Looks for a colour that has been registered with the given colour ID number.
  20115. If a colour has been set for this ID number using setColour(), then it is
  20116. returned. If none has been set, the method will try calling the component's
  20117. LookAndFeel class's findColour() method. If none has been registered with the
  20118. look-and-feel either, it will just return black.
  20119. The colour IDs for various purposes are stored as enums in the components that
  20120. they are relevent to - for an example, see Slider::ColourIds,
  20121. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  20122. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  20123. */
  20124. const Colour findColour (int colourId, bool inheritFromParent = false) const;
  20125. /** Registers a colour to be used for a particular purpose.
  20126. Changing a colour will cause a synchronous callback to the colourChanged()
  20127. method, which your component can override if it needs to do something when
  20128. colours are altered.
  20129. For more details about colour IDs, see the comments for findColour().
  20130. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  20131. */
  20132. void setColour (int colourId, const Colour& colour);
  20133. /** If a colour has been set with setColour(), this will remove it.
  20134. This allows you to make a colour revert to its default state.
  20135. */
  20136. void removeColour (int colourId);
  20137. /** Returns true if the specified colour ID has been explicitly set for this
  20138. component using the setColour() method.
  20139. */
  20140. bool isColourSpecified (int colourId) const;
  20141. /** This looks for any colours that have been specified for this component,
  20142. and copies them to the specified target component.
  20143. */
  20144. void copyAllExplicitColoursTo (Component& target) const;
  20145. /** This method is called when a colour is changed by the setColour() method.
  20146. @see setColour, findColour
  20147. */
  20148. virtual void colourChanged();
  20149. /** Returns the underlying native window handle for this component.
  20150. This is platform-dependent and strictly for power-users only!
  20151. */
  20152. void* getWindowHandle() const;
  20153. /** When created, each component is given a number to uniquely identify it.
  20154. The number is incremented each time a new component is created, so it's a more
  20155. unique way of identifying a component than using its memory location (which
  20156. may be reused after the component is deleted, of course).
  20157. */
  20158. uint32 getComponentUID() const throw() { return componentUID; }
  20159. /** Holds a pointer to some type of Component, which automatically becomes null if
  20160. the component is deleted.
  20161. If you're using a component which may be deleted by another event that's outside
  20162. of your control, use a SafePointer instead of a normal pointer to refer to it,
  20163. and you can test whether it's null before using it to see if something has deleted
  20164. it.
  20165. The ComponentType typedef must be Component, or some subclass of Component.
  20166. Note that this class isn't thread-safe, and assumes that all the code that uses
  20167. it is running on the message thread.
  20168. */
  20169. template <class ComponentType>
  20170. class SafePointer : private ComponentListener
  20171. {
  20172. public:
  20173. /** Creates a null SafePointer. */
  20174. SafePointer() : comp (0) {}
  20175. /** Creates a SafePointer that points at the given component. */
  20176. SafePointer (ComponentType* const component) : comp (component) { attach(); }
  20177. /** Creates a copy of another SafePointer. */
  20178. SafePointer (const SafePointer& other) : comp (other.comp) { attach(); }
  20179. /** Destructor. */
  20180. ~SafePointer() { detach(); }
  20181. /** Copies another pointer to this one. */
  20182. SafePointer& operator= (const SafePointer& other) { return operator= (other.comp); }
  20183. /** Copies another pointer to this one. */
  20184. SafePointer& operator= (ComponentType* const newComponent)
  20185. {
  20186. detach();
  20187. comp = newComponent;
  20188. attach();
  20189. return *this;
  20190. }
  20191. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20192. operator ComponentType*() const throw() { return comp; }
  20193. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20194. ComponentType* getComponent() const throw() { return comp; }
  20195. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20196. ComponentType* operator->() throw() { jassert (comp != 0); return comp; }
  20197. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20198. const ComponentType* operator->() const throw() { jassert (comp != 0); return comp; }
  20199. juce_UseDebuggingNewOperator
  20200. private:
  20201. ComponentType* comp;
  20202. void attach() { if (comp != 0) comp->addComponentListener (this); }
  20203. void detach() { if (comp != 0) comp->removeComponentListener (this); }
  20204. void componentBeingDeleted (Component&) { comp = 0; }
  20205. };
  20206. /** A class to keep an eye on one or two components and check for them being deleted.
  20207. This is designed for use with the ListenerList::callChecked() methods, to allow
  20208. the list iterator to stop cleanly if the component is deleted by a listener callback
  20209. while the list is still being iterated.
  20210. */
  20211. class BailOutChecker
  20212. {
  20213. public:
  20214. /** Creates a checker that watches either one or two components.
  20215. component1 must be a valid component; component2 can be null if you only need
  20216. to check on one component.
  20217. */
  20218. BailOutChecker (Component* component1,
  20219. Component* component2 = 0);
  20220. /** Returns true if either of the two components have been deleted since this
  20221. object was created. */
  20222. bool shouldBailOut() const throw();
  20223. private:
  20224. typedef SafePointer<Component> SafeComponentPtr;
  20225. SafeComponentPtr safePointer1, safePointer2;
  20226. Component* const component2;
  20227. BailOutChecker (const BailOutChecker&);
  20228. BailOutChecker& operator= (const BailOutChecker&);
  20229. };
  20230. juce_UseDebuggingNewOperator
  20231. private:
  20232. friend class ComponentPeer;
  20233. friend class InternalDragRepeater;
  20234. friend class MouseInputSource;
  20235. friend class MouseInputSourceInternal;
  20236. static Component* currentlyFocusedComponent;
  20237. String componentName_;
  20238. Component* parentComponent_;
  20239. uint32 componentUID;
  20240. Rectangle<int> bounds_;
  20241. int numDeepMouseListeners;
  20242. Array <Component*> childComponentList_;
  20243. LookAndFeel* lookAndFeel_;
  20244. MouseCursor cursor_;
  20245. ImageEffectFilter* effect_;
  20246. Image bufferedImage_;
  20247. Array <MouseListener*>* mouseListeners_;
  20248. Array <KeyListener*>* keyListeners_;
  20249. ListenerList <ComponentListener> componentListeners;
  20250. NamedValueSet properties;
  20251. struct ComponentFlags
  20252. {
  20253. bool hasHeavyweightPeerFlag : 1;
  20254. bool visibleFlag : 1;
  20255. bool opaqueFlag : 1;
  20256. bool ignoresMouseClicksFlag : 1;
  20257. bool allowChildMouseClicksFlag : 1;
  20258. bool wantsFocusFlag : 1;
  20259. bool isFocusContainerFlag : 1;
  20260. bool dontFocusOnMouseClickFlag : 1;
  20261. bool alwaysOnTopFlag : 1;
  20262. bool bufferToImageFlag : 1;
  20263. bool bringToFrontOnClickFlag : 1;
  20264. bool repaintOnMouseActivityFlag : 1;
  20265. bool draggingFlag : 1;
  20266. bool mouseOverFlag : 1;
  20267. bool mouseInsideFlag : 1;
  20268. bool currentlyModalFlag : 1;
  20269. bool isDisabledFlag : 1;
  20270. bool childCompFocusedFlag : 1;
  20271. #if JUCE_DEBUG
  20272. bool isInsidePaintCall : 1;
  20273. #endif
  20274. };
  20275. union
  20276. {
  20277. uint32 componentFlags_;
  20278. ComponentFlags flags;
  20279. };
  20280. void internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20281. void internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20282. void internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20283. void internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers);
  20284. void internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20285. void internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20286. void internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos, const Time& time, float amountX, float amountY);
  20287. void internalBroughtToFront();
  20288. void internalFocusGain (const FocusChangeType cause);
  20289. void internalFocusLoss (const FocusChangeType cause);
  20290. void internalChildFocusChange (FocusChangeType cause);
  20291. void internalModalInputAttempt();
  20292. void internalModifierKeysChanged();
  20293. void internalChildrenChanged();
  20294. void internalHierarchyChanged();
  20295. void renderComponent (Graphics& context);
  20296. void sendMovedResizedMessages (bool wasMoved, bool wasResized);
  20297. void repaintParent();
  20298. void sendFakeMouseMove() const;
  20299. void takeKeyboardFocus (const FocusChangeType cause);
  20300. void grabFocusInternal (const FocusChangeType cause, bool canTryParent = true);
  20301. static void giveAwayFocus();
  20302. void sendEnablementChangeMessage();
  20303. static void* runModalLoopCallback (void*);
  20304. static void bringModalComponentToFront();
  20305. void subtractObscuredRegions (RectangleList& result, const Point<int>& delta,
  20306. const Rectangle<int>& clipRect,
  20307. const Component* const compToAvoid) const;
  20308. void clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  20309. int deltaX, int deltaY) const;
  20310. // how much of the component is not off the edges of its parents
  20311. const Rectangle<int> getUnclippedArea() const;
  20312. void sendVisibilityChangeMessage();
  20313. // This is included here just to cause a compile error if your code is still handling
  20314. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  20315. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  20316. // implement its methods instead of this Component method).
  20317. virtual void filesDropped (const StringArray&, int, int) {}
  20318. // components aren't allowed to have copy constructors, as this would mess up parent
  20319. // hierarchies. You might need to give your subclasses a private dummy constructor like
  20320. // this one to avoid compiler warnings.
  20321. Component (const Component&);
  20322. Component& operator= (const Component&);
  20323. protected:
  20324. /** @internal */
  20325. virtual void internalRepaint (int x, int y, int w, int h);
  20326. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  20327. /** Overridden from the MessageListener parent class.
  20328. You can override this if you really need to, but be sure to pass your unwanted messages up
  20329. to this base class implementation, as the Component class needs to send itself messages
  20330. to work properly.
  20331. */
  20332. void handleMessage (const Message&);
  20333. };
  20334. #endif // __JUCE_COMPONENT_JUCEHEADER__
  20335. /*** End of inlined file: juce_Component.h ***/
  20336. /*** Start of inlined file: juce_ApplicationCommandInfo.h ***/
  20337. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20338. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20339. /*** Start of inlined file: juce_ApplicationCommandID.h ***/
  20340. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20341. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20342. /** A type used to hold the unique ID for an application command.
  20343. This is a numeric type, so it can be stored as an integer.
  20344. @see ApplicationCommandInfo, ApplicationCommandManager,
  20345. ApplicationCommandTarget, KeyPressMappingSet
  20346. */
  20347. typedef int CommandID;
  20348. /** A set of general-purpose application command IDs.
  20349. Because these commands are likely to be used in most apps, they're defined
  20350. here to help different apps to use the same numeric values for them.
  20351. Of course you don't have to use these, but some of them are used internally by
  20352. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  20353. @see ApplicationCommandInfo, ApplicationCommandManager,
  20354. ApplicationCommandTarget, KeyPressMappingSet
  20355. */
  20356. namespace StandardApplicationCommandIDs
  20357. {
  20358. /** This command ID should be used to send a "Quit the App" command.
  20359. This command is recognised by the JUCEApplication class, so if it is invoked
  20360. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  20361. object will catch it and call JUCEApplication::systemRequestedQuit().
  20362. */
  20363. static const CommandID quit = 0x1001;
  20364. /** The command ID that should be used to send a "Delete" command. */
  20365. static const CommandID del = 0x1002;
  20366. /** The command ID that should be used to send a "Cut" command. */
  20367. static const CommandID cut = 0x1003;
  20368. /** The command ID that should be used to send a "Copy to clipboard" command. */
  20369. static const CommandID copy = 0x1004;
  20370. /** The command ID that should be used to send a "Paste from clipboard" command. */
  20371. static const CommandID paste = 0x1005;
  20372. /** The command ID that should be used to send a "Select all" command. */
  20373. static const CommandID selectAll = 0x1006;
  20374. /** The command ID that should be used to send a "Deselect all" command. */
  20375. static const CommandID deselectAll = 0x1007;
  20376. }
  20377. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20378. /*** End of inlined file: juce_ApplicationCommandID.h ***/
  20379. /**
  20380. Holds information describing an application command.
  20381. This object is used to pass information about a particular command, such as its
  20382. name, description and other usage flags.
  20383. When an ApplicationCommandTarget is asked to provide information about the commands
  20384. it can perform, this is the structure gets filled-in to describe each one.
  20385. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  20386. ApplicationCommandManager
  20387. */
  20388. struct JUCE_API ApplicationCommandInfo
  20389. {
  20390. explicit ApplicationCommandInfo (CommandID commandID) throw();
  20391. /** Sets a number of the structures values at once.
  20392. The meanings of each of the parameters is described below, in the appropriate
  20393. member variable's description.
  20394. */
  20395. void setInfo (const String& shortName,
  20396. const String& description,
  20397. const String& categoryName,
  20398. int flags) throw();
  20399. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  20400. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  20401. is false, the bit is set.
  20402. */
  20403. void setActive (bool isActive) throw();
  20404. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  20405. */
  20406. void setTicked (bool isTicked) throw();
  20407. /** Handy method for adding a keypress to the defaultKeypresses array.
  20408. This is just so you can write things like:
  20409. @code
  20410. myinfo.addDefaultKeypress ('s', ModifierKeys::commandModifier);
  20411. @endcode
  20412. instead of
  20413. @code
  20414. myinfo.defaultKeypresses.add (KeyPress ('s', ModifierKeys::commandModifier));
  20415. @endcode
  20416. */
  20417. void addDefaultKeypress (int keyCode,
  20418. const ModifierKeys& modifiers) throw();
  20419. /** The command's unique ID number.
  20420. */
  20421. CommandID commandID;
  20422. /** A short name to describe the command.
  20423. This should be suitable for use in menus, on buttons that trigger the command, etc.
  20424. You can use the setInfo() method to quickly set this and some of the command's
  20425. other properties.
  20426. */
  20427. String shortName;
  20428. /** A longer description of the command.
  20429. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  20430. pop-up tooltip describing what the command does.
  20431. You can use the setInfo() method to quickly set this and some of the command's
  20432. other properties.
  20433. */
  20434. String description;
  20435. /** A named category that the command fits into.
  20436. You can give your commands any category you like, and these will be displayed in
  20437. contexts such as the KeyMappingEditorComponent, where the category is used to group
  20438. commands together.
  20439. You can use the setInfo() method to quickly set this and some of the command's
  20440. other properties.
  20441. */
  20442. String categoryName;
  20443. /** A list of zero or more keypresses that should be used as the default keys for
  20444. this command.
  20445. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  20446. this list to initialise the default set of key-to-command mappings.
  20447. @see addDefaultKeypress
  20448. */
  20449. Array <KeyPress> defaultKeypresses;
  20450. /** Flags describing the ways in which this command should be used.
  20451. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  20452. variable.
  20453. */
  20454. enum CommandFlags
  20455. {
  20456. /** Indicates that the command can't currently be performed.
  20457. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  20458. not currently permissable to perform the command. If the flag is set, then
  20459. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  20460. command or show themselves as not being enabled.
  20461. @see ApplicationCommandInfo::setActive
  20462. */
  20463. isDisabled = 1 << 0,
  20464. /** Indicates that the command should have a tick next to it on a menu.
  20465. If your command is shown on a menu and this is set, it'll show a tick next to
  20466. it. Other components such as buttons may also use this flag to indicate that it
  20467. is a value that can be toggled, and is currently in the 'on' state.
  20468. @see ApplicationCommandInfo::setTicked
  20469. */
  20470. isTicked = 1 << 1,
  20471. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  20472. it will call the command twice, once on key-down and again on key-up.
  20473. @see ApplicationCommandTarget::InvocationInfo
  20474. */
  20475. wantsKeyUpDownCallbacks = 1 << 2,
  20476. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  20477. command in its list.
  20478. */
  20479. hiddenFromKeyEditor = 1 << 3,
  20480. /** If this flag is present, then a KeyMappingEditorComponent will display the
  20481. command in its list, but won't allow the assigned keypress to be changed.
  20482. */
  20483. readOnlyInKeyEditor = 1 << 4,
  20484. /** If this flag is present and the command is invoked from a keypress, then any
  20485. buttons or menus that are also connected to the command will not flash to
  20486. indicate that they've been triggered.
  20487. */
  20488. dontTriggerVisualFeedback = 1 << 5
  20489. };
  20490. /** A bitwise-OR of the values specified in the CommandFlags enum.
  20491. You can use the setInfo() method to quickly set this and some of the command's
  20492. other properties.
  20493. */
  20494. int flags;
  20495. };
  20496. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20497. /*** End of inlined file: juce_ApplicationCommandInfo.h ***/
  20498. /**
  20499. A command target publishes a list of command IDs that it can perform.
  20500. An ApplicationCommandManager despatches commands to targets, which must be
  20501. able to provide information about what commands they can handle.
  20502. To create a target, you'll need to inherit from this class, implementing all of
  20503. its pure virtual methods.
  20504. For info about how a target is chosen to receive a command, see
  20505. ApplicationCommandManager::getFirstCommandTarget().
  20506. @see ApplicationCommandManager, ApplicationCommandInfo
  20507. */
  20508. class JUCE_API ApplicationCommandTarget
  20509. {
  20510. public:
  20511. /** Creates a command target. */
  20512. ApplicationCommandTarget();
  20513. /** Destructor. */
  20514. virtual ~ApplicationCommandTarget();
  20515. /**
  20516. */
  20517. struct JUCE_API InvocationInfo
  20518. {
  20519. InvocationInfo (const CommandID commandID) throw();
  20520. /** The UID of the command that should be performed. */
  20521. CommandID commandID;
  20522. /** The command's flags.
  20523. See ApplicationCommandInfo for a description of these flag values.
  20524. */
  20525. int commandFlags;
  20526. /** The types of context in which the command might be called. */
  20527. enum InvocationMethod
  20528. {
  20529. direct = 0, /**< The command is being invoked directly by a piece of code. */
  20530. fromKeyPress, /**< The command is being invoked by a key-press. */
  20531. fromMenu, /**< The command is being invoked by a menu selection. */
  20532. fromButton /**< The command is being invoked by a button click. */
  20533. };
  20534. /** The type of event that triggered this command. */
  20535. InvocationMethod invocationMethod;
  20536. /** If triggered by a keypress or menu, this will be the component that had the
  20537. keyboard focus at the time.
  20538. If triggered by a button, it may be set to that component, or it may be null.
  20539. */
  20540. Component* originatingComponent;
  20541. /** The keypress that was used to invoke it.
  20542. Note that this will be an invalid keypress if the command was invoked
  20543. by some other means than a keyboard shortcut.
  20544. */
  20545. KeyPress keyPress;
  20546. /** True if the callback is being invoked when the key is pressed,
  20547. false if the key is being released.
  20548. @see KeyPressMappingSet::addCommand()
  20549. */
  20550. bool isKeyDown;
  20551. /** If the key is being released, this indicates how long it had been held
  20552. down for.
  20553. (Only relevant if isKeyDown is false.)
  20554. */
  20555. int millisecsSinceKeyPressed;
  20556. };
  20557. /** This must return the next target to try after this one.
  20558. When a command is being sent, and the first target can't handle
  20559. that command, this method is used to determine the next target that should
  20560. be tried.
  20561. It may return 0 if it doesn't know of another target.
  20562. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  20563. method to return a parent component that might want to handle it.
  20564. @see invoke
  20565. */
  20566. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  20567. /** This must return a complete list of commands that this target can handle.
  20568. Your target should add all the command IDs that it handles to the array that is
  20569. passed-in.
  20570. */
  20571. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  20572. /** This must provide details about one of the commands that this target can perform.
  20573. This will be called with one of the command IDs that the target provided in its
  20574. getAllCommands() methods.
  20575. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  20576. suitable information about the command. (The commandID field will already have been filled-in
  20577. by the caller).
  20578. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  20579. set all the fields at once.
  20580. If the command is currently inactive for some reason, this method must use
  20581. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  20582. bit of the ApplicationCommandInfo::flags field).
  20583. Any default key-presses for the command should be appended to the
  20584. ApplicationCommandInfo::defaultKeypresses field.
  20585. Note that if you change something that affects the status of the commands
  20586. that would be returned by this method (e.g. something that makes some commands
  20587. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  20588. to cause the manager to refresh its status.
  20589. */
  20590. virtual void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) = 0;
  20591. /** This must actually perform the specified command.
  20592. If this target is able to perform the command specified by the commandID field of the
  20593. InvocationInfo structure, then it should do so, and must return true.
  20594. If it can't handle this command, it should return false, which tells the caller to pass
  20595. the command on to the next target in line.
  20596. @see invoke, ApplicationCommandManager::invoke
  20597. */
  20598. virtual bool perform (const InvocationInfo& info) = 0;
  20599. /** Makes this target invoke a command.
  20600. Your code can call this method to invoke a command on this target, but normally
  20601. you'd call it indirectly via ApplicationCommandManager::invoke() or
  20602. ApplicationCommandManager::invokeDirectly().
  20603. If this target can perform the given command, it will call its perform() method to
  20604. do so. If not, then getNextCommandTarget() will be used to determine the next target
  20605. to try, and the command will be passed along to it.
  20606. @param invocationInfo this must be correctly filled-in, describing the context for
  20607. the invocation.
  20608. @param asynchronously if false, the command will be performed before this method returns.
  20609. If true, a message will be posted so that the command will be performed
  20610. later on the message thread, and this method will return immediately.
  20611. @see perform, ApplicationCommandManager::invoke
  20612. */
  20613. bool invoke (const InvocationInfo& invocationInfo,
  20614. const bool asynchronously);
  20615. /** Invokes a given command directly on this target.
  20616. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  20617. structure.
  20618. */
  20619. bool invokeDirectly (const CommandID commandID,
  20620. const bool asynchronously);
  20621. /** Searches this target and all subsequent ones for the first one that can handle
  20622. the specified command.
  20623. This will use getNextCommandTarget() to determine the chain of targets to try
  20624. after this one.
  20625. */
  20626. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  20627. /** Checks whether this command can currently be performed by this target.
  20628. This will return true only if a call to getCommandInfo() doesn't set the
  20629. isDisabled flag to indicate that the command is inactive.
  20630. */
  20631. bool isCommandActive (const CommandID commandID);
  20632. /** If this object is a Component, this method will seach upwards in its current
  20633. UI hierarchy for the next parent component that implements the
  20634. ApplicationCommandTarget class.
  20635. If your target is a Component, this is a very handy method to use in your
  20636. getNextCommandTarget() implementation.
  20637. */
  20638. ApplicationCommandTarget* findFirstTargetParentComponent();
  20639. juce_UseDebuggingNewOperator
  20640. private:
  20641. // (for async invocation of commands)
  20642. class CommandTargetMessageInvoker : public MessageListener
  20643. {
  20644. public:
  20645. CommandTargetMessageInvoker (ApplicationCommandTarget* const owner);
  20646. ~CommandTargetMessageInvoker();
  20647. void handleMessage (const Message& message);
  20648. private:
  20649. ApplicationCommandTarget* const owner;
  20650. CommandTargetMessageInvoker (const CommandTargetMessageInvoker&);
  20651. CommandTargetMessageInvoker& operator= (const CommandTargetMessageInvoker&);
  20652. };
  20653. ScopedPointer <CommandTargetMessageInvoker> messageInvoker;
  20654. friend class CommandTargetMessageInvoker;
  20655. bool tryToInvoke (const InvocationInfo& info, const bool async);
  20656. ApplicationCommandTarget (const ApplicationCommandTarget&);
  20657. ApplicationCommandTarget& operator= (const ApplicationCommandTarget&);
  20658. };
  20659. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  20660. /*** End of inlined file: juce_ApplicationCommandTarget.h ***/
  20661. /*** Start of inlined file: juce_ActionListener.h ***/
  20662. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  20663. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  20664. /**
  20665. Receives callbacks to indicate that some kind of event has occurred.
  20666. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  20667. about something that's happened.
  20668. @see ActionListenerList, ActionBroadcaster, ChangeListener
  20669. */
  20670. class JUCE_API ActionListener
  20671. {
  20672. public:
  20673. /** Destructor. */
  20674. virtual ~ActionListener() {}
  20675. /** Overridden by your subclass to receive the callback.
  20676. @param message the string that was specified when the event was triggered
  20677. by a call to ActionListenerList::sendActionMessage()
  20678. */
  20679. virtual void actionListenerCallback (const String& message) = 0;
  20680. };
  20681. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  20682. /*** End of inlined file: juce_ActionListener.h ***/
  20683. /**
  20684. An instance of this class is used to specify initialisation and shutdown
  20685. code for the application.
  20686. An application that wants to run in the JUCE framework needs to declare a
  20687. subclass of JUCEApplication and implement its various pure virtual methods.
  20688. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  20689. to declare an instance of this class and generate a suitable platform-specific
  20690. main() function.
  20691. e.g. @code
  20692. class MyJUCEApp : public JUCEApplication
  20693. {
  20694. // NEVER put objects inside a JUCEApplication class - only use pointers to
  20695. // objects, which you must create in the initialise() method.
  20696. MyApplicationWindow* myMainWindow;
  20697. public:
  20698. MyJUCEApp()
  20699. : myMainWindow (0)
  20700. {
  20701. // never create any Juce objects in the constructor - do all your initialisation
  20702. // in the initialise() method.
  20703. }
  20704. ~MyJUCEApp()
  20705. {
  20706. // all your shutdown code must have already been done in the shutdown() method -
  20707. // nothing should happen in this destructor.
  20708. }
  20709. void initialise (const String& commandLine)
  20710. {
  20711. myMainWindow = new MyApplicationWindow();
  20712. myMainWindow->setBounds (100, 100, 400, 500);
  20713. myMainWindow->setVisible (true);
  20714. }
  20715. void shutdown()
  20716. {
  20717. delete myMainWindow;
  20718. }
  20719. const String getApplicationName()
  20720. {
  20721. return "Super JUCE-o-matic";
  20722. }
  20723. const String getApplicationVersion()
  20724. {
  20725. return "1.0";
  20726. }
  20727. };
  20728. // this creates wrapper code to actually launch the app properly.
  20729. START_JUCE_APPLICATION (MyJUCEApp)
  20730. @endcode
  20731. Because this object will be created before Juce has properly initialised, you must
  20732. NEVER add any member variable objects that will be automatically constructed. Likewise
  20733. don't put ANY code in the constructor that could call Juce functions. Any objects that
  20734. you want to add to the class must be pointers, which you should instantiate during the
  20735. initialise() method, and delete in the shutdown() method.
  20736. @see MessageManager, DeletedAtShutdown
  20737. */
  20738. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  20739. private ActionListener
  20740. {
  20741. protected:
  20742. /** Constructs a JUCE app object.
  20743. If subclasses implement a constructor or destructor, they shouldn't call any
  20744. JUCE code in there - put your startup/shutdown code in initialise() and
  20745. shutdown() instead.
  20746. */
  20747. JUCEApplication();
  20748. public:
  20749. /** Destructor.
  20750. If subclasses implement a constructor or destructor, they shouldn't call any
  20751. JUCE code in there - put your startup/shutdown code in initialise() and
  20752. shutdown() instead.
  20753. */
  20754. virtual ~JUCEApplication();
  20755. /** Returns the global instance of the application object being run. */
  20756. static JUCEApplication* getInstance() throw();
  20757. /** Called when the application starts.
  20758. This will be called once to let the application do whatever initialisation
  20759. it needs, create its windows, etc.
  20760. After the method returns, the normal event-dispatch loop will be run,
  20761. until the quit() method is called, at which point the shutdown()
  20762. method will be called to let the application clear up anything it needs
  20763. to delete.
  20764. If during the initialise() method, the application decides not to start-up
  20765. after all, it can just call the quit() method and the event loop won't be run.
  20766. @param commandLineParameters the line passed in does not include the
  20767. name of the executable, just the parameter list.
  20768. @see shutdown, quit
  20769. */
  20770. virtual void initialise (const String& commandLineParameters) = 0;
  20771. /** Returns true if the application hasn't yet completed its initialise() method
  20772. and entered the main event loop.
  20773. This is handy for things like splash screens to know when the app's up-and-running
  20774. properly.
  20775. */
  20776. bool isInitialising() const throw();
  20777. /* Called to allow the application to clear up before exiting.
  20778. After JUCEApplication::quit() has been called, the event-dispatch loop will
  20779. terminate, and this method will get called to allow the app to sort itself
  20780. out.
  20781. Be careful that nothing happens in this method that might rely on messages
  20782. being sent, or any kind of window activity, because the message loop is no
  20783. longer running at this point.
  20784. @see DeletedAtShutdown
  20785. */
  20786. virtual void shutdown() = 0;
  20787. /** Returns the application's name.
  20788. An application must implement this to name itself.
  20789. */
  20790. virtual const String getApplicationName() = 0;
  20791. /** Returns the application's version number.
  20792. An application can implement this to give itself a version.
  20793. (The default implementation of this just returns an empty string).
  20794. */
  20795. virtual const String getApplicationVersion();
  20796. /** Checks whether multiple instances of the app are allowed.
  20797. If you application class returns true for this, more than one instance is
  20798. permitted to run (except on the Mac where this isn't possible).
  20799. If it's false, the second instance won't start, but it you will still get a
  20800. callback to anotherInstanceStarted() to tell you about this - which
  20801. gives you a chance to react to what the user was trying to do.
  20802. */
  20803. virtual bool moreThanOneInstanceAllowed();
  20804. /** Indicates that the user has tried to start up another instance of the app.
  20805. This will get called even if moreThanOneInstanceAllowed() is false.
  20806. */
  20807. virtual void anotherInstanceStarted (const String& commandLine);
  20808. /** Called when the operating system is trying to close the application.
  20809. The default implementation of this method is to call quit(), but it may
  20810. be overloaded to ignore the request or do some other special behaviour
  20811. instead. For example, you might want to offer the user the chance to save
  20812. their changes before quitting, and give them the chance to cancel.
  20813. If you want to send a quit signal to your app, this is the correct method
  20814. to call, because it means that requests that come from the system get handled
  20815. in the same way as those from your own application code. So e.g. you'd
  20816. call this method from a "quit" item on a menu bar.
  20817. */
  20818. virtual void systemRequestedQuit();
  20819. /** If any unhandled exceptions make it through to the message dispatch loop, this
  20820. callback will be triggered, in case you want to log them or do some other
  20821. type of error-handling.
  20822. If the type of exception is derived from the std::exception class, the pointer
  20823. passed-in will be valid. If the exception is of unknown type, this pointer
  20824. will be null.
  20825. */
  20826. virtual void unhandledException (const std::exception* e,
  20827. const String& sourceFilename,
  20828. int lineNumber);
  20829. /** Signals that the main message loop should stop and the application should terminate.
  20830. This isn't synchronous, it just posts a quit message to the main queue, and
  20831. when this message arrives, the message loop will stop, the shutdown() method
  20832. will be called, and the app will exit.
  20833. Note that this will cause an unconditional quit to happen, so if you need an
  20834. extra level before this, e.g. to give the user the chance to save their work
  20835. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  20836. method - see that method's help for more info.
  20837. @see MessageManager, DeletedAtShutdown
  20838. */
  20839. static void quit();
  20840. /** Sets the value that should be returned as the application's exit code when the
  20841. app quits.
  20842. This is the value that's returned by the main() function. Normally you'd leave this
  20843. as 0 unless you want to indicate an error code.
  20844. @see getApplicationReturnValue
  20845. */
  20846. void setApplicationReturnValue (int newReturnValue) throw();
  20847. /** Returns the value that has been set as the application's exit code.
  20848. @see setApplicationReturnValue
  20849. */
  20850. int getApplicationReturnValue() const throw() { return appReturnValue; }
  20851. /** Returns the application's command line params.
  20852. */
  20853. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  20854. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  20855. /** @internal */
  20856. static int main (String& commandLine, JUCEApplication* newApp);
  20857. /** @internal */
  20858. static int main (int argc, const char* argv[], JUCEApplication* newApp);
  20859. /** @internal */
  20860. static void sendUnhandledException (const std::exception* e,
  20861. const char* sourceFile,
  20862. int lineNumber);
  20863. /** @internal */
  20864. ApplicationCommandTarget* getNextCommandTarget();
  20865. /** @internal */
  20866. void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result);
  20867. /** @internal */
  20868. void getAllCommands (Array <CommandID>& commands);
  20869. /** @internal */
  20870. bool perform (const InvocationInfo& info);
  20871. /** @internal */
  20872. void actionListenerCallback (const String& message);
  20873. private:
  20874. String commandLineParameters;
  20875. int appReturnValue;
  20876. bool stillInitialising;
  20877. ScopedPointer<InterProcessLock> appLock;
  20878. JUCEApplication (const JUCEApplication&);
  20879. JUCEApplication& operator= (const JUCEApplication&);
  20880. public:
  20881. /** @internal */
  20882. bool initialiseApp (String& commandLine);
  20883. /** @internal */
  20884. static int shutdownAppAndClearUp();
  20885. };
  20886. #endif // __JUCE_APPLICATION_JUCEHEADER__
  20887. /*** End of inlined file: juce_Application.h ***/
  20888. #endif
  20889. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20890. #endif
  20891. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20892. #endif
  20893. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  20894. /*** Start of inlined file: juce_ApplicationCommandManager.h ***/
  20895. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  20896. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  20897. /*** Start of inlined file: juce_Desktop.h ***/
  20898. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  20899. #define __JUCE_DESKTOP_JUCEHEADER__
  20900. /*** Start of inlined file: juce_DeletedAtShutdown.h ***/
  20901. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  20902. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  20903. /**
  20904. Classes derived from this will be automatically deleted when the application exits.
  20905. After JUCEApplication::shutdown() has been called, any objects derived from
  20906. DeletedAtShutdown which are still in existence will be deleted in the reverse
  20907. order to that in which they were created.
  20908. So if you've got a singleton and don't want to have to explicitly delete it, just
  20909. inherit from this and it'll be taken care of.
  20910. */
  20911. class JUCE_API DeletedAtShutdown
  20912. {
  20913. protected:
  20914. /** Creates a DeletedAtShutdown object. */
  20915. DeletedAtShutdown();
  20916. /** Destructor.
  20917. It's ok to delete these objects explicitly - it's only the ones left
  20918. dangling at the end that will be deleted automatically.
  20919. */
  20920. virtual ~DeletedAtShutdown();
  20921. public:
  20922. /** Deletes all extant objects.
  20923. This shouldn't be used by applications, as it's called automatically
  20924. in the shutdown code of the JUCEApplication class.
  20925. */
  20926. static void deleteAll();
  20927. private:
  20928. DeletedAtShutdown (const DeletedAtShutdown&);
  20929. DeletedAtShutdown& operator= (const DeletedAtShutdown&);
  20930. static CriticalSection& getLock();
  20931. static Array <DeletedAtShutdown*>& getObjects();
  20932. };
  20933. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  20934. /*** End of inlined file: juce_DeletedAtShutdown.h ***/
  20935. /*** Start of inlined file: juce_Timer.h ***/
  20936. #ifndef __JUCE_TIMER_JUCEHEADER__
  20937. #define __JUCE_TIMER_JUCEHEADER__
  20938. class InternalTimerThread;
  20939. /**
  20940. Repeatedly calls a user-defined method at a specified time interval.
  20941. A Timer's timerCallback() method will be repeatedly called at a given
  20942. interval. Initially when a Timer object is created, they will do nothing
  20943. until the startTimer() method is called, then the message thread will
  20944. start calling it back until stopTimer() is called.
  20945. The time interval isn't guaranteed to be precise to any more than maybe
  20946. 10-20ms, and the intervals may end up being much longer than requested if the
  20947. system is busy. Because it's the message thread that is doing the callbacks,
  20948. any messages that take a significant amount of time to process will block
  20949. all the timers for that period.
  20950. If you need to have a single callback that is shared by multiple timers with
  20951. different frequencies, then the MultiTimer class allows you to do that - its
  20952. structure is very similar to the Timer class, but contains multiple timers
  20953. internally, each one identified by an ID number.
  20954. @see MultiTimer
  20955. */
  20956. class JUCE_API Timer
  20957. {
  20958. protected:
  20959. /** Creates a Timer.
  20960. When created, the timer is stopped, so use startTimer() to get it going.
  20961. */
  20962. Timer() throw();
  20963. /** Creates a copy of another timer.
  20964. Note that this timer won't be started, even if the one you're copying
  20965. is running.
  20966. */
  20967. Timer (const Timer& other) throw();
  20968. public:
  20969. /** Destructor. */
  20970. virtual ~Timer();
  20971. /** The user-defined callback routine that actually gets called periodically.
  20972. It's perfectly ok to call startTimer() or stopTimer() from within this
  20973. callback to change the subsequent intervals.
  20974. */
  20975. virtual void timerCallback() = 0;
  20976. /** Starts the timer and sets the length of interval required.
  20977. If the timer is already started, this will reset it, so the
  20978. time between calling this method and the next timer callback
  20979. will not be less than the interval length passed in.
  20980. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  20981. rounded up to 1)
  20982. */
  20983. void startTimer (int intervalInMilliseconds) throw();
  20984. /** Stops the timer.
  20985. No more callbacks will be made after this method returns.
  20986. If this is called from a different thread, any callbacks that may
  20987. be currently executing may be allowed to finish before the method
  20988. returns.
  20989. */
  20990. void stopTimer() throw();
  20991. /** Checks if the timer has been started.
  20992. @returns true if the timer is running.
  20993. */
  20994. bool isTimerRunning() const throw() { return periodMs > 0; }
  20995. /** Returns the timer's interval.
  20996. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  20997. */
  20998. int getTimerInterval() const throw() { return periodMs; }
  20999. private:
  21000. friend class InternalTimerThread;
  21001. int countdownMs, periodMs;
  21002. Timer* previous;
  21003. Timer* next;
  21004. Timer& operator= (const Timer&);
  21005. };
  21006. #endif // __JUCE_TIMER_JUCEHEADER__
  21007. /*** End of inlined file: juce_Timer.h ***/
  21008. class MouseInputSource;
  21009. class MouseInputSourceInternal;
  21010. class MouseListener;
  21011. /**
  21012. Classes can implement this interface and register themselves with the Desktop class
  21013. to receive callbacks when the currently focused component changes.
  21014. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  21015. */
  21016. class JUCE_API FocusChangeListener
  21017. {
  21018. public:
  21019. /** Destructor. */
  21020. virtual ~FocusChangeListener() {}
  21021. /** Callback to indicate that the currently focused component has changed. */
  21022. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  21023. };
  21024. /**
  21025. Describes and controls aspects of the computer's desktop.
  21026. */
  21027. class JUCE_API Desktop : private DeletedAtShutdown,
  21028. private Timer,
  21029. private AsyncUpdater
  21030. {
  21031. public:
  21032. /** There's only one dektop object, and this method will return it.
  21033. */
  21034. static Desktop& JUCE_CALLTYPE getInstance();
  21035. /** Returns a list of the positions of all the monitors available.
  21036. The first rectangle in the list will be the main monitor area.
  21037. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  21038. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  21039. */
  21040. const RectangleList getAllMonitorDisplayAreas (bool clippedToWorkArea = true) const throw();
  21041. /** Returns the position and size of the main monitor.
  21042. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  21043. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  21044. */
  21045. const Rectangle<int> getMainMonitorArea (bool clippedToWorkArea = true) const throw();
  21046. /** Returns the position and size of the monitor which contains this co-ordinate.
  21047. If none of the monitors contains the point, this will just return the
  21048. main monitor.
  21049. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  21050. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  21051. */
  21052. const Rectangle<int> getMonitorAreaContaining (const Point<int>& position, bool clippedToWorkArea = true) const;
  21053. /** Returns the mouse position.
  21054. The co-ordinates are relative to the top-left of the main monitor.
  21055. */
  21056. static const Point<int> getMousePosition();
  21057. /** Makes the mouse pointer jump to a given location.
  21058. The co-ordinates are relative to the top-left of the main monitor.
  21059. */
  21060. static void setMousePosition (const Point<int>& newPosition);
  21061. /** Returns the last position at which a mouse button was pressed.
  21062. */
  21063. static const Point<int> getLastMouseDownPosition() throw();
  21064. /** Returns the number of times the mouse button has been clicked since the
  21065. app started.
  21066. Each mouse-down event increments this number by 1.
  21067. */
  21068. static int getMouseButtonClickCounter() throw();
  21069. /** This lets you prevent the screensaver from becoming active.
  21070. Handy if you're running some sort of presentation app where having a screensaver
  21071. appear would be annoying.
  21072. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  21073. won't enable a screensaver unless the user has actually set one up).
  21074. The disablement will only happen while the Juce application is the foreground
  21075. process - if another task is running in front of it, then the screensaver will
  21076. be unaffected.
  21077. @see isScreenSaverEnabled
  21078. */
  21079. static void setScreenSaverEnabled (bool isEnabled);
  21080. /** Returns true if the screensaver has not been turned off.
  21081. This will return the last value passed into setScreenSaverEnabled(). Note that
  21082. it won't tell you whether the user is actually using a screen saver, just
  21083. whether this app is deliberately preventing one from running.
  21084. @see setScreenSaverEnabled
  21085. */
  21086. static bool isScreenSaverEnabled();
  21087. /** Registers a MouseListener that will receive all mouse events that occur on
  21088. any component.
  21089. @see removeGlobalMouseListener
  21090. */
  21091. void addGlobalMouseListener (MouseListener* listener);
  21092. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  21093. method.
  21094. @see addGlobalMouseListener
  21095. */
  21096. void removeGlobalMouseListener (MouseListener* listener);
  21097. /** Registers a MouseListener that will receive a callback whenever the focused
  21098. component changes.
  21099. */
  21100. void addFocusChangeListener (FocusChangeListener* listener);
  21101. /** Unregisters a listener that was added with addFocusChangeListener(). */
  21102. void removeFocusChangeListener (FocusChangeListener* listener);
  21103. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  21104. The component must already be on the desktop for this method to work. It will
  21105. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  21106. etc will be hidden.
  21107. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  21108. the component that's currently being used will be resized back to the size
  21109. and position it was in before being put into this mode.
  21110. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  21111. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  21112. to hide as much on-screen paraphenalia as possible.
  21113. */
  21114. void setKioskModeComponent (Component* componentToUse,
  21115. bool allowMenusAndBars = true);
  21116. /** Returns the component that is currently being used in kiosk-mode.
  21117. This is the component that was last set by setKioskModeComponent(). If none
  21118. has been set, this returns 0.
  21119. */
  21120. Component* getKioskModeComponent() const throw() { return kioskModeComponent; }
  21121. /** Returns the number of components that are currently active as top-level
  21122. desktop windows.
  21123. @see getComponent, Component::addToDesktop
  21124. */
  21125. int getNumComponents() const throw();
  21126. /** Returns one of the top-level desktop window components.
  21127. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  21128. index is out-of-range.
  21129. @see getNumComponents, Component::addToDesktop
  21130. */
  21131. Component* getComponent (int index) const throw();
  21132. /** Finds the component at a given screen location.
  21133. This will drill down into top-level windows to find the child component at
  21134. the given position.
  21135. Returns 0 if the co-ordinates are inside a non-Juce window.
  21136. */
  21137. Component* findComponentAt (const Point<int>& screenPosition) const;
  21138. /** Returns the number of MouseInputSource objects the system has at its disposal.
  21139. In a traditional single-mouse system, there might be only one object. On a multi-touch
  21140. system, there could be one input source per potential finger.
  21141. To find out how many mouse events are currently happening, use getNumDraggingMouseSources().
  21142. @see getMouseSource
  21143. */
  21144. int getNumMouseSources() const throw() { return mouseSources.size(); }
  21145. /** Returns one of the system's MouseInputSource objects.
  21146. The index should be from 0 to getNumMouseSources() - 1. Out-of-range indexes will return
  21147. a null pointer.
  21148. In a traditional single-mouse system, there might be only one object. On a multi-touch
  21149. system, there could be one input source per potential finger.
  21150. */
  21151. MouseInputSource* getMouseSource (int index) const throw() { return mouseSources [index]; }
  21152. /** Returns the main mouse input device that the system is using.
  21153. @see getNumMouseSources()
  21154. */
  21155. MouseInputSource& getMainMouseSource() const throw() { return *mouseSources.getUnchecked(0); }
  21156. /** Returns the number of mouse-sources that are currently being dragged.
  21157. In a traditional single-mouse system, this will be 0 or 1, depending on whether a
  21158. juce component has the button down on it. In a multi-touch system, this could
  21159. be any number from 0 to the number of simultaneous touches that can be detected.
  21160. */
  21161. int getNumDraggingMouseSources() const throw();
  21162. /** Returns one of the mouse sources that's currently being dragged.
  21163. The index should be between 0 and getNumDraggingMouseSources() - 1. If the index is
  21164. out of range, or if no mice or fingers are down, this will return a null pointer.
  21165. */
  21166. MouseInputSource* getDraggingMouseSource (int index) const throw();
  21167. juce_UseDebuggingNewOperator
  21168. /** Tells this object to refresh its idea of what the screen resolution is.
  21169. (Called internally by the native code).
  21170. */
  21171. void refreshMonitorSizes();
  21172. /** True if the OS supports semitransparent windows */
  21173. static bool canUseSemiTransparentWindows() throw();
  21174. private:
  21175. static Desktop* instance;
  21176. friend class Component;
  21177. friend class ComponentPeer;
  21178. friend class MouseInputSource;
  21179. friend class MouseInputSourceInternal;
  21180. friend class DeletedAtShutdown;
  21181. friend class TopLevelWindowManager;
  21182. OwnedArray <MouseInputSource> mouseSources;
  21183. void createMouseInputSources();
  21184. ListenerList <MouseListener> mouseListeners;
  21185. ListenerList <FocusChangeListener> focusListeners;
  21186. Array <Component*> desktopComponents;
  21187. Array <Rectangle<int> > monitorCoordsClipped, monitorCoordsUnclipped;
  21188. Point<int> lastFakeMouseMove;
  21189. void sendMouseMove();
  21190. int mouseClickCounter;
  21191. void incrementMouseClickCounter() throw();
  21192. Component* kioskModeComponent;
  21193. Rectangle<int> kioskComponentOriginalBounds;
  21194. void timerCallback();
  21195. void resetTimer();
  21196. int getNumDisplayMonitors() const throw();
  21197. const Rectangle<int> getDisplayMonitorCoordinates (int index, bool clippedToWorkArea) const throw();
  21198. void addDesktopComponent (Component* c);
  21199. void removeDesktopComponent (Component* c);
  21200. void componentBroughtToFront (Component* c);
  21201. void triggerFocusCallback();
  21202. void handleAsyncUpdate();
  21203. Desktop();
  21204. ~Desktop();
  21205. Desktop (const Desktop&);
  21206. Desktop& operator= (const Desktop&);
  21207. };
  21208. #endif // __JUCE_DESKTOP_JUCEHEADER__
  21209. /*** End of inlined file: juce_Desktop.h ***/
  21210. class KeyPressMappingSet;
  21211. class ApplicationCommandManagerListener;
  21212. /**
  21213. One of these objects holds a list of all the commands your app can perform,
  21214. and despatches these commands when needed.
  21215. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  21216. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  21217. to invoke automatically, which means you don't have to handle the result of a menu
  21218. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  21219. which can choose which events they want to handle.
  21220. This architecture also allows for nested ApplicationCommandTargets, so that for example
  21221. you could have two different objects, one inside the other, both of which can respond to
  21222. a "delete" command. Depending on which one has focus, the command will be sent to the
  21223. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  21224. method.
  21225. To set up your app to use commands, you'll need to do the following:
  21226. - Create a global ApplicationCommandManager to hold the list of all possible
  21227. commands. (This will also manage a set of key-mappings for them).
  21228. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  21229. This allows the object to provide a list of commands that it can perform, and
  21230. to handle them.
  21231. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  21232. or ApplicationCommandManager::registerCommand().
  21233. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  21234. method to access the key-mapper object, which you will need to register as a key-listener
  21235. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  21236. about setting this up.
  21237. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  21238. cause these commands to be invoked automatically.
  21239. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  21240. When a command is invoked, the ApplicationCommandManager will try to choose the best
  21241. ApplicationCommandTarget to receive the specified command. To do this it will use the
  21242. current keyboard focus to see which component might be interested, and will search the
  21243. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  21244. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  21245. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  21246. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  21247. point if the command still hasn't been performed, it will be passed to the current
  21248. JUCEApplication object (which is itself an ApplicationCommandTarget).
  21249. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  21250. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  21251. the object yourself.
  21252. @see ApplicationCommandTarget, ApplicationCommandInfo
  21253. */
  21254. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  21255. private FocusChangeListener
  21256. {
  21257. public:
  21258. /** Creates an ApplicationCommandManager.
  21259. Once created, you'll need to register all your app's commands with it, using
  21260. ApplicationCommandManager::registerAllCommandsForTarget() or
  21261. ApplicationCommandManager::registerCommand().
  21262. */
  21263. ApplicationCommandManager();
  21264. /** Destructor.
  21265. Make sure that you don't delete this if pointers to it are still being used by
  21266. objects such as PopupMenus or Buttons.
  21267. */
  21268. virtual ~ApplicationCommandManager();
  21269. /** Clears the current list of all commands.
  21270. Note that this will also clear the contents of the KeyPressMappingSet.
  21271. */
  21272. void clearCommands();
  21273. /** Adds a command to the list of registered commands.
  21274. @see registerAllCommandsForTarget
  21275. */
  21276. void registerCommand (const ApplicationCommandInfo& newCommand);
  21277. /** Adds all the commands that this target publishes to the manager's list.
  21278. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  21279. to get details about all the commands that this target can do, and will call
  21280. registerCommand() to add each one to the manger's list.
  21281. @see registerCommand
  21282. */
  21283. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  21284. /** Removes the command with a specified ID.
  21285. Note that this will also remove any key mappings that are mapped to the command.
  21286. */
  21287. void removeCommand (CommandID commandID);
  21288. /** This should be called to tell the manager that one of its registered commands may have changed
  21289. its active status.
  21290. Because the command manager only finds out whether a command is active or inactive by querying
  21291. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  21292. allows things like buttons to update their enablement, etc.
  21293. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  21294. for any registered listeners.
  21295. */
  21296. void commandStatusChanged();
  21297. /** Returns the number of commands that have been registered.
  21298. @see registerCommand
  21299. */
  21300. int getNumCommands() const throw() { return commands.size(); }
  21301. /** Returns the details about one of the registered commands.
  21302. The index is between 0 and (getNumCommands() - 1).
  21303. */
  21304. const ApplicationCommandInfo* getCommandForIndex (int index) const throw() { return commands [index]; }
  21305. /** Returns the details about a given command ID.
  21306. This will search the list of registered commands for one with the given command
  21307. ID number, and return its associated info. If no matching command is found, this
  21308. will return 0.
  21309. */
  21310. const ApplicationCommandInfo* getCommandForID (CommandID commandID) const throw();
  21311. /** Returns the name field for a command.
  21312. An empty string is returned if no command with this ID has been registered.
  21313. @see getDescriptionOfCommand
  21314. */
  21315. const String getNameOfCommand (CommandID commandID) const throw();
  21316. /** Returns the description field for a command.
  21317. An empty string is returned if no command with this ID has been registered. If the
  21318. command has no description, this will return its short name field instead.
  21319. @see getNameOfCommand
  21320. */
  21321. const String getDescriptionOfCommand (CommandID commandID) const throw();
  21322. /** Returns the list of categories.
  21323. This will go through all registered commands, and return a list of all the distict
  21324. categoryName values from their ApplicationCommandInfo structure.
  21325. @see getCommandsInCategory()
  21326. */
  21327. const StringArray getCommandCategories() const throw();
  21328. /** Returns a list of all the command UIDs in a particular category.
  21329. @see getCommandCategories()
  21330. */
  21331. const Array <CommandID> getCommandsInCategory (const String& categoryName) const throw();
  21332. /** Returns the manager's internal set of key mappings.
  21333. This object can be used to edit the keypresses. To actually link this object up
  21334. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  21335. class.
  21336. @see KeyPressMappingSet
  21337. */
  21338. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  21339. /** Invokes the given command directly, sending it to the default target.
  21340. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  21341. structure.
  21342. */
  21343. bool invokeDirectly (CommandID commandID, bool asynchronously);
  21344. /** Sends a command to the default target.
  21345. This will choose a target using getFirstCommandTarget(), and send the specified command
  21346. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  21347. first target can't handle the command, it will be passed on to targets further down the
  21348. chain (see ApplicationCommandTarget::invoke() for more info).
  21349. @param invocationInfo this must be correctly filled-in, describing the context for
  21350. the invocation.
  21351. @param asynchronously if false, the command will be performed before this method returns.
  21352. If true, a message will be posted so that the command will be performed
  21353. later on the message thread, and this method will return immediately.
  21354. @see ApplicationCommandTarget::invoke
  21355. */
  21356. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  21357. bool asynchronously);
  21358. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  21359. Whenever the manager needs to know which target a command should be sent to, it calls
  21360. this method to determine the first one to try.
  21361. By default, this method will return the target that was set by calling setFirstCommandTarget().
  21362. If no target is set, it will return the result of findDefaultComponentTarget().
  21363. If you need to make sure all commands go via your own custom target, then you can
  21364. either use setFirstCommandTarget() to specify a single target, or override this method
  21365. if you need more complex logic to choose one.
  21366. It may return 0 if no targets are available.
  21367. @see getTargetForCommand, invoke, invokeDirectly
  21368. */
  21369. virtual ApplicationCommandTarget* getFirstCommandTarget (CommandID commandID);
  21370. /** Sets a target to be returned by getFirstCommandTarget().
  21371. If this is set to 0, then getFirstCommandTarget() will by default return the
  21372. result of findDefaultComponentTarget().
  21373. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  21374. deleting the target object.
  21375. */
  21376. void setFirstCommandTarget (ApplicationCommandTarget* newTarget) throw();
  21377. /** Tries to find the best target to use to perform a given command.
  21378. This will call getFirstCommandTarget() to find the preferred target, and will
  21379. check whether that target can handle the given command. If it can't, then it'll use
  21380. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  21381. so on until no more are available.
  21382. If no targets are found that can perform the command, this method will return 0.
  21383. If a target is found, then it will get the target to fill-in the upToDateInfo
  21384. structure with the latest info about that command, so that the caller can see
  21385. whether the command is disabled, ticked, etc.
  21386. */
  21387. ApplicationCommandTarget* getTargetForCommand (CommandID commandID,
  21388. ApplicationCommandInfo& upToDateInfo);
  21389. /** Registers a listener that will be called when various events occur. */
  21390. void addListener (ApplicationCommandManagerListener* listener) throw();
  21391. /** Deregisters a previously-added listener. */
  21392. void removeListener (ApplicationCommandManagerListener* listener) throw();
  21393. /** Looks for a suitable command target based on which Components have the keyboard focus.
  21394. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  21395. but is exposed here in case it's useful.
  21396. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  21397. windows, etc., and using the findTargetForComponent() method.
  21398. */
  21399. static ApplicationCommandTarget* findDefaultComponentTarget();
  21400. /** Examines this component and all its parents in turn, looking for the first one
  21401. which is a ApplicationCommandTarget.
  21402. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  21403. that class.
  21404. */
  21405. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  21406. juce_UseDebuggingNewOperator
  21407. private:
  21408. OwnedArray <ApplicationCommandInfo> commands;
  21409. ListenerList <ApplicationCommandManagerListener> listeners;
  21410. ScopedPointer <KeyPressMappingSet> keyMappings;
  21411. ApplicationCommandTarget* firstTarget;
  21412. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info);
  21413. void handleAsyncUpdate();
  21414. void globalFocusChanged (Component*);
  21415. // xxx this is just here to cause a compile error in old code that hasn't been changed to use the new
  21416. // version of this method.
  21417. virtual short getFirstCommandTarget() { return 0; }
  21418. ApplicationCommandManager (const ApplicationCommandManager&);
  21419. ApplicationCommandManager& operator= (const ApplicationCommandManager&);
  21420. };
  21421. /**
  21422. A listener that receives callbacks from an ApplicationCommandManager when
  21423. commands are invoked or the command list is changed.
  21424. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  21425. */
  21426. class JUCE_API ApplicationCommandManagerListener
  21427. {
  21428. public:
  21429. /** Destructor. */
  21430. virtual ~ApplicationCommandManagerListener() {}
  21431. /** Called when an app command is about to be invoked. */
  21432. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  21433. /** Called when commands are registered or deregistered from the
  21434. command manager, or when commands are made active or inactive.
  21435. Note that if you're using this to watch for changes to whether a command is disabled,
  21436. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  21437. whenever the status of your command might have changed.
  21438. */
  21439. virtual void applicationCommandListChanged() = 0;
  21440. };
  21441. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  21442. /*** End of inlined file: juce_ApplicationCommandManager.h ***/
  21443. #endif
  21444. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  21445. #endif
  21446. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21447. /*** Start of inlined file: juce_ApplicationProperties.h ***/
  21448. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21449. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21450. /*** Start of inlined file: juce_PropertiesFile.h ***/
  21451. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  21452. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  21453. /** Wrapper on a file that stores a list of key/value data pairs.
  21454. Useful for storing application settings, etc. See the PropertySet class for
  21455. the interfaces that read and write values.
  21456. Not designed for very large amounts of data, as it keeps all the values in
  21457. memory and writes them out to disk lazily when they are changed.
  21458. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  21459. with it, and these will be signalled when a value changes.
  21460. @see PropertySet
  21461. */
  21462. class JUCE_API PropertiesFile : public PropertySet,
  21463. public ChangeBroadcaster,
  21464. private Timer
  21465. {
  21466. public:
  21467. enum FileFormatOptions
  21468. {
  21469. ignoreCaseOfKeyNames = 1,
  21470. storeAsBinary = 2,
  21471. storeAsCompressedBinary = 4,
  21472. storeAsXML = 8
  21473. };
  21474. /**
  21475. Creates a PropertiesFile object.
  21476. @param file the file to use
  21477. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  21478. is changed, the object will wait for this amount
  21479. of time and then save the file. If zero, the file
  21480. will be written to disk immediately on being changed
  21481. (which might be slow, as it'll re-write synchronously
  21482. each time a value-change method is called). If it is
  21483. less than zero, the file won't be saved until
  21484. save() or saveIfNeeded() are explicitly called.
  21485. @param optionFlags a combination of the flags in the FileFormatOptions
  21486. enum, which specify the type of file to save, and other
  21487. options.
  21488. @param processLock an optional InterprocessLock object that will be used to
  21489. prevent multiple threads or processes from writing to the file
  21490. at the same time. The PropertiesFile will keep a pointer to
  21491. this object but will not take ownership of it - the caller is
  21492. responsible for making sure that the lock doesn't get deleted
  21493. before the PropertiesFile has been deleted.
  21494. */
  21495. PropertiesFile (const File& file,
  21496. int millisecondsBeforeSaving,
  21497. int optionFlags,
  21498. InterProcessLock* processLock = 0);
  21499. /** Destructor.
  21500. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  21501. */
  21502. ~PropertiesFile();
  21503. /** Returns true if this file was created from a valid (or non-existent) file.
  21504. If the file failed to load correctly because it was corrupt or had insufficient
  21505. access, this will be false.
  21506. */
  21507. bool isValidFile() const throw() { return loadedOk; }
  21508. /** This will flush all the values to disk if they've changed since the last
  21509. time they were saved.
  21510. Returns false if it fails to write to the file for some reason (maybe because
  21511. it's read-only or the directory doesn't exist or something).
  21512. @see save
  21513. */
  21514. bool saveIfNeeded();
  21515. /** This will force a write-to-disk of the current values, regardless of whether
  21516. anything has changed since the last save.
  21517. Returns false if it fails to write to the file for some reason (maybe because
  21518. it's read-only or the directory doesn't exist or something).
  21519. @see saveIfNeeded
  21520. */
  21521. bool save();
  21522. /** Returns true if the properties have been altered since the last time they were saved.
  21523. The file is flagged as needing to be saved when you change a value, but you can
  21524. explicitly set this flag with setNeedsToBeSaved().
  21525. */
  21526. bool needsToBeSaved() const;
  21527. /** Explicitly sets the flag to indicate whether the file needs saving or not.
  21528. @see needsToBeSaved
  21529. */
  21530. void setNeedsToBeSaved (bool needsToBeSaved);
  21531. /** Returns the file that's being used. */
  21532. const File getFile() const { return file; }
  21533. /** Handy utility to create a properties file in whatever the standard OS-specific
  21534. location is for these things.
  21535. This uses getDefaultAppSettingsFile() to decide what file to create, then
  21536. creates a PropertiesFile object with the specified properties. See
  21537. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  21538. what the parameters do.
  21539. @see getDefaultAppSettingsFile
  21540. */
  21541. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  21542. const String& fileNameSuffix,
  21543. const String& folderName,
  21544. bool commonToAllUsers,
  21545. int millisecondsBeforeSaving,
  21546. int propertiesFileOptions,
  21547. InterProcessLock* processLock = 0);
  21548. /** Handy utility to choose a file in the standard OS-dependent location for application
  21549. settings files.
  21550. So on a Mac, this will return a file called:
  21551. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  21552. On Windows it'll return something like:
  21553. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  21554. On Linux it'll return
  21555. ~/.[folderName]/[applicationName].[fileNameSuffix]
  21556. If you pass an empty string as the folder name, it'll use the app name for this (or
  21557. omit the folder name on the Mac).
  21558. If commonToAllUsers is true, then this will return the same file for all users of the
  21559. computer, regardless of the current user. If it is false, the file will be specific to
  21560. only the current user. Use this to choose whether you're saving settings that are common
  21561. or user-specific.
  21562. */
  21563. static const File getDefaultAppSettingsFile (const String& applicationName,
  21564. const String& fileNameSuffix,
  21565. const String& folderName,
  21566. bool commonToAllUsers);
  21567. juce_UseDebuggingNewOperator
  21568. protected:
  21569. virtual void propertyChanged();
  21570. private:
  21571. File file;
  21572. int timerInterval;
  21573. const int options;
  21574. bool loadedOk, needsWriting;
  21575. InterProcessLock* processLock;
  21576. typedef const ScopedPointer<InterProcessLock::ScopedLockType> ProcessScopedLock;
  21577. InterProcessLock::ScopedLockType* createProcessLock() const;
  21578. void timerCallback();
  21579. PropertiesFile (const PropertiesFile&);
  21580. PropertiesFile& operator= (const PropertiesFile&);
  21581. };
  21582. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  21583. /*** End of inlined file: juce_PropertiesFile.h ***/
  21584. /**
  21585. Manages a collection of properties.
  21586. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  21587. as a singleton.
  21588. It holds two different PropertiesFile objects internally, one for user-specific
  21589. settings (stored in your user directory), and one for settings that are common to
  21590. all users (stored in a folder accessible to all users).
  21591. The class manages the creation of these files on-demand, allowing access via the
  21592. getUserSettings() and getCommonSettings() methods. It also has a few handy
  21593. methods like testWriteAccess() to check that the files can be saved.
  21594. If you're using one of these as a singleton, then your app's start-up code should
  21595. first of all call setStorageParameters() to tell it the parameters to use to create
  21596. the properties files.
  21597. @see PropertiesFile
  21598. */
  21599. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  21600. {
  21601. public:
  21602. /**
  21603. Creates an ApplicationProperties object.
  21604. Before using it, you must call setStorageParameters() to give it the info
  21605. it needs to create the property files.
  21606. */
  21607. ApplicationProperties() throw();
  21608. /** Destructor.
  21609. */
  21610. ~ApplicationProperties();
  21611. juce_DeclareSingleton (ApplicationProperties, false)
  21612. /** Gives the object the information it needs to create the appropriate properties files.
  21613. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  21614. info about how these parameters are used.
  21615. */
  21616. void setStorageParameters (const String& applicationName,
  21617. const String& fileNameSuffix,
  21618. const String& folderName,
  21619. int millisecondsBeforeSaving,
  21620. int propertiesFileOptions) throw();
  21621. /** Tests whether the files can be successfully written to, and can show
  21622. an error message if not.
  21623. Returns true if none of the tests fail.
  21624. @param testUserSettings if true, the user settings file will be tested
  21625. @param testCommonSettings if true, the common settings file will be tested
  21626. @param showWarningDialogOnFailure if true, the method will show a helpful error
  21627. message box if either of the tests fail
  21628. */
  21629. bool testWriteAccess (bool testUserSettings,
  21630. bool testCommonSettings,
  21631. bool showWarningDialogOnFailure);
  21632. /** Returns the user settings file.
  21633. The first time this is called, it will create and load the properties file.
  21634. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  21635. the common settings are used as a second-chance place to look. This is done via the
  21636. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  21637. to the fallback for the user settings.
  21638. @see getCommonSettings
  21639. */
  21640. PropertiesFile* getUserSettings() throw();
  21641. /** Returns the common settings file.
  21642. The first time this is called, it will create and load the properties file.
  21643. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  21644. read-only (e.g. because the user doesn't have permission to write
  21645. to shared files), then this will return the user settings instead,
  21646. (like getUserSettings() would do). This is handy if you'd like to
  21647. write a value to the common settings, but if that's no possible,
  21648. then you'd rather write to the user settings than none at all.
  21649. If returnUserPropsIfReadOnly is false, this method will always return
  21650. the common settings, even if any changes to them can't be saved.
  21651. @see getUserSettings
  21652. */
  21653. PropertiesFile* getCommonSettings (bool returnUserPropsIfReadOnly) throw();
  21654. /** Saves both files if they need to be saved.
  21655. @see PropertiesFile::saveIfNeeded
  21656. */
  21657. bool saveIfNeeded();
  21658. /** Flushes and closes both files if they are open.
  21659. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  21660. and closes both files. They will then be re-opened the next time getUserSettings()
  21661. or getCommonSettings() is called.
  21662. */
  21663. void closeFiles();
  21664. juce_UseDebuggingNewOperator
  21665. private:
  21666. ScopedPointer <PropertiesFile> userProps, commonProps;
  21667. String appName, fileSuffix, folderName;
  21668. int msBeforeSaving, options;
  21669. int commonSettingsAreReadOnly;
  21670. ApplicationProperties (const ApplicationProperties&);
  21671. ApplicationProperties& operator= (const ApplicationProperties&);
  21672. void openFiles() throw();
  21673. };
  21674. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21675. /*** End of inlined file: juce_ApplicationProperties.h ***/
  21676. #endif
  21677. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  21678. /*** Start of inlined file: juce_AiffAudioFormat.h ***/
  21679. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  21680. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  21681. /*** Start of inlined file: juce_AudioFormat.h ***/
  21682. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  21683. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  21684. /*** Start of inlined file: juce_AudioFormatReader.h ***/
  21685. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  21686. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  21687. class AudioFormat;
  21688. /**
  21689. Reads samples from an audio file stream.
  21690. A subclass that reads a specific type of audio format will be created by
  21691. an AudioFormat object.
  21692. @see AudioFormat, AudioFormatWriter
  21693. */
  21694. class JUCE_API AudioFormatReader
  21695. {
  21696. protected:
  21697. /** Creates an AudioFormatReader object.
  21698. @param sourceStream the stream to read from - this will be deleted
  21699. by this object when it is no longer needed. (Some
  21700. specialised readers might not use this parameter and
  21701. can leave it as 0).
  21702. @param formatName the description that will be returned by the getFormatName()
  21703. method
  21704. */
  21705. AudioFormatReader (InputStream* sourceStream,
  21706. const String& formatName);
  21707. public:
  21708. /** Destructor. */
  21709. virtual ~AudioFormatReader();
  21710. /** Returns a description of what type of format this is.
  21711. E.g. "AIFF"
  21712. */
  21713. const String getFormatName() const throw() { return formatName; }
  21714. /** Reads samples from the stream.
  21715. @param destSamples an array of buffers into which the sample data for each
  21716. channel will be written.
  21717. If the format is fixed-point, each channel will be written
  21718. as an array of 32-bit signed integers using the full
  21719. range -0x80000000 to 0x7fffffff, regardless of the source's
  21720. bit-depth. If it is a floating-point format, you should cast
  21721. the resulting array to a (float**) to get the values (in the
  21722. range -1.0 to 1.0 or beyond)
  21723. If the format is stereo, then destSamples[0] is the left channel
  21724. data, and destSamples[1] is the right channel.
  21725. The numDestChannels parameter indicates how many pointers this array
  21726. contains, but some of these pointers can be null if you don't want to
  21727. read data for some of the channels
  21728. @param numDestChannels the number of array elements in the destChannels array
  21729. @param startSampleInSource the position in the audio file or stream at which the samples
  21730. should be read, as a number of samples from the start of the
  21731. stream. It's ok for this to be beyond the start or end of the
  21732. available data - any samples that are out-of-range will be returned
  21733. as zeros.
  21734. @param numSamplesToRead the number of samples to read. If this is greater than the number
  21735. of samples that the file or stream contains. the result will be padded
  21736. with zeros
  21737. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  21738. for some of the channels that you pass in, then they should be filled with
  21739. copies of valid source channels.
  21740. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  21741. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  21742. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  21743. was false, then only the first channel would be filled with the file's contents, and
  21744. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  21745. from a stereo file, then the last 3 would all end up with copies of the same data.
  21746. @returns true if the operation succeeded, false if there was an error. Note
  21747. that reading sections of data beyond the extent of the stream isn't an
  21748. error - the reader should just return zeros for these regions
  21749. @see readMaxLevels
  21750. */
  21751. bool read (int** destSamples,
  21752. int numDestChannels,
  21753. int64 startSampleInSource,
  21754. int numSamplesToRead,
  21755. bool fillLeftoverChannelsWithCopies);
  21756. /** Finds the highest and lowest sample levels from a section of the audio stream.
  21757. This will read a block of samples from the stream, and measure the
  21758. highest and lowest sample levels from the channels in that section, returning
  21759. these as normalised floating-point levels.
  21760. @param startSample the offset into the audio stream to start reading from. It's
  21761. ok for this to be beyond the start or end of the stream.
  21762. @param numSamples how many samples to read
  21763. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  21764. @param highestLeft on return, this is the highest absolute sample from the left channel
  21765. @param lowestRight on return, this is the lowest absolute sample from the right
  21766. channel (if there is one)
  21767. @param highestRight on return, this is the highest absolute sample from the right
  21768. channel (if there is one)
  21769. @see read
  21770. */
  21771. virtual void readMaxLevels (int64 startSample,
  21772. int64 numSamples,
  21773. float& lowestLeft,
  21774. float& highestLeft,
  21775. float& lowestRight,
  21776. float& highestRight);
  21777. /** Scans the source looking for a sample whose magnitude is in a specified range.
  21778. This will read from the source, either forwards or backwards between two sample
  21779. positions, until it finds a sample whose magnitude lies between two specified levels.
  21780. If it finds a suitable sample, it returns its position; if not, it will return -1.
  21781. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  21782. points when you're searching for a continuous range of samples
  21783. @param startSample the first sample to look at
  21784. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  21785. the search will go backwards
  21786. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  21787. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  21788. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  21789. of this many consecutive samples, all of which lie
  21790. within the target range. When it finds such a sequence,
  21791. it returns the position of the first in-range sample
  21792. it found (i.e. the earliest one if scanning forwards, the
  21793. latest one if scanning backwards)
  21794. */
  21795. int64 searchForLevel (int64 startSample,
  21796. int64 numSamplesToSearch,
  21797. double magnitudeRangeMinimum,
  21798. double magnitudeRangeMaximum,
  21799. int minimumConsecutiveSamples);
  21800. /** The sample-rate of the stream. */
  21801. double sampleRate;
  21802. /** The number of bits per sample, e.g. 16, 24, 32. */
  21803. unsigned int bitsPerSample;
  21804. /** The total number of samples in the audio stream. */
  21805. int64 lengthInSamples;
  21806. /** The total number of channels in the audio stream. */
  21807. unsigned int numChannels;
  21808. /** Indicates whether the data is floating-point or fixed. */
  21809. bool usesFloatingPointData;
  21810. /** A set of metadata values that the reader has pulled out of the stream.
  21811. Exactly what these values are depends on the format, so you can
  21812. check out the format implementation code to see what kind of stuff
  21813. they understand.
  21814. */
  21815. StringPairArray metadataValues;
  21816. /** The input stream, for use by subclasses. */
  21817. InputStream* input;
  21818. /** Subclasses must implement this method to perform the low-level read operation.
  21819. Callers should use read() instead of calling this directly.
  21820. @param destSamples the array of destination buffers to fill. Some of these
  21821. pointers may be null
  21822. @param numDestChannels the number of items in the destSamples array. This
  21823. value is guaranteed not to be greater than the number of
  21824. channels that this reader object contains
  21825. @param startOffsetInDestBuffer the number of samples from the start of the
  21826. dest data at which to begin writing
  21827. @param startSampleInFile the number of samples into the source data at which
  21828. to begin reading. This value is guaranteed to be >= 0.
  21829. @param numSamples the number of samples to read
  21830. */
  21831. virtual bool readSamples (int** destSamples,
  21832. int numDestChannels,
  21833. int startOffsetInDestBuffer,
  21834. int64 startSampleInFile,
  21835. int numSamples) = 0;
  21836. juce_UseDebuggingNewOperator
  21837. private:
  21838. String formatName;
  21839. AudioFormatReader (const AudioFormatReader&);
  21840. AudioFormatReader& operator= (const AudioFormatReader&);
  21841. };
  21842. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  21843. /*** End of inlined file: juce_AudioFormatReader.h ***/
  21844. /*** Start of inlined file: juce_AudioFormatWriter.h ***/
  21845. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  21846. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  21847. /*** Start of inlined file: juce_AudioSource.h ***/
  21848. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  21849. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  21850. /*** Start of inlined file: juce_AudioSampleBuffer.h ***/
  21851. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  21852. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  21853. class AudioFormatReader;
  21854. class AudioFormatWriter;
  21855. /**
  21856. A multi-channel buffer of 32-bit floating point audio samples.
  21857. */
  21858. class JUCE_API AudioSampleBuffer
  21859. {
  21860. public:
  21861. /** Creates a buffer with a specified number of channels and samples.
  21862. The contents of the buffer will initially be undefined, so use clear() to
  21863. set all the samples to zero.
  21864. The buffer will allocate its memory internally, and this will be released
  21865. when the buffer is deleted.
  21866. */
  21867. AudioSampleBuffer (int numChannels,
  21868. int numSamples) throw();
  21869. /** Creates a buffer using a pre-allocated block of memory.
  21870. Note that if the buffer is resized or its number of channels is changed, it
  21871. will re-allocate memory internally and copy the existing data to this new area,
  21872. so it will then stop directly addressing this memory.
  21873. @param dataToReferTo a pre-allocated array containing pointers to the data
  21874. for each channel that should be used by this buffer. The
  21875. buffer will only refer to this memory, it won't try to delete
  21876. it when the buffer is deleted or resized.
  21877. @param numChannels the number of channels to use - this must correspond to the
  21878. number of elements in the array passed in
  21879. @param numSamples the number of samples to use - this must correspond to the
  21880. size of the arrays passed in
  21881. */
  21882. AudioSampleBuffer (float** dataToReferTo,
  21883. int numChannels,
  21884. int numSamples) throw();
  21885. /** Copies another buffer.
  21886. This buffer will make its own copy of the other's data, unless the buffer was created
  21887. using an external data buffer, in which case boths buffers will just point to the same
  21888. shared block of data.
  21889. */
  21890. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  21891. /** Copies another buffer onto this one.
  21892. This buffer's size will be changed to that of the other buffer.
  21893. */
  21894. AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  21895. /** Destructor.
  21896. This will free any memory allocated by the buffer.
  21897. */
  21898. virtual ~AudioSampleBuffer() throw();
  21899. /** Returns the number of channels of audio data that this buffer contains.
  21900. @see getSampleData
  21901. */
  21902. int getNumChannels() const throw() { return numChannels; }
  21903. /** Returns the number of samples allocated in each of the buffer's channels.
  21904. @see getSampleData
  21905. */
  21906. int getNumSamples() const throw() { return size; }
  21907. /** Returns a pointer one of the buffer's channels.
  21908. For speed, this doesn't check whether the channel number is out of range,
  21909. so be careful when using it!
  21910. */
  21911. float* getSampleData (const int channelNumber) const throw()
  21912. {
  21913. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  21914. return channels [channelNumber];
  21915. }
  21916. /** Returns a pointer to a sample in one of the buffer's channels.
  21917. For speed, this doesn't check whether the channel and sample number
  21918. are out-of-range, so be careful when using it!
  21919. */
  21920. float* getSampleData (const int channelNumber,
  21921. const int sampleOffset) const throw()
  21922. {
  21923. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  21924. jassert (((unsigned int) sampleOffset) < (unsigned int) size);
  21925. return channels [channelNumber] + sampleOffset;
  21926. }
  21927. /** Returns an array of pointers to the channels in the buffer.
  21928. Don't modify any of the pointers that are returned, and bear in mind that
  21929. these will become invalid if the buffer is resized.
  21930. */
  21931. float** getArrayOfChannels() const throw() { return channels; }
  21932. /** Chages the buffer's size or number of channels.
  21933. This can expand or contract the buffer's length, and add or remove channels.
  21934. If keepExistingContent is true, it will try to preserve as much of the
  21935. old data as it can in the new buffer.
  21936. If clearExtraSpace is true, then any extra channels or space that is
  21937. allocated will be also be cleared. If false, then this space is left
  21938. uninitialised.
  21939. If avoidReallocating is true, then changing the buffer's size won't reduce the
  21940. amount of memory that is currently allocated (but it will still increase it if
  21941. the new size is bigger than the amount it currently has). If this is false, then
  21942. a new allocation will be done so that the buffer uses takes up the minimum amount
  21943. of memory that it needs.
  21944. */
  21945. void setSize (int newNumChannels,
  21946. int newNumSamples,
  21947. bool keepExistingContent = false,
  21948. bool clearExtraSpace = false,
  21949. bool avoidReallocating = false) throw();
  21950. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  21951. There's also a constructor that lets you specify arrays like this, but this
  21952. lets you change the channels dynamically.
  21953. Note that if the buffer is resized or its number of channels is changed, it
  21954. will re-allocate memory internally and copy the existing data to this new area,
  21955. so it will then stop directly addressing this memory.
  21956. @param dataToReferTo a pre-allocated array containing pointers to the data
  21957. for each channel that should be used by this buffer. The
  21958. buffer will only refer to this memory, it won't try to delete
  21959. it when the buffer is deleted or resized.
  21960. @param numChannels the number of channels to use - this must correspond to the
  21961. number of elements in the array passed in
  21962. @param numSamples the number of samples to use - this must correspond to the
  21963. size of the arrays passed in
  21964. */
  21965. void setDataToReferTo (float** dataToReferTo,
  21966. int numChannels,
  21967. int numSamples) throw();
  21968. /** Clears all the samples in all channels. */
  21969. void clear() throw();
  21970. /** Clears a specified region of all the channels.
  21971. For speed, this doesn't check whether the channel and sample number
  21972. are in-range, so be careful!
  21973. */
  21974. void clear (int startSample,
  21975. int numSamples) throw();
  21976. /** Clears a specified region of just one channel.
  21977. For speed, this doesn't check whether the channel and sample number
  21978. are in-range, so be careful!
  21979. */
  21980. void clear (int channel,
  21981. int startSample,
  21982. int numSamples) throw();
  21983. /** Applies a gain multiple to a region of one channel.
  21984. For speed, this doesn't check whether the channel and sample number
  21985. are in-range, so be careful!
  21986. */
  21987. void applyGain (int channel,
  21988. int startSample,
  21989. int numSamples,
  21990. float gain) throw();
  21991. /** Applies a gain multiple to a region of all the channels.
  21992. For speed, this doesn't check whether the sample numbers
  21993. are in-range, so be careful!
  21994. */
  21995. void applyGain (int startSample,
  21996. int numSamples,
  21997. float gain) throw();
  21998. /** Applies a range of gains to a region of a channel.
  21999. The gain that is applied to each sample will vary from
  22000. startGain on the first sample to endGain on the last Sample,
  22001. so it can be used to do basic fades.
  22002. For speed, this doesn't check whether the sample numbers
  22003. are in-range, so be careful!
  22004. */
  22005. void applyGainRamp (int channel,
  22006. int startSample,
  22007. int numSamples,
  22008. float startGain,
  22009. float endGain) throw();
  22010. /** Adds samples from another buffer to this one.
  22011. @param destChannel the channel within this buffer to add the samples to
  22012. @param destStartSample the start sample within this buffer's channel
  22013. @param source the source buffer to add from
  22014. @param sourceChannel the channel within the source buffer to read from
  22015. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  22016. @param numSamples the number of samples to process
  22017. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  22018. added to this buffer's samples
  22019. @see copyFrom
  22020. */
  22021. void addFrom (int destChannel,
  22022. int destStartSample,
  22023. const AudioSampleBuffer& source,
  22024. int sourceChannel,
  22025. int sourceStartSample,
  22026. int numSamples,
  22027. float gainToApplyToSource = 1.0f) throw();
  22028. /** Adds samples from an array of floats to one of the channels.
  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 data to use
  22032. @param numSamples the number of samples to process
  22033. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  22034. added to this buffer's samples
  22035. @see copyFrom
  22036. */
  22037. void addFrom (int destChannel,
  22038. int destStartSample,
  22039. const float* source,
  22040. int numSamples,
  22041. float gainToApplyToSource = 1.0f) throw();
  22042. /** Adds samples from an array of floats, applying a gain ramp to them.
  22043. @param destChannel the channel within this buffer to add the samples to
  22044. @param destStartSample the start sample within this buffer's channel
  22045. @param source the source data to use
  22046. @param numSamples the number of samples to process
  22047. @param startGain the gain to apply to the first sample (this is multiplied with
  22048. the source samples before they are added to this buffer)
  22049. @param endGain the gain to apply to the final sample. The gain is linearly
  22050. interpolated between the first and last samples.
  22051. */
  22052. void addFromWithRamp (int destChannel,
  22053. int destStartSample,
  22054. const float* source,
  22055. int numSamples,
  22056. float startGain,
  22057. float endGain) throw();
  22058. /** Copies samples from another buffer to this one.
  22059. @param destChannel the channel within this buffer to copy the samples to
  22060. @param destStartSample the start sample within this buffer's channel
  22061. @param source the source buffer to read from
  22062. @param sourceChannel the channel within the source buffer to read from
  22063. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  22064. @param numSamples the number of samples to process
  22065. @see addFrom
  22066. */
  22067. void copyFrom (int destChannel,
  22068. int destStartSample,
  22069. const AudioSampleBuffer& source,
  22070. int sourceChannel,
  22071. int sourceStartSample,
  22072. int numSamples) throw();
  22073. /** Copies samples from an array of floats into one of the channels.
  22074. @param destChannel the channel within this buffer to copy the samples to
  22075. @param destStartSample the start sample within this buffer's channel
  22076. @param source the source buffer to read from
  22077. @param numSamples the number of samples to process
  22078. @see addFrom
  22079. */
  22080. void copyFrom (int destChannel,
  22081. int destStartSample,
  22082. const float* source,
  22083. int numSamples) throw();
  22084. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  22085. @param destChannel the channel within this buffer to copy the samples to
  22086. @param destStartSample the start sample within this buffer's channel
  22087. @param source the source buffer to read from
  22088. @param numSamples the number of samples to process
  22089. @param gain the gain to apply
  22090. @see addFrom
  22091. */
  22092. void copyFrom (int destChannel,
  22093. int destStartSample,
  22094. const float* source,
  22095. int numSamples,
  22096. float gain) throw();
  22097. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  22098. @param destChannel the channel within this buffer to copy the samples to
  22099. @param destStartSample the start sample within this buffer's channel
  22100. @param source the source buffer to read from
  22101. @param numSamples the number of samples to process
  22102. @param startGain the gain to apply to the first sample (this is multiplied with
  22103. the source samples before they are copied to this buffer)
  22104. @param endGain the gain to apply to the final sample. The gain is linearly
  22105. interpolated between the first and last samples.
  22106. @see addFrom
  22107. */
  22108. void copyFromWithRamp (int destChannel,
  22109. int destStartSample,
  22110. const float* source,
  22111. int numSamples,
  22112. float startGain,
  22113. float endGain) throw();
  22114. /** Finds the highest and lowest sample values in a given range.
  22115. @param channel the channel to read from
  22116. @param startSample the start sample within the channel
  22117. @param numSamples the number of samples to check
  22118. @param minVal on return, the lowest value that was found
  22119. @param maxVal on return, the highest value that was found
  22120. */
  22121. void findMinMax (int channel,
  22122. int startSample,
  22123. int numSamples,
  22124. float& minVal,
  22125. float& maxVal) const throw();
  22126. /** Finds the highest absolute sample value within a region of a channel.
  22127. */
  22128. float getMagnitude (int channel,
  22129. int startSample,
  22130. int numSamples) const throw();
  22131. /** Finds the highest absolute sample value within a region on all channels.
  22132. */
  22133. float getMagnitude (int startSample,
  22134. int numSamples) const throw();
  22135. /** Returns the root mean squared level for a region of a channel.
  22136. */
  22137. float getRMSLevel (int channel,
  22138. int startSample,
  22139. int numSamples) const throw();
  22140. /** Fills a section of the buffer using an AudioReader as its source.
  22141. This will convert the reader's fixed- or floating-point data to
  22142. the buffer's floating-point format, and will try to intelligently
  22143. cope with mismatches between the number of channels in the reader
  22144. and the buffer.
  22145. @see writeToAudioWriter
  22146. */
  22147. void readFromAudioReader (AudioFormatReader* reader,
  22148. int startSample,
  22149. int numSamples,
  22150. int readerStartSample,
  22151. bool useReaderLeftChan,
  22152. bool useReaderRightChan) throw();
  22153. /** Writes a section of this buffer to an audio writer.
  22154. This saves you having to mess about with channels or floating/fixed
  22155. point conversion.
  22156. @see readFromAudioReader
  22157. */
  22158. void writeToAudioWriter (AudioFormatWriter* writer,
  22159. int startSample,
  22160. int numSamples) const throw();
  22161. juce_UseDebuggingNewOperator
  22162. private:
  22163. int numChannels, size;
  22164. size_t allocatedBytes;
  22165. float** channels;
  22166. HeapBlock <char> allocatedData;
  22167. float* preallocatedChannelSpace [32];
  22168. void allocateData();
  22169. void allocateChannels (float** dataToReferTo);
  22170. };
  22171. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  22172. /*** End of inlined file: juce_AudioSampleBuffer.h ***/
  22173. /**
  22174. Used by AudioSource::getNextAudioBlock().
  22175. */
  22176. struct JUCE_API AudioSourceChannelInfo
  22177. {
  22178. /** The destination buffer to fill with audio data.
  22179. When the AudioSource::getNextAudioBlock() method is called, the active section
  22180. of this buffer should be filled with whatever output the source produces.
  22181. Only the samples specified by the startSample and numSamples members of this structure
  22182. should be affected by the call.
  22183. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  22184. method can be treated as the input if the source is performing some kind of filter operation,
  22185. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  22186. a handy way of doing this.
  22187. The number of channels in the buffer could be anything, so the AudioSource
  22188. must cope with this in whatever way is appropriate for its function.
  22189. */
  22190. AudioSampleBuffer* buffer;
  22191. /** The first sample in the buffer from which the callback is expected
  22192. to write data. */
  22193. int startSample;
  22194. /** The number of samples in the buffer which the callback is expected to
  22195. fill with data. */
  22196. int numSamples;
  22197. /** Convenient method to clear the buffer if the source is not producing any data. */
  22198. void clearActiveBufferRegion() const
  22199. {
  22200. if (buffer != 0)
  22201. buffer->clear (startSample, numSamples);
  22202. }
  22203. };
  22204. /**
  22205. Base class for objects that can produce a continuous stream of audio.
  22206. @see AudioFormatReaderSource, ResamplingAudioSource
  22207. */
  22208. class JUCE_API AudioSource
  22209. {
  22210. protected:
  22211. /** Creates an AudioSource. */
  22212. AudioSource() throw() {}
  22213. public:
  22214. /** Destructor. */
  22215. virtual ~AudioSource() {}
  22216. /** Tells the source to prepare for playing.
  22217. The source can use this opportunity to initialise anything it needs to.
  22218. Note that this method could be called more than once in succession without
  22219. a matching call to releaseResources(), so make sure your code is robust and
  22220. can handle that kind of situation.
  22221. @param samplesPerBlockExpected the number of samples that the source
  22222. will be expected to supply each time its
  22223. getNextAudioBlock() method is called. This
  22224. number may vary slightly, because it will be dependent
  22225. on audio hardware callbacks, and these aren't
  22226. guaranteed to always use a constant block size, so
  22227. the source should be able to cope with small variations.
  22228. @param sampleRate the sample rate that the output will be used at - this
  22229. is needed by sources such as tone generators.
  22230. @see releaseResources, getNextAudioBlock
  22231. */
  22232. virtual void prepareToPlay (int samplesPerBlockExpected,
  22233. double sampleRate) = 0;
  22234. /** Allows the source to release anything it no longer needs after playback has stopped.
  22235. This will be called when the source is no longer going to have its getNextAudioBlock()
  22236. method called, so it should release any spare memory, etc. that it might have
  22237. allocated during the prepareToPlay() call.
  22238. Note that there's no guarantee that prepareToPlay() will actually have been called before
  22239. releaseResources(), and it may be called more than once in succession, so make sure your
  22240. code is robust and doesn't make any assumptions about when it will be called.
  22241. @see prepareToPlay, getNextAudioBlock
  22242. */
  22243. virtual void releaseResources() = 0;
  22244. /** Called repeatedly to fetch subsequent blocks of audio data.
  22245. After calling the prepareToPlay() method, this callback will be made each
  22246. time the audio playback hardware (or whatever other destination the audio
  22247. data is going to) needs another block of data.
  22248. It will generally be called on a high-priority system thread, or possibly even
  22249. an interrupt, so be careful not to do too much work here, as that will cause
  22250. audio glitches!
  22251. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  22252. */
  22253. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  22254. };
  22255. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  22256. /*** End of inlined file: juce_AudioSource.h ***/
  22257. /**
  22258. Writes samples to an audio file stream.
  22259. A subclass that writes a specific type of audio format will be created by
  22260. an AudioFormat object.
  22261. After creating one of these with the AudioFormat::createWriterFor() method
  22262. you can call its write() method to store the samples, and then delete it.
  22263. @see AudioFormat, AudioFormatReader
  22264. */
  22265. class JUCE_API AudioFormatWriter
  22266. {
  22267. protected:
  22268. /** Creates an AudioFormatWriter object.
  22269. @param destStream the stream to write to - this will be deleted
  22270. by this object when it is no longer needed
  22271. @param formatName the description that will be returned by the getFormatName()
  22272. method
  22273. @param sampleRate the sample rate to use - the base class just stores
  22274. this value, it doesn't do anything with it
  22275. @param numberOfChannels the number of channels to write - the base class just stores
  22276. this value, it doesn't do anything with it
  22277. @param bitsPerSample the bit depth of the stream - the base class just stores
  22278. this value, it doesn't do anything with it
  22279. */
  22280. AudioFormatWriter (OutputStream* destStream,
  22281. const String& formatName,
  22282. double sampleRate,
  22283. unsigned int numberOfChannels,
  22284. unsigned int bitsPerSample);
  22285. public:
  22286. /** Destructor. */
  22287. virtual ~AudioFormatWriter();
  22288. /** Returns a description of what type of format this is.
  22289. E.g. "AIFF file"
  22290. */
  22291. const String getFormatName() const throw() { return formatName; }
  22292. /** Writes a set of samples to the audio stream.
  22293. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  22294. can use AudioSampleBuffer::writeToAudioWriter().
  22295. @param samplesToWrite an array of arrays containing the sample data for
  22296. each channel to write. This is a zero-terminated
  22297. array of arrays, and can contain a different number
  22298. of channels than the actual stream uses, and the
  22299. writer should do its best to cope with this.
  22300. If the format is fixed-point, each channel will be formatted
  22301. as an array of signed integers using the full 32-bit
  22302. range -0x80000000 to 0x7fffffff, regardless of the source's
  22303. bit-depth. If it is a floating-point format, you should treat
  22304. the arrays as arrays of floats, and just cast it to an (int**)
  22305. to pass it into the method.
  22306. @param numSamples the number of samples to write
  22307. */
  22308. virtual bool write (const int** samplesToWrite,
  22309. int numSamples) = 0;
  22310. /** Reads a section of samples from an AudioFormatReader, and writes these to
  22311. the output.
  22312. This will take care of any floating-point conversion that's required to convert
  22313. between the two formats. It won't deal with sample-rate conversion, though.
  22314. If numSamplesToRead < 0, it will write the entire length of the reader.
  22315. @returns false if it can't read or write properly during the operation
  22316. */
  22317. bool writeFromAudioReader (AudioFormatReader& reader,
  22318. int64 startSample,
  22319. int64 numSamplesToRead);
  22320. /** Reads some samples from an AudioSource, and writes these to the output.
  22321. The source must already have been initialised with the AudioSource::prepareToPlay() method
  22322. @param source the source to read from
  22323. @param numSamplesToRead total number of samples to read and write
  22324. @param samplesPerBlock the maximum number of samples to fetch from the source
  22325. @returns false if it can't read or write properly during the operation
  22326. */
  22327. bool writeFromAudioSource (AudioSource& source,
  22328. int numSamplesToRead,
  22329. int samplesPerBlock = 2048);
  22330. /** Returns the sample rate being used. */
  22331. double getSampleRate() const throw() { return sampleRate; }
  22332. /** Returns the number of channels being written. */
  22333. int getNumChannels() const throw() { return numChannels; }
  22334. /** Returns the bit-depth of the data being written. */
  22335. int getBitsPerSample() const throw() { return bitsPerSample; }
  22336. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  22337. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  22338. juce_UseDebuggingNewOperator
  22339. protected:
  22340. /** The sample rate of the stream. */
  22341. double sampleRate;
  22342. /** The number of channels being written to the stream. */
  22343. unsigned int numChannels;
  22344. /** The bit depth of the file. */
  22345. unsigned int bitsPerSample;
  22346. /** True if it's a floating-point format, false if it's fixed-point. */
  22347. bool usesFloatingPointData;
  22348. /** The output stream for Use by subclasses. */
  22349. OutputStream* output;
  22350. private:
  22351. String formatName;
  22352. AudioFormatWriter (const AudioFormatWriter&);
  22353. AudioFormatWriter& operator= (const AudioFormatWriter&);
  22354. };
  22355. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  22356. /*** End of inlined file: juce_AudioFormatWriter.h ***/
  22357. /**
  22358. Subclasses of AudioFormat are used to read and write different audio
  22359. file formats.
  22360. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  22361. */
  22362. class JUCE_API AudioFormat
  22363. {
  22364. public:
  22365. /** Destructor. */
  22366. virtual ~AudioFormat();
  22367. /** Returns the name of this format.
  22368. e.g. "WAV file" or "AIFF file"
  22369. */
  22370. const String& getFormatName() const;
  22371. /** Returns all the file extensions that might apply to a file of this format.
  22372. The first item will be the one that's preferred when creating a new file.
  22373. So for a wav file this might just return ".wav"; for an AIFF file it might
  22374. return two items, ".aif" and ".aiff"
  22375. */
  22376. const StringArray& getFileExtensions() const;
  22377. /** Returns true if this the given file can be read by this format.
  22378. Subclasses shouldn't do too much work here, just check the extension or
  22379. file type. The base class implementation just checks the file's extension
  22380. against one of the ones that was registered in the constructor.
  22381. */
  22382. virtual bool canHandleFile (const File& fileToTest);
  22383. /** Returns a set of sample rates that the format can read and write. */
  22384. virtual const Array <int> getPossibleSampleRates() = 0;
  22385. /** Returns a set of bit depths that the format can read and write. */
  22386. virtual const Array <int> getPossibleBitDepths() = 0;
  22387. /** Returns true if the format can do 2-channel audio. */
  22388. virtual bool canDoStereo() = 0;
  22389. /** Returns true if the format can do 1-channel audio. */
  22390. virtual bool canDoMono() = 0;
  22391. /** Returns true if the format uses compressed data. */
  22392. virtual bool isCompressed();
  22393. /** Returns a list of different qualities that can be used when writing.
  22394. Non-compressed formats will just return an empty array, but for something
  22395. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  22396. When calling createWriterFor(), an index from this array is passed in to
  22397. tell the format which option is required.
  22398. */
  22399. virtual const StringArray getQualityOptions();
  22400. /** Tries to create an object that can read from a stream containing audio
  22401. data in this format.
  22402. The reader object that is returned can be used to read from the stream, and
  22403. should then be deleted by the caller.
  22404. @param sourceStream the stream to read from - the AudioFormatReader object
  22405. that is returned will delete this stream when it no longer
  22406. needs it.
  22407. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  22408. should delete the stream object that was passed-in. (If a valid
  22409. reader is returned, it will always be in charge of deleting the
  22410. stream, so this parameter is ignored)
  22411. @see AudioFormatReader
  22412. */
  22413. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  22414. const bool deleteStreamIfOpeningFails) = 0;
  22415. /** Tries to create an object that can write to a stream with this audio format.
  22416. The writer object that is returned can be used to write to the stream, and
  22417. should then be deleted by the caller.
  22418. If the stream can't be created for some reason (e.g. the parameters passed in
  22419. here aren't suitable), this will return 0.
  22420. @param streamToWriteTo the stream that the data will go to - this will be
  22421. deleted by the AudioFormatWriter object when it's no longer
  22422. needed. If no AudioFormatWriter can be created by this method,
  22423. the stream will NOT be deleted, so that the caller can re-use it
  22424. to try to open a different format, etc
  22425. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  22426. returned by getPossibleSampleRates()
  22427. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  22428. the choice will depend on the results of canDoMono() and
  22429. canDoStereo()
  22430. @param bitsPerSample the bits per sample to use - this must be one of the values
  22431. returned by getPossibleBitDepths()
  22432. @param metadataValues a set of metadata values that the writer should try to write
  22433. to the stream. Exactly what these are depends on the format,
  22434. and the subclass doesn't actually have to do anything with
  22435. them if it doesn't want to. Have a look at the specific format
  22436. implementation classes to see possible values that can be
  22437. used
  22438. @param qualityOptionIndex the index of one of compression qualities returned by the
  22439. getQualityOptions() method. If there aren't any quality options
  22440. for this format, just pass 0 in this parameter, as it'll be
  22441. ignored
  22442. @see AudioFormatWriter
  22443. */
  22444. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  22445. double sampleRateToUse,
  22446. unsigned int numberOfChannels,
  22447. int bitsPerSample,
  22448. const StringPairArray& metadataValues,
  22449. int qualityOptionIndex) = 0;
  22450. protected:
  22451. /** Creates an AudioFormat object.
  22452. @param formatName this sets the value that will be returned by getFormatName()
  22453. @param fileExtensions a zero-terminated list of file extensions - this is what will
  22454. be returned by getFileExtension()
  22455. */
  22456. AudioFormat (const String& formatName,
  22457. const StringArray& fileExtensions);
  22458. private:
  22459. String formatName;
  22460. StringArray fileExtensions;
  22461. };
  22462. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  22463. /*** End of inlined file: juce_AudioFormat.h ***/
  22464. /**
  22465. Reads and Writes AIFF format audio files.
  22466. @see AudioFormat
  22467. */
  22468. class JUCE_API AiffAudioFormat : public AudioFormat
  22469. {
  22470. public:
  22471. /** Creates an format object. */
  22472. AiffAudioFormat();
  22473. /** Destructor. */
  22474. ~AiffAudioFormat();
  22475. const Array <int> getPossibleSampleRates();
  22476. const Array <int> getPossibleBitDepths();
  22477. bool canDoStereo();
  22478. bool canDoMono();
  22479. #if JUCE_MAC
  22480. bool canHandleFile (const File& fileToTest);
  22481. #endif
  22482. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  22483. const bool deleteStreamIfOpeningFails);
  22484. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  22485. double sampleRateToUse,
  22486. unsigned int numberOfChannels,
  22487. int bitsPerSample,
  22488. const StringPairArray& metadataValues,
  22489. int qualityOptionIndex);
  22490. juce_UseDebuggingNewOperator
  22491. };
  22492. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  22493. /*** End of inlined file: juce_AiffAudioFormat.h ***/
  22494. #endif
  22495. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22496. /*** Start of inlined file: juce_AudioCDBurner.h ***/
  22497. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22498. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22499. #if JUCE_USE_CDBURNER
  22500. /**
  22501. */
  22502. class AudioCDBurner : public ChangeBroadcaster
  22503. {
  22504. public:
  22505. /** Returns a list of available optical drives.
  22506. Use openDevice() to open one of the items from this list.
  22507. */
  22508. static const StringArray findAvailableDevices();
  22509. /** Tries to open one of the optical drives.
  22510. The deviceIndex is an index into the array returned by findAvailableDevices().
  22511. */
  22512. static AudioCDBurner* openDevice (const int deviceIndex);
  22513. /** Destructor. */
  22514. ~AudioCDBurner();
  22515. enum DiskState
  22516. {
  22517. unknown, /**< An error condition, if the device isn't responding. */
  22518. trayOpen, /**< The drive is currently open. Note that a slot-loading drive
  22519. may seem to be permanently open. */
  22520. noDisc, /**< The drive has no disk in it. */
  22521. writableDiskPresent, /**< The drive contains a writeable disk. */
  22522. readOnlyDiskPresent /**< The drive contains a read-only disk. */
  22523. };
  22524. /** Returns the current status of the device.
  22525. To get informed when the drive's status changes, attach a ChangeListener to
  22526. the AudioCDBurner.
  22527. */
  22528. DiskState getDiskState() const;
  22529. /** Returns true if there's a writable disk in the drive. */
  22530. bool isDiskPresent() const;
  22531. /** Sends an eject signal to the drive.
  22532. The eject will happen asynchronously, so you can use getDiskState() and
  22533. waitUntilStateChange() to monitor its progress.
  22534. */
  22535. bool openTray();
  22536. /** Blocks the current thread until the drive's state changes, or until the timeout expires.
  22537. @returns the device's new state
  22538. */
  22539. DiskState waitUntilStateChange (int timeOutMilliseconds);
  22540. /** Returns the set of possible write speeds that the device can handle.
  22541. These are as a multiple of 'normal' speed, so e.g. '24x' returns 24, etc.
  22542. Note that if there's no media present in the drive, this value may be unavailable!
  22543. @see setWriteSpeed, getWriteSpeed
  22544. */
  22545. const Array<int> getAvailableWriteSpeeds() const;
  22546. /** Tries to enable or disable buffer underrun safety on devices that support it.
  22547. @returns true if it's now enabled. If the device doesn't support it, this
  22548. will always return false.
  22549. */
  22550. bool setBufferUnderrunProtection (const bool shouldBeEnabled);
  22551. /** Returns the number of free blocks on the disk.
  22552. There are 75 blocks per second, at 44100Hz.
  22553. */
  22554. int getNumAvailableAudioBlocks() const;
  22555. /** Adds a track to be written.
  22556. The source passed-in here will be kept by this object, and it will
  22557. be used and deleted at some point in the future, either during the
  22558. burn() method or when this AudioCDBurner object is deleted. Your caller
  22559. method shouldn't keep a reference to it or use it again after passing
  22560. it in here.
  22561. */
  22562. bool addAudioTrack (AudioSource* source, int numSamples);
  22563. /** Receives progress callbacks during a cd-burn operation.
  22564. @see AudioCDBurner::burn()
  22565. */
  22566. class BurnProgressListener
  22567. {
  22568. public:
  22569. BurnProgressListener() throw() {}
  22570. virtual ~BurnProgressListener() {}
  22571. /** Called at intervals to report on the progress of the AudioCDBurner.
  22572. To cancel the burn, return true from this method.
  22573. */
  22574. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  22575. };
  22576. /** Runs the burn process.
  22577. This method will block until the operation is complete.
  22578. @param listener the object to receive callbacks about progress
  22579. @param ejectDiscAfterwards whether to eject the disk after the burn completes
  22580. @param performFakeBurnForTesting if true, no data will actually be written to the disk
  22581. @param writeSpeed one of the write speeds from getAvailableWriteSpeeds(), or
  22582. 0 or less to mean the fastest speed.
  22583. */
  22584. const String burn (BurnProgressListener* listener,
  22585. bool ejectDiscAfterwards,
  22586. bool performFakeBurnForTesting,
  22587. int writeSpeed);
  22588. /** If a burn operation is currently in progress, this tells it to stop
  22589. as soon as possible.
  22590. It's also possible to stop the burn process by returning true from
  22591. BurnProgressListener::audioCDBurnProgress()
  22592. */
  22593. void abortBurn();
  22594. juce_UseDebuggingNewOperator
  22595. private:
  22596. AudioCDBurner (const int deviceIndex);
  22597. class Pimpl;
  22598. friend class ScopedPointer<Pimpl>;
  22599. ScopedPointer<Pimpl> pimpl;
  22600. };
  22601. #endif
  22602. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22603. /*** End of inlined file: juce_AudioCDBurner.h ***/
  22604. #endif
  22605. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  22606. /*** Start of inlined file: juce_AudioCDReader.h ***/
  22607. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  22608. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  22609. #if JUCE_USE_CDREADER
  22610. #if JUCE_MAC
  22611. #endif
  22612. /**
  22613. A type of AudioFormatReader that reads from an audio CD.
  22614. One of these can be used to read a CD as if it's one big audio stream. Use the
  22615. getPositionOfTrackStart() method to find where the individual tracks are
  22616. within the stream.
  22617. @see AudioFormatReader
  22618. */
  22619. class JUCE_API AudioCDReader : public AudioFormatReader
  22620. {
  22621. public:
  22622. /** Returns a list of names of Audio CDs currently available for reading.
  22623. If there's a CD drive but no CD in it, this might return an empty list, or
  22624. possibly a device that can be opened but which has no tracks, depending
  22625. on the platform.
  22626. @see createReaderForCD
  22627. */
  22628. static const StringArray getAvailableCDNames();
  22629. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  22630. @param index the index of one of the available CDs - use getAvailableCDNames()
  22631. to find out how many there are.
  22632. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  22633. caller will be responsible for deleting the object returned.
  22634. */
  22635. static AudioCDReader* createReaderForCD (const int index);
  22636. /** Destructor. */
  22637. ~AudioCDReader();
  22638. /** Implementation of the AudioFormatReader method. */
  22639. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  22640. int64 startSampleInFile, int numSamples);
  22641. /** Checks whether the CD has been removed from the drive.
  22642. */
  22643. bool isCDStillPresent() const;
  22644. /** Returns the total number of tracks (audio + data).
  22645. */
  22646. int getNumTracks() const;
  22647. /** Finds the sample offset of the start of a track.
  22648. @param trackNum the track number, where 0 is the first track.
  22649. */
  22650. int getPositionOfTrackStart (int trackNum) const;
  22651. /** Returns true if a given track is an audio track.
  22652. @param trackNum the track number, where 0 is the first track.
  22653. */
  22654. bool isTrackAudio (int trackNum) const;
  22655. /** Refreshes the object's table of contents.
  22656. If the disc has been ejected and a different one put in since this
  22657. object was created, this will cause it to update its idea of how many tracks
  22658. there are, etc.
  22659. */
  22660. void refreshTrackLengths();
  22661. /** Enables scanning for indexes within tracks.
  22662. @see getLastIndex
  22663. */
  22664. void enableIndexScanning (bool enabled);
  22665. /** Returns the index number found during the last read() call.
  22666. Index scanning is turned off by default - turn it on with enableIndexScanning().
  22667. Then when the read() method is called, if it comes across an index within that
  22668. block, the index number is stored and returned by this method.
  22669. Some devices might not support indexes, of course.
  22670. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  22671. @see enableIndexScanning
  22672. */
  22673. int getLastIndex() const;
  22674. /** Scans a track to find the position of any indexes within it.
  22675. @param trackNumber the track to look in, where 0 is the first track on the disc
  22676. @returns an array of sample positions of any index points found (not including
  22677. the index that marks the start of the track)
  22678. */
  22679. const Array <int> findIndexesInTrack (const int trackNumber);
  22680. /** Returns the CDDB id number for the CD.
  22681. It's not a great way of identifying a disc, but it's traditional.
  22682. */
  22683. int getCDDBId();
  22684. /** Tries to eject the disk.
  22685. Of course this might not be possible, if some other process is using it.
  22686. */
  22687. void ejectDisk();
  22688. juce_UseDebuggingNewOperator
  22689. private:
  22690. #if JUCE_MAC
  22691. File volumeDir;
  22692. Array<File> tracks;
  22693. Array<int> trackStartSamples;
  22694. int currentReaderTrack;
  22695. ScopedPointer <AudioFormatReader> reader;
  22696. AudioCDReader (const File& volume);
  22697. public:
  22698. static int compareElements (const File&, const File&);
  22699. private:
  22700. #elif JUCE_WINDOWS
  22701. int numTracks;
  22702. int trackStarts[100];
  22703. bool audioTracks [100];
  22704. void* handle;
  22705. bool indexingEnabled;
  22706. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  22707. MemoryBlock buffer;
  22708. AudioCDReader (void* handle);
  22709. int getIndexAt (int samplePos);
  22710. #elif JUCE_LINUX
  22711. AudioCDReader();
  22712. #endif
  22713. AudioCDReader (const AudioCDReader&);
  22714. AudioCDReader& operator= (const AudioCDReader&);
  22715. };
  22716. #endif
  22717. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  22718. /*** End of inlined file: juce_AudioCDReader.h ***/
  22719. #endif
  22720. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  22721. #endif
  22722. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  22723. /*** Start of inlined file: juce_AudioFormatManager.h ***/
  22724. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  22725. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  22726. /**
  22727. A class for keeping a list of available audio formats, and for deciding which
  22728. one to use to open a given file.
  22729. You can either use this class as a singleton object, or create instances of it
  22730. yourself. Once created, use its registerFormat() method to tell it which
  22731. formats it should use.
  22732. @see AudioFormat
  22733. */
  22734. class JUCE_API AudioFormatManager
  22735. {
  22736. public:
  22737. /** Creates an empty format manager.
  22738. Before it'll be any use, you'll need to call registerFormat() with all the
  22739. formats you want it to be able to recognise.
  22740. */
  22741. AudioFormatManager();
  22742. /** Destructor. */
  22743. ~AudioFormatManager();
  22744. juce_DeclareSingleton (AudioFormatManager, false);
  22745. /** Adds a format to the manager's list of available file types.
  22746. The object passed-in will be deleted by this object, so don't keep a pointer
  22747. to it!
  22748. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  22749. return this one when called.
  22750. */
  22751. void registerFormat (AudioFormat* newFormat,
  22752. bool makeThisTheDefaultFormat);
  22753. /** Handy method to make it easy to register the formats that come with Juce.
  22754. Currently, this will add WAV and AIFF to the list.
  22755. */
  22756. void registerBasicFormats();
  22757. /** Clears the list of known formats. */
  22758. void clearFormats();
  22759. /** Returns the number of currently registered file formats. */
  22760. int getNumKnownFormats() const;
  22761. /** Returns one of the registered file formats. */
  22762. AudioFormat* getKnownFormat (int index) const;
  22763. /** Looks for which of the known formats is listed as being for a given file
  22764. extension.
  22765. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  22766. */
  22767. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  22768. /** Returns the format which has been set as the default one.
  22769. You can set a format as being the default when it is registered. It's useful
  22770. when you want to write to a file, because the best format may change between
  22771. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  22772. If none has been set as the default, this method will just return the first
  22773. one in the list.
  22774. */
  22775. AudioFormat* getDefaultFormat() const;
  22776. /** Returns a set of wildcards for file-matching that contains the extensions for
  22777. all known formats.
  22778. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  22779. */
  22780. const String getWildcardForAllFormats() const;
  22781. /** Searches through the known formats to try to create a suitable reader for
  22782. this file.
  22783. If none of the registered formats can open the file, it'll return 0. If it
  22784. returns a reader, it's the caller's responsibility to delete the reader.
  22785. */
  22786. AudioFormatReader* createReaderFor (const File& audioFile);
  22787. /** Searches through the known formats to try to create a suitable reader for
  22788. this stream.
  22789. The stream object that is passed-in will be deleted by this method or by the
  22790. reader that is returned, so the caller should not keep any references to it.
  22791. The stream that is passed-in must be capable of being repositioned so
  22792. that all the formats can have a go at opening it.
  22793. If none of the registered formats can open the stream, it'll return 0. If it
  22794. returns a reader, it's the caller's responsibility to delete the reader.
  22795. */
  22796. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  22797. juce_UseDebuggingNewOperator
  22798. private:
  22799. OwnedArray<AudioFormat> knownFormats;
  22800. int defaultFormatIndex;
  22801. };
  22802. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  22803. /*** End of inlined file: juce_AudioFormatManager.h ***/
  22804. #endif
  22805. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  22806. #endif
  22807. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  22808. #endif
  22809. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  22810. /*** Start of inlined file: juce_AudioSubsectionReader.h ***/
  22811. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  22812. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  22813. /**
  22814. This class is used to wrap an AudioFormatReader and only read from a
  22815. subsection of the file.
  22816. So if you have a reader which can read a 1000 sample file, you could wrap it
  22817. in one of these to only access, e.g. samples 100 to 200, and any samples
  22818. outside that will come back as 0. Accessing sample 0 from this reader will
  22819. actually read the first sample from the other's subsection, which might
  22820. be at a non-zero position.
  22821. @see AudioFormatReader
  22822. */
  22823. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  22824. {
  22825. public:
  22826. /** Creates a AudioSubsectionReader for a given data source.
  22827. @param sourceReader the source reader from which we'll be taking data
  22828. @param subsectionStartSample the sample within the source reader which will be
  22829. mapped onto sample 0 for this reader.
  22830. @param subsectionLength the number of samples from the source that will
  22831. make up the subsection. If this reader is asked for
  22832. any samples beyond this region, it will return zero.
  22833. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  22834. this object is deleted.
  22835. */
  22836. AudioSubsectionReader (AudioFormatReader* sourceReader,
  22837. int64 subsectionStartSample,
  22838. int64 subsectionLength,
  22839. bool deleteSourceWhenDeleted);
  22840. /** Destructor. */
  22841. ~AudioSubsectionReader();
  22842. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  22843. int64 startSampleInFile, int numSamples);
  22844. void readMaxLevels (int64 startSample,
  22845. int64 numSamples,
  22846. float& lowestLeft,
  22847. float& highestLeft,
  22848. float& lowestRight,
  22849. float& highestRight);
  22850. juce_UseDebuggingNewOperator
  22851. private:
  22852. AudioFormatReader* const source;
  22853. int64 startSample, length;
  22854. const bool deleteSourceWhenDeleted;
  22855. AudioSubsectionReader (const AudioSubsectionReader&);
  22856. AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  22857. };
  22858. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  22859. /*** End of inlined file: juce_AudioSubsectionReader.h ***/
  22860. #endif
  22861. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  22862. /*** Start of inlined file: juce_AudioThumbnail.h ***/
  22863. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  22864. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  22865. class AudioThumbnailCache;
  22866. /**
  22867. Makes it easy to quickly draw scaled views of the waveform shape of an
  22868. audio file.
  22869. To use this class, just create an AudioThumbNail class for the file you want
  22870. to draw, call setSource to tell it which file or resource to use, then call
  22871. drawChannel() to draw it.
  22872. The class will asynchronously scan the wavefile to create its scaled-down view,
  22873. so you should make your UI repaint itself as this data comes in. To do this, the
  22874. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  22875. listeners should repaint themselves.
  22876. The thumbnail stores an internal low-res version of the wave data, and this can
  22877. be loaded and saved to avoid having to scan the file again.
  22878. @see AudioThumbnailCache
  22879. */
  22880. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  22881. public TimeSliceClient,
  22882. private Timer
  22883. {
  22884. public:
  22885. /** Creates an audio thumbnail.
  22886. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  22887. of the audio data, this is the scale at which it should be done. (This
  22888. number is the number of original samples that will be averaged for each
  22889. low-res sample)
  22890. @param formatManagerToUse the audio format manager that is used to open the file
  22891. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  22892. thread and storage that is used to by the thumbnail, and the cache
  22893. object can be shared between multiple thumbnails
  22894. */
  22895. AudioThumbnail (int sourceSamplesPerThumbnailSample,
  22896. AudioFormatManager& formatManagerToUse,
  22897. AudioThumbnailCache& cacheToUse);
  22898. /** Destructor. */
  22899. ~AudioThumbnail();
  22900. /** Specifies the file or stream that contains the audio file.
  22901. For a file, just call
  22902. @code
  22903. setSource (new FileInputSource (file))
  22904. @endcode
  22905. You can pass a zero in here to clear the thumbnail.
  22906. The source that is passed in will be deleted by this object when it is no
  22907. longer needed
  22908. */
  22909. void setSource (InputSource* newSource);
  22910. /** Reloads the low res thumbnail data from an input stream.
  22911. The thumb will automatically attempt to reload itself from its
  22912. AudioThumbnailCache.
  22913. */
  22914. void loadFrom (InputStream& input);
  22915. /** Saves the low res thumbnail data to an output stream.
  22916. The thumb will automatically attempt to save itself to its
  22917. AudioThumbnailCache after it finishes scanning the wave file.
  22918. */
  22919. void saveTo (OutputStream& output) const;
  22920. /** Returns the number of channels in the file.
  22921. */
  22922. int getNumChannels() const throw();
  22923. /** Returns the length of the audio file, in seconds.
  22924. */
  22925. double getTotalLength() const throw();
  22926. /** Renders the waveform shape for a channel.
  22927. The waveform will be drawn within the specified rectangle, where startTime
  22928. and endTime specify the times within the audio file that should be positioned
  22929. at the left and right edges of the rectangle.
  22930. The waveform will be scaled vertically so that a full-volume sample will fill
  22931. the rectangle vertically, but you can also specify an extra vertical scale factor
  22932. with the verticalZoomFactor parameter.
  22933. */
  22934. void drawChannel (Graphics& g,
  22935. int x, int y, int w, int h,
  22936. double startTimeSeconds,
  22937. double endTimeSeconds,
  22938. int channelNum,
  22939. float verticalZoomFactor);
  22940. /** Returns true if the low res preview is fully generated.
  22941. */
  22942. bool isFullyLoaded() const throw();
  22943. /** @internal */
  22944. bool useTimeSlice();
  22945. /** @internal */
  22946. void timerCallback();
  22947. juce_UseDebuggingNewOperator
  22948. private:
  22949. AudioFormatManager& formatManagerToUse;
  22950. AudioThumbnailCache& cache;
  22951. ScopedPointer <InputSource> source;
  22952. CriticalSection readerLock;
  22953. ScopedPointer <AudioFormatReader> reader;
  22954. MemoryBlock data, cachedLevels;
  22955. int orginalSamplesPerThumbnailSample;
  22956. int numChannelsCached, numSamplesCached;
  22957. double cachedStart, cachedTimePerPixel;
  22958. bool cacheNeedsRefilling;
  22959. void clear();
  22960. AudioFormatReader* createReader() const;
  22961. void generateSection (AudioFormatReader& reader, int64 startSample, int numSamples);
  22962. char* getChannelData (int channel) const;
  22963. void refillCache (int numSamples, double startTime, double timePerPixel);
  22964. friend class AudioThumbnailCache;
  22965. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  22966. bool initialiseFromAudioFile (AudioFormatReader& reader);
  22967. // returns true if more needs to be read
  22968. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  22969. };
  22970. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  22971. /*** End of inlined file: juce_AudioThumbnail.h ***/
  22972. #endif
  22973. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  22974. /*** Start of inlined file: juce_AudioThumbnailCache.h ***/
  22975. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  22976. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  22977. struct ThumbnailCacheEntry;
  22978. /**
  22979. An instance of this class is used to manage multiple AudioThumbnail objects.
  22980. The cache runs a single background thread that is shared by all the thumbnails
  22981. that need it, and it maintains a set of low-res previews in memory, to avoid
  22982. having to re-scan audio files too often.
  22983. @see AudioThumbnail
  22984. */
  22985. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  22986. {
  22987. public:
  22988. /** Creates a cache object.
  22989. The maxNumThumbsToStore parameter lets you specify how many previews should
  22990. be kept in memory at once.
  22991. */
  22992. explicit AudioThumbnailCache (int maxNumThumbsToStore);
  22993. /** Destructor. */
  22994. ~AudioThumbnailCache();
  22995. /** Clears out any stored thumbnails.
  22996. */
  22997. void clear();
  22998. /** Reloads the specified thumb if this cache contains the appropriate stored
  22999. data.
  23000. This is called automatically by the AudioThumbnail class, so you shouldn't
  23001. normally need to call it directly.
  23002. */
  23003. bool loadThumb (AudioThumbnail& thumb, int64 hashCode);
  23004. /** Stores the cachable data from the specified thumb in this cache.
  23005. This is called automatically by the AudioThumbnail class, so you shouldn't
  23006. normally need to call it directly.
  23007. */
  23008. void storeThumb (const AudioThumbnail& thumb, int64 hashCode);
  23009. juce_UseDebuggingNewOperator
  23010. private:
  23011. OwnedArray <ThumbnailCacheEntry> thumbs;
  23012. int maxNumThumbsToStore;
  23013. friend class AudioThumbnail;
  23014. void addThumbnail (AudioThumbnail* thumb);
  23015. void removeThumbnail (AudioThumbnail* thumb);
  23016. };
  23017. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  23018. /*** End of inlined file: juce_AudioThumbnailCache.h ***/
  23019. #endif
  23020. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23021. /*** Start of inlined file: juce_FlacAudioFormat.h ***/
  23022. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23023. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23024. #if JUCE_USE_FLAC || defined (DOXYGEN)
  23025. /**
  23026. Reads and writes the lossless-compression FLAC audio format.
  23027. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  23028. and make sure your include search path and library search path are set up to find
  23029. the FLAC header files and static libraries.
  23030. @see AudioFormat
  23031. */
  23032. class JUCE_API FlacAudioFormat : public AudioFormat
  23033. {
  23034. public:
  23035. FlacAudioFormat();
  23036. ~FlacAudioFormat();
  23037. const Array <int> getPossibleSampleRates();
  23038. const Array <int> getPossibleBitDepths();
  23039. bool canDoStereo();
  23040. bool canDoMono();
  23041. bool isCompressed();
  23042. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23043. const bool deleteStreamIfOpeningFails);
  23044. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23045. double sampleRateToUse,
  23046. unsigned int numberOfChannels,
  23047. int bitsPerSample,
  23048. const StringPairArray& metadataValues,
  23049. int qualityOptionIndex);
  23050. juce_UseDebuggingNewOperator
  23051. };
  23052. #endif
  23053. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23054. /*** End of inlined file: juce_FlacAudioFormat.h ***/
  23055. #endif
  23056. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23057. /*** Start of inlined file: juce_OggVorbisAudioFormat.h ***/
  23058. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23059. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23060. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  23061. /**
  23062. Reads and writes the Ogg-Vorbis audio format.
  23063. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  23064. and make sure your include search path and library search path are set up to find
  23065. the Vorbis and Ogg header files and static libraries.
  23066. @see AudioFormat,
  23067. */
  23068. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  23069. {
  23070. public:
  23071. OggVorbisAudioFormat();
  23072. ~OggVorbisAudioFormat();
  23073. const Array <int> getPossibleSampleRates();
  23074. const Array <int> getPossibleBitDepths();
  23075. bool canDoStereo();
  23076. bool canDoMono();
  23077. bool isCompressed();
  23078. const StringArray getQualityOptions();
  23079. /** Tries to estimate the quality level of an ogg file based on its size.
  23080. If it can't read the file for some reason, this will just return 1 (medium quality),
  23081. otherwise it will return the approximate quality setting that would have been used
  23082. to create the file.
  23083. @see getQualityOptions
  23084. */
  23085. int estimateOggFileQuality (const File& source);
  23086. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23087. const bool deleteStreamIfOpeningFails);
  23088. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23089. double sampleRateToUse,
  23090. unsigned int numberOfChannels,
  23091. int bitsPerSample,
  23092. const StringPairArray& metadataValues,
  23093. int qualityOptionIndex);
  23094. juce_UseDebuggingNewOperator
  23095. };
  23096. #endif
  23097. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23098. /*** End of inlined file: juce_OggVorbisAudioFormat.h ***/
  23099. #endif
  23100. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23101. /*** Start of inlined file: juce_QuickTimeAudioFormat.h ***/
  23102. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23103. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23104. #if JUCE_QUICKTIME
  23105. /**
  23106. Uses QuickTime to read the audio track a movie or media file.
  23107. As well as QuickTime movies, this should also manage to open other audio
  23108. files that quicktime can understand, like mp3, m4a, etc.
  23109. @see AudioFormat
  23110. */
  23111. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  23112. {
  23113. public:
  23114. /** Creates a format object. */
  23115. QuickTimeAudioFormat();
  23116. /** Destructor. */
  23117. ~QuickTimeAudioFormat();
  23118. const Array <int> getPossibleSampleRates();
  23119. const Array <int> getPossibleBitDepths();
  23120. bool canDoStereo();
  23121. bool canDoMono();
  23122. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23123. const bool deleteStreamIfOpeningFails);
  23124. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23125. double sampleRateToUse,
  23126. unsigned int numberOfChannels,
  23127. int bitsPerSample,
  23128. const StringPairArray& metadataValues,
  23129. int qualityOptionIndex);
  23130. juce_UseDebuggingNewOperator
  23131. };
  23132. #endif
  23133. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23134. /*** End of inlined file: juce_QuickTimeAudioFormat.h ***/
  23135. #endif
  23136. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23137. /*** Start of inlined file: juce_WavAudioFormat.h ***/
  23138. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23139. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23140. /**
  23141. Reads and Writes WAV format audio files.
  23142. @see AudioFormat
  23143. */
  23144. class JUCE_API WavAudioFormat : public AudioFormat
  23145. {
  23146. public:
  23147. /** Creates a format object. */
  23148. WavAudioFormat();
  23149. /** Destructor. */
  23150. ~WavAudioFormat();
  23151. /** Metadata property name used by wav readers and writers for adding
  23152. a BWAV chunk to the file.
  23153. @see AudioFormatReader::metadataValues, createWriterFor
  23154. */
  23155. static const char* const bwavDescription;
  23156. /** Metadata property name used by wav readers and writers for adding
  23157. a BWAV chunk to the file.
  23158. @see AudioFormatReader::metadataValues, createWriterFor
  23159. */
  23160. static const char* const bwavOriginator;
  23161. /** Metadata property name used by wav readers and writers for adding
  23162. a BWAV chunk to the file.
  23163. @see AudioFormatReader::metadataValues, createWriterFor
  23164. */
  23165. static const char* const bwavOriginatorRef;
  23166. /** Metadata property name used by wav readers and writers for adding
  23167. a BWAV chunk to the file.
  23168. Date format is: yyyy-mm-dd
  23169. @see AudioFormatReader::metadataValues, createWriterFor
  23170. */
  23171. static const char* const bwavOriginationDate;
  23172. /** Metadata property name used by wav readers and writers for adding
  23173. a BWAV chunk to the file.
  23174. Time format is: hh-mm-ss
  23175. @see AudioFormatReader::metadataValues, createWriterFor
  23176. */
  23177. static const char* const bwavOriginationTime;
  23178. /** Metadata property name used by wav readers and writers for adding
  23179. a BWAV chunk to the file.
  23180. This is the number of samples from the start of an edit that the
  23181. file is supposed to begin at. Seems like an obvious mistake to
  23182. only allow a file to occur in an edit once, but that's the way
  23183. it is..
  23184. @see AudioFormatReader::metadataValues, createWriterFor
  23185. */
  23186. static const char* const bwavTimeReference;
  23187. /** Metadata property name used by wav readers and writers for adding
  23188. a BWAV chunk to the file.
  23189. This is a
  23190. @see AudioFormatReader::metadataValues, createWriterFor
  23191. */
  23192. static const char* const bwavCodingHistory;
  23193. /** Utility function to fill out the appropriate metadata for a BWAV file.
  23194. This just makes it easier than using the property names directly, and it
  23195. fills out the time and date in the right format.
  23196. */
  23197. static const StringPairArray createBWAVMetadata (const String& description,
  23198. const String& originator,
  23199. const String& originatorRef,
  23200. const Time& dateAndTime,
  23201. const int64 timeReferenceSamples,
  23202. const String& codingHistory);
  23203. const Array <int> getPossibleSampleRates();
  23204. const Array <int> getPossibleBitDepths();
  23205. bool canDoStereo();
  23206. bool canDoMono();
  23207. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23208. const bool deleteStreamIfOpeningFails);
  23209. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23210. double sampleRateToUse,
  23211. unsigned int numberOfChannels,
  23212. int bitsPerSample,
  23213. const StringPairArray& metadataValues,
  23214. int qualityOptionIndex);
  23215. /** Utility function to replace the metadata in a wav file with a new set of values.
  23216. If possible, this cheats by overwriting just the metadata region of the file, rather
  23217. than by copying the whole file again.
  23218. */
  23219. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  23220. juce_UseDebuggingNewOperator
  23221. };
  23222. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23223. /*** End of inlined file: juce_WavAudioFormat.h ***/
  23224. #endif
  23225. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23226. /*** Start of inlined file: juce_AudioFormatReaderSource.h ***/
  23227. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23228. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23229. /*** Start of inlined file: juce_PositionableAudioSource.h ***/
  23230. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23231. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23232. /**
  23233. A type of AudioSource which can be repositioned.
  23234. The basic AudioSource just streams continuously with no idea of a current
  23235. time or length, so the PositionableAudioSource is used for a finite stream
  23236. that has a current read position.
  23237. @see AudioSource, AudioTransportSource
  23238. */
  23239. class JUCE_API PositionableAudioSource : public AudioSource
  23240. {
  23241. protected:
  23242. /** Creates the PositionableAudioSource. */
  23243. PositionableAudioSource() throw() {}
  23244. public:
  23245. /** Destructor */
  23246. ~PositionableAudioSource() {}
  23247. /** Tells the stream to move to a new position.
  23248. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  23249. should return samples from this position.
  23250. Note that this may be called on a different thread to getNextAudioBlock(),
  23251. so the subclass should make sure it's synchronised.
  23252. */
  23253. virtual void setNextReadPosition (int newPosition) = 0;
  23254. /** Returns the position from which the next block will be returned.
  23255. @see setNextReadPosition
  23256. */
  23257. virtual int getNextReadPosition() const = 0;
  23258. /** Returns the total length of the stream (in samples). */
  23259. virtual int getTotalLength() const = 0;
  23260. /** Returns true if this source is actually playing in a loop. */
  23261. virtual bool isLooping() const = 0;
  23262. };
  23263. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23264. /*** End of inlined file: juce_PositionableAudioSource.h ***/
  23265. /**
  23266. A type of AudioSource that will read from an AudioFormatReader.
  23267. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  23268. */
  23269. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  23270. {
  23271. public:
  23272. /** Creates an AudioFormatReaderSource for a given reader.
  23273. @param sourceReader the reader to use as the data source
  23274. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  23275. when this object is deleted; if false it will be
  23276. left up to the caller to manage its lifetime
  23277. */
  23278. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  23279. const bool deleteReaderWhenThisIsDeleted);
  23280. /** Destructor. */
  23281. ~AudioFormatReaderSource();
  23282. /** Toggles loop-mode.
  23283. If set to true, it will continuously loop the input source. If false,
  23284. it will just emit silence after the source has finished.
  23285. @see isLooping
  23286. */
  23287. void setLooping (const bool shouldLoop) throw();
  23288. /** Returns whether loop-mode is turned on or not. */
  23289. bool isLooping() const { return looping; }
  23290. /** Returns the reader that's being used. */
  23291. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  23292. /** Implementation of the AudioSource method. */
  23293. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23294. /** Implementation of the AudioSource method. */
  23295. void releaseResources();
  23296. /** Implementation of the AudioSource method. */
  23297. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23298. /** Implements the PositionableAudioSource method. */
  23299. void setNextReadPosition (int newPosition);
  23300. /** Implements the PositionableAudioSource method. */
  23301. int getNextReadPosition() const;
  23302. /** Implements the PositionableAudioSource method. */
  23303. int getTotalLength() const;
  23304. juce_UseDebuggingNewOperator
  23305. private:
  23306. AudioFormatReader* reader;
  23307. bool deleteReader;
  23308. int volatile nextPlayPos;
  23309. bool volatile looping;
  23310. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  23311. AudioFormatReaderSource (const AudioFormatReaderSource&);
  23312. AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  23313. };
  23314. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23315. /*** End of inlined file: juce_AudioFormatReaderSource.h ***/
  23316. #endif
  23317. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23318. #endif
  23319. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23320. /*** Start of inlined file: juce_AudioSourcePlayer.h ***/
  23321. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23322. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23323. /*** Start of inlined file: juce_AudioIODevice.h ***/
  23324. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23325. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23326. class AudioIODevice;
  23327. /**
  23328. One of these is passed to an AudioIODevice object to stream the audio data
  23329. in and out.
  23330. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  23331. method on its own high-priority audio thread, when it needs to send or receive
  23332. the next block of data.
  23333. @see AudioIODevice, AudioDeviceManager
  23334. */
  23335. class JUCE_API AudioIODeviceCallback
  23336. {
  23337. public:
  23338. /** Destructor. */
  23339. virtual ~AudioIODeviceCallback() {}
  23340. /** Processes a block of incoming and outgoing audio data.
  23341. The subclass's implementation should use the incoming audio for whatever
  23342. purposes it needs to, and must fill all the output channels with the next
  23343. block of output data before returning.
  23344. The channel data is arranged with the same array indices as the channel name
  23345. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  23346. that aren't specified in AudioIODevice::open() will have a null pointer for their
  23347. associated channel, so remember to check for this.
  23348. @param inputChannelData a set of arrays containing the audio data for each
  23349. incoming channel - this data is valid until the function
  23350. returns. There will be one channel of data for each input
  23351. channel that was enabled when the audio device was opened
  23352. (see AudioIODevice::open())
  23353. @param numInputChannels the number of pointers to channel data in the
  23354. inputChannelData array.
  23355. @param outputChannelData a set of arrays which need to be filled with the data
  23356. that should be sent to each outgoing channel of the device.
  23357. There will be one channel of data for each output channel
  23358. that was enabled when the audio device was opened (see
  23359. AudioIODevice::open())
  23360. The initial contents of the array is undefined, so the
  23361. callback function must fill all the channels with zeros if
  23362. its output is silence. Failing to do this could cause quite
  23363. an unpleasant noise!
  23364. @param numOutputChannels the number of pointers to channel data in the
  23365. outputChannelData array.
  23366. @param numSamples the number of samples in each channel of the input and
  23367. output arrays. The number of samples will depend on the
  23368. audio device's buffer size and will usually remain constant,
  23369. although this isn't guaranteed, so make sure your code can
  23370. cope with reasonable changes in the buffer size from one
  23371. callback to the next.
  23372. */
  23373. virtual void audioDeviceIOCallback (const float** inputChannelData,
  23374. int numInputChannels,
  23375. float** outputChannelData,
  23376. int numOutputChannels,
  23377. int numSamples) = 0;
  23378. /** Called to indicate that the device is about to start calling back.
  23379. This will be called just before the audio callbacks begin, either when this
  23380. callback has just been added to an audio device, or after the device has been
  23381. restarted because of a sample-rate or block-size change.
  23382. You can use this opportunity to find out the sample rate and block size
  23383. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  23384. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  23385. @param device the audio IO device that will be used to drive the callback.
  23386. Note that if you're going to store this this pointer, it is
  23387. only valid until the next time that audioDeviceStopped is called.
  23388. */
  23389. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  23390. /** Called to indicate that the device has stopped.
  23391. */
  23392. virtual void audioDeviceStopped() = 0;
  23393. };
  23394. /**
  23395. Base class for an audio device with synchronised input and output channels.
  23396. Subclasses of this are used to implement different protocols such as DirectSound,
  23397. ASIO, CoreAudio, etc.
  23398. To create one of these, you'll need to use the AudioIODeviceType class - see the
  23399. documentation for that class for more info.
  23400. For an easier way of managing audio devices and their settings, have a look at the
  23401. AudioDeviceManager class.
  23402. @see AudioIODeviceType, AudioDeviceManager
  23403. */
  23404. class JUCE_API AudioIODevice
  23405. {
  23406. public:
  23407. /** Destructor. */
  23408. virtual ~AudioIODevice();
  23409. /** Returns the device's name, (as set in the constructor). */
  23410. const String& getName() const throw() { return name; }
  23411. /** Returns the type of the device.
  23412. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  23413. */
  23414. const String& getTypeName() const throw() { return typeName; }
  23415. /** Returns the names of all the available output channels on this device.
  23416. To find out which of these are currently in use, call getActiveOutputChannels().
  23417. */
  23418. virtual const StringArray getOutputChannelNames() = 0;
  23419. /** Returns the names of all the available input channels on this device.
  23420. To find out which of these are currently in use, call getActiveInputChannels().
  23421. */
  23422. virtual const StringArray getInputChannelNames() = 0;
  23423. /** Returns the number of sample-rates this device supports.
  23424. To find out which rates are available on this device, use this method to
  23425. find out how many there are, and getSampleRate() to get the rates.
  23426. @see getSampleRate
  23427. */
  23428. virtual int getNumSampleRates() = 0;
  23429. /** Returns one of the sample-rates this device supports.
  23430. To find out which rates are available on this device, use getNumSampleRates() to
  23431. find out how many there are, and getSampleRate() to get the individual rates.
  23432. The sample rate is set by the open() method.
  23433. (Note that for DirectSound some rates might not work, depending on combinations
  23434. of i/o channels that are being opened).
  23435. @see getNumSampleRates
  23436. */
  23437. virtual double getSampleRate (int index) = 0;
  23438. /** Returns the number of sizes of buffer that are available.
  23439. @see getBufferSizeSamples, getDefaultBufferSize
  23440. */
  23441. virtual int getNumBufferSizesAvailable() = 0;
  23442. /** Returns one of the possible buffer-sizes.
  23443. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  23444. @returns a number of samples
  23445. @see getNumBufferSizesAvailable, getDefaultBufferSize
  23446. */
  23447. virtual int getBufferSizeSamples (int index) = 0;
  23448. /** Returns the default buffer-size to use.
  23449. @returns a number of samples
  23450. @see getNumBufferSizesAvailable, getBufferSizeSamples
  23451. */
  23452. virtual int getDefaultBufferSize() = 0;
  23453. /** Tries to open the device ready to play.
  23454. @param inputChannels a BigInteger in which a set bit indicates that the corresponding
  23455. input channel should be enabled
  23456. @param outputChannels a BigInteger in which a set bit indicates that the corresponding
  23457. output channel should be enabled
  23458. @param sampleRate the sample rate to try to use - to find out which rates are
  23459. available, see getNumSampleRates() and getSampleRate()
  23460. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  23461. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  23462. @returns an error description if there's a problem, or an empty string if it succeeds in
  23463. opening the device
  23464. @see close
  23465. */
  23466. virtual const String open (const BigInteger& inputChannels,
  23467. const BigInteger& outputChannels,
  23468. double sampleRate,
  23469. int bufferSizeSamples) = 0;
  23470. /** Closes and releases the device if it's open. */
  23471. virtual void close() = 0;
  23472. /** Returns true if the device is still open.
  23473. A device might spontaneously close itself if something goes wrong, so this checks if
  23474. it's still open.
  23475. */
  23476. virtual bool isOpen() = 0;
  23477. /** Starts the device actually playing.
  23478. This must be called after the device has been opened.
  23479. @param callback the callback to use for streaming the data.
  23480. @see AudioIODeviceCallback, open
  23481. */
  23482. virtual void start (AudioIODeviceCallback* callback) = 0;
  23483. /** Stops the device playing.
  23484. Once a device has been started, this will stop it. Any pending calls to the
  23485. callback class will be flushed before this method returns.
  23486. */
  23487. virtual void stop() = 0;
  23488. /** Returns true if the device is still calling back.
  23489. The device might mysteriously stop, so this checks whether it's
  23490. still playing.
  23491. */
  23492. virtual bool isPlaying() = 0;
  23493. /** Returns the last error that happened if anything went wrong. */
  23494. virtual const String getLastError() = 0;
  23495. /** Returns the buffer size that the device is currently using.
  23496. If the device isn't actually open, this value doesn't really mean much.
  23497. */
  23498. virtual int getCurrentBufferSizeSamples() = 0;
  23499. /** Returns the sample rate that the device is currently using.
  23500. If the device isn't actually open, this value doesn't really mean much.
  23501. */
  23502. virtual double getCurrentSampleRate() = 0;
  23503. /** Returns the device's current physical bit-depth.
  23504. If the device isn't actually open, this value doesn't really mean much.
  23505. */
  23506. virtual int getCurrentBitDepth() = 0;
  23507. /** Returns a mask showing which of the available output channels are currently
  23508. enabled.
  23509. @see getOutputChannelNames
  23510. */
  23511. virtual const BigInteger getActiveOutputChannels() const = 0;
  23512. /** Returns a mask showing which of the available input channels are currently
  23513. enabled.
  23514. @see getInputChannelNames
  23515. */
  23516. virtual const BigInteger getActiveInputChannels() const = 0;
  23517. /** Returns the device's output latency.
  23518. This is the delay in samples between a callback getting a block of data, and
  23519. that data actually getting played.
  23520. */
  23521. virtual int getOutputLatencyInSamples() = 0;
  23522. /** Returns the device's input latency.
  23523. This is the delay in samples between some audio actually arriving at the soundcard,
  23524. and the callback getting passed this block of data.
  23525. */
  23526. virtual int getInputLatencyInSamples() = 0;
  23527. /** True if this device can show a pop-up control panel for editing its settings.
  23528. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  23529. to display it.
  23530. */
  23531. virtual bool hasControlPanel() const;
  23532. /** Shows a device-specific control panel if there is one.
  23533. This should only be called for devices which return true from hasControlPanel().
  23534. */
  23535. virtual bool showControlPanel();
  23536. protected:
  23537. /** Creates a device, setting its name and type member variables. */
  23538. AudioIODevice (const String& deviceName,
  23539. const String& typeName);
  23540. /** @internal */
  23541. String name, typeName;
  23542. };
  23543. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23544. /*** End of inlined file: juce_AudioIODevice.h ***/
  23545. /**
  23546. Wrapper class to continuously stream audio from an audio source to an
  23547. AudioIODevice.
  23548. This object acts as an AudioIODeviceCallback, so can be attached to an
  23549. output device, and will stream audio from an AudioSource.
  23550. */
  23551. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  23552. {
  23553. public:
  23554. /** Creates an empty AudioSourcePlayer. */
  23555. AudioSourcePlayer();
  23556. /** Destructor.
  23557. Make sure this object isn't still being used by an AudioIODevice before
  23558. deleting it!
  23559. */
  23560. virtual ~AudioSourcePlayer();
  23561. /** Changes the current audio source to play from.
  23562. If the source passed in is already being used, this method will do nothing.
  23563. If the source is not null, its prepareToPlay() method will be called
  23564. before it starts being used for playback.
  23565. If there's another source currently playing, its releaseResources() method
  23566. will be called after it has been swapped for the new one.
  23567. @param newSource the new source to use - this will NOT be deleted
  23568. by this object when no longer needed, so it's the
  23569. caller's responsibility to manage it.
  23570. */
  23571. void setSource (AudioSource* newSource);
  23572. /** Returns the source that's playing.
  23573. May return 0 if there's no source.
  23574. */
  23575. AudioSource* getCurrentSource() const throw() { return source; }
  23576. /** Sets a gain to apply to the audio data.
  23577. @see getGain
  23578. */
  23579. void setGain (const float newGain) throw();
  23580. /** Returns the current gain.
  23581. @see setGain
  23582. */
  23583. float getGain() const throw() { return gain; }
  23584. /** Implementation of the AudioIODeviceCallback method. */
  23585. void audioDeviceIOCallback (const float** inputChannelData,
  23586. int totalNumInputChannels,
  23587. float** outputChannelData,
  23588. int totalNumOutputChannels,
  23589. int numSamples);
  23590. /** Implementation of the AudioIODeviceCallback method. */
  23591. void audioDeviceAboutToStart (AudioIODevice* device);
  23592. /** Implementation of the AudioIODeviceCallback method. */
  23593. void audioDeviceStopped();
  23594. juce_UseDebuggingNewOperator
  23595. private:
  23596. CriticalSection readLock;
  23597. AudioSource* source;
  23598. double sampleRate;
  23599. int bufferSize;
  23600. float* channels [128];
  23601. float* outputChans [128];
  23602. const float* inputChans [128];
  23603. AudioSampleBuffer tempBuffer;
  23604. float lastGain, gain;
  23605. AudioSourcePlayer (const AudioSourcePlayer&);
  23606. AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  23607. };
  23608. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23609. /*** End of inlined file: juce_AudioSourcePlayer.h ***/
  23610. #endif
  23611. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23612. /*** Start of inlined file: juce_AudioTransportSource.h ***/
  23613. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23614. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23615. /*** Start of inlined file: juce_BufferingAudioSource.h ***/
  23616. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23617. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23618. /**
  23619. An AudioSource which takes another source as input, and buffers it using a thread.
  23620. Create this as a wrapper around another thread, and it will read-ahead with
  23621. a background thread to smooth out playback. You can either create one of these
  23622. directly, or use it indirectly using an AudioTransportSource.
  23623. @see PositionableAudioSource, AudioTransportSource
  23624. */
  23625. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  23626. {
  23627. public:
  23628. /** Creates a BufferingAudioSource.
  23629. @param source the input source to read from
  23630. @param deleteSourceWhenDeleted if true, then the input source object will
  23631. be deleted when this object is deleted
  23632. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  23633. */
  23634. BufferingAudioSource (PositionableAudioSource* source,
  23635. const bool deleteSourceWhenDeleted,
  23636. int numberOfSamplesToBuffer);
  23637. /** Destructor.
  23638. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  23639. flag was set in the constructor.
  23640. */
  23641. ~BufferingAudioSource();
  23642. /** Implementation of the AudioSource method. */
  23643. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23644. /** Implementation of the AudioSource method. */
  23645. void releaseResources();
  23646. /** Implementation of the AudioSource method. */
  23647. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23648. /** Implements the PositionableAudioSource method. */
  23649. void setNextReadPosition (int newPosition);
  23650. /** Implements the PositionableAudioSource method. */
  23651. int getNextReadPosition() const;
  23652. /** Implements the PositionableAudioSource method. */
  23653. int getTotalLength() const { return source->getTotalLength(); }
  23654. /** Implements the PositionableAudioSource method. */
  23655. bool isLooping() const { return source->isLooping(); }
  23656. juce_UseDebuggingNewOperator
  23657. private:
  23658. PositionableAudioSource* source;
  23659. bool deleteSourceWhenDeleted;
  23660. int numberOfSamplesToBuffer;
  23661. AudioSampleBuffer buffer;
  23662. CriticalSection bufferStartPosLock;
  23663. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  23664. bool wasSourceLooping;
  23665. double volatile sampleRate;
  23666. friend class SharedBufferingAudioSourceThread;
  23667. bool readNextBufferChunk();
  23668. void readBufferSection (int start, int length, int bufferOffset);
  23669. BufferingAudioSource (const BufferingAudioSource&);
  23670. BufferingAudioSource& operator= (const BufferingAudioSource&);
  23671. };
  23672. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23673. /*** End of inlined file: juce_BufferingAudioSource.h ***/
  23674. /*** Start of inlined file: juce_ResamplingAudioSource.h ***/
  23675. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23676. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23677. /**
  23678. A type of AudioSource that takes an input source and changes its sample rate.
  23679. @see AudioSource
  23680. */
  23681. class JUCE_API ResamplingAudioSource : public AudioSource
  23682. {
  23683. public:
  23684. /** Creates a ResamplingAudioSource for a given input source.
  23685. @param inputSource the input source to read from
  23686. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23687. this object is deleted
  23688. */
  23689. ResamplingAudioSource (AudioSource* const inputSource,
  23690. const bool deleteInputWhenDeleted);
  23691. /** Destructor. */
  23692. ~ResamplingAudioSource();
  23693. /** Changes the resampling ratio.
  23694. (This value can be changed at any time, even while the source is running).
  23695. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  23696. values will speed it up; lower values will slow it
  23697. down. The ratio must be greater than 0
  23698. */
  23699. void setResamplingRatio (const double samplesInPerOutputSample);
  23700. /** Returns the current resampling ratio.
  23701. This is the value that was set by setResamplingRatio().
  23702. */
  23703. double getResamplingRatio() const throw() { return ratio; }
  23704. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23705. void releaseResources();
  23706. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23707. juce_UseDebuggingNewOperator
  23708. private:
  23709. AudioSource* const input;
  23710. const bool deleteInputWhenDeleted;
  23711. double ratio, lastRatio;
  23712. AudioSampleBuffer buffer;
  23713. int bufferPos, sampsInBuffer;
  23714. double subSampleOffset;
  23715. double coefficients[6];
  23716. CriticalSection ratioLock;
  23717. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  23718. void createLowPass (const double proportionalRate);
  23719. struct FilterState
  23720. {
  23721. double x1, x2, y1, y2;
  23722. };
  23723. FilterState filterStates[2];
  23724. void resetFilters();
  23725. void applyFilter (float* samples, int num, FilterState& fs);
  23726. ResamplingAudioSource (const ResamplingAudioSource&);
  23727. ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  23728. };
  23729. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23730. /*** End of inlined file: juce_ResamplingAudioSource.h ***/
  23731. /**
  23732. An AudioSource that takes a PositionableAudioSource and allows it to be
  23733. played, stopped, started, etc.
  23734. This can also be told use a buffer and background thread to read ahead, and
  23735. if can correct for different sample-rates.
  23736. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  23737. to control playback of an audio file.
  23738. @see AudioSource, AudioSourcePlayer
  23739. */
  23740. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  23741. public ChangeBroadcaster
  23742. {
  23743. public:
  23744. /** Creates an AudioTransportSource.
  23745. After creating one of these, use the setSource() method to select an input source.
  23746. */
  23747. AudioTransportSource();
  23748. /** Destructor. */
  23749. ~AudioTransportSource();
  23750. /** Sets the reader that is being used as the input source.
  23751. This will stop playback, reset the position to 0 and change to the new reader.
  23752. The source passed in will not be deleted by this object, so must be managed by
  23753. the caller.
  23754. @param newSource the new input source to use. This may be zero
  23755. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  23756. is zero, no reading ahead will be done; if it's
  23757. greater than zero, a BufferingAudioSource will be used
  23758. to do the reading-ahead
  23759. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  23760. rate of the source, and playback will be sample-rate
  23761. adjusted to maintain playback at the correct pitch. If
  23762. this is 0, no sample-rate adjustment will be performed
  23763. */
  23764. void setSource (PositionableAudioSource* const newSource,
  23765. int readAheadBufferSize = 0,
  23766. double sourceSampleRateToCorrectFor = 0.0);
  23767. /** Changes the current playback position in the source stream.
  23768. The next time the getNextAudioBlock() method is called, this
  23769. is the time from which it'll read data.
  23770. @see getPosition
  23771. */
  23772. void setPosition (double newPosition);
  23773. /** Returns the position that the next data block will be read from
  23774. This is a time in seconds.
  23775. */
  23776. double getCurrentPosition() const;
  23777. /** Returns true if the player has stopped because its input stream ran out of data.
  23778. */
  23779. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  23780. /** Starts playing (if a source has been selected).
  23781. If it starts playing, this will send a message to any ChangeListeners
  23782. that are registered with this object.
  23783. */
  23784. void start();
  23785. /** Stops playing.
  23786. If it's actually playing, this will send a message to any ChangeListeners
  23787. that are registered with this object.
  23788. */
  23789. void stop();
  23790. /** Returns true if it's currently playing. */
  23791. bool isPlaying() const throw() { return playing; }
  23792. /** Changes the gain to apply to the output.
  23793. @param newGain a factor by which to multiply the outgoing samples,
  23794. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  23795. */
  23796. void setGain (const float newGain) throw();
  23797. /** Returns the current gain setting.
  23798. @see setGain
  23799. */
  23800. float getGain() const throw() { return gain; }
  23801. /** Implementation of the AudioSource method. */
  23802. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23803. /** Implementation of the AudioSource method. */
  23804. void releaseResources();
  23805. /** Implementation of the AudioSource method. */
  23806. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23807. /** Implements the PositionableAudioSource method. */
  23808. void setNextReadPosition (int newPosition);
  23809. /** Implements the PositionableAudioSource method. */
  23810. int getNextReadPosition() const;
  23811. /** Implements the PositionableAudioSource method. */
  23812. int getTotalLength() const;
  23813. /** Implements the PositionableAudioSource method. */
  23814. bool isLooping() const;
  23815. juce_UseDebuggingNewOperator
  23816. private:
  23817. PositionableAudioSource* source;
  23818. ResamplingAudioSource* resamplerSource;
  23819. BufferingAudioSource* bufferingSource;
  23820. PositionableAudioSource* positionableSource;
  23821. AudioSource* masterSource;
  23822. CriticalSection callbackLock;
  23823. float volatile gain, lastGain;
  23824. bool volatile playing, stopped;
  23825. double sampleRate, sourceSampleRate;
  23826. int blockSize, readAheadBufferSize;
  23827. bool isPrepared, inputStreamEOF;
  23828. AudioTransportSource (const AudioTransportSource&);
  23829. AudioTransportSource& operator= (const AudioTransportSource&);
  23830. };
  23831. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23832. /*** End of inlined file: juce_AudioTransportSource.h ***/
  23833. #endif
  23834. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23835. #endif
  23836. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23837. /*** Start of inlined file: juce_ChannelRemappingAudioSource.h ***/
  23838. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23839. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23840. /**
  23841. An AudioSource that takes the audio from another source, and re-maps its
  23842. input and output channels to a different arrangement.
  23843. You can use this to increase or decrease the number of channels that an
  23844. audio source uses, or to re-order those channels.
  23845. Call the reset() method before using it to set up a default mapping, and then
  23846. the setInputChannelMapping() and setOutputChannelMapping() methods to
  23847. create an appropriate mapping, otherwise no channels will be connected and
  23848. it'll produce silence.
  23849. @see AudioSource
  23850. */
  23851. class ChannelRemappingAudioSource : public AudioSource
  23852. {
  23853. public:
  23854. /** Creates a remapping source that will pass on audio from the given input.
  23855. @param source the input source to use. Make sure that this doesn't
  23856. get deleted before the ChannelRemappingAudioSource object
  23857. @param deleteSourceWhenDeleted if true, the input source will be deleted
  23858. when this object is deleted, if false, the caller is
  23859. responsible for its deletion
  23860. */
  23861. ChannelRemappingAudioSource (AudioSource* const source,
  23862. const bool deleteSourceWhenDeleted);
  23863. /** Destructor. */
  23864. ~ChannelRemappingAudioSource();
  23865. /** Specifies a number of channels that this audio source must produce from its
  23866. getNextAudioBlock() callback.
  23867. */
  23868. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  23869. /** Clears any mapped channels.
  23870. After this, no channels are mapped, so this object will produce silence. Create
  23871. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  23872. */
  23873. void clearAllMappings() throw();
  23874. /** Creates an input channel mapping.
  23875. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  23876. data will be sent to destChannelIndex of our input source.
  23877. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  23878. source specified when this object was created).
  23879. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  23880. during our getNextAudioBlock() callback
  23881. */
  23882. void setInputChannelMapping (const int destChannelIndex,
  23883. const int sourceChannelIndex) throw();
  23884. /** Creates an output channel mapping.
  23885. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  23886. our input audio source will be copied to channel destChannelIndex of the final buffer.
  23887. @param sourceChannelIndex the index of an output channel coming from our input audio source
  23888. (i.e. the source specified when this object was created).
  23889. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  23890. during our getNextAudioBlock() callback
  23891. */
  23892. void setOutputChannelMapping (const int sourceChannelIndex,
  23893. const int destChannelIndex) throw();
  23894. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  23895. our input audio source.
  23896. */
  23897. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  23898. /** Returns the output channel to which channel outputChannelIndex of our input audio
  23899. source will be sent to.
  23900. */
  23901. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  23902. /** Returns an XML object to encapsulate the state of the mappings.
  23903. @see restoreFromXml
  23904. */
  23905. XmlElement* createXml() const throw();
  23906. /** Restores the mappings from an XML object created by createXML().
  23907. @see createXml
  23908. */
  23909. void restoreFromXml (const XmlElement& e) throw();
  23910. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23911. void releaseResources();
  23912. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23913. juce_UseDebuggingNewOperator
  23914. private:
  23915. int requiredNumberOfChannels;
  23916. Array <int> remappedInputs, remappedOutputs;
  23917. AudioSource* const source;
  23918. const bool deleteSourceWhenDeleted;
  23919. AudioSampleBuffer buffer;
  23920. AudioSourceChannelInfo remappedInfo;
  23921. CriticalSection lock;
  23922. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  23923. ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  23924. };
  23925. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23926. /*** End of inlined file: juce_ChannelRemappingAudioSource.h ***/
  23927. #endif
  23928. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23929. /*** Start of inlined file: juce_IIRFilterAudioSource.h ***/
  23930. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23931. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23932. /*** Start of inlined file: juce_IIRFilter.h ***/
  23933. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  23934. #define __JUCE_IIRFILTER_JUCEHEADER__
  23935. /**
  23936. An IIR filter that can perform low, high, or band-pass filtering on an
  23937. audio signal.
  23938. @see IIRFilterAudioSource
  23939. */
  23940. class JUCE_API IIRFilter
  23941. {
  23942. public:
  23943. /** Creates a filter.
  23944. Initially the filter is inactive, so will have no effect on samples that
  23945. you process with it. Use the appropriate method to turn it into the type
  23946. of filter needed.
  23947. */
  23948. IIRFilter();
  23949. /** Creates a copy of another filter. */
  23950. IIRFilter (const IIRFilter& other);
  23951. /** Destructor. */
  23952. ~IIRFilter();
  23953. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  23954. Note that this clears the processing state, but the type of filter and
  23955. its coefficients aren't changed. To put a filter into an inactive state, use
  23956. the makeInactive() method.
  23957. */
  23958. void reset() throw();
  23959. /** Performs the filter operation on the given set of samples.
  23960. */
  23961. void processSamples (float* samples,
  23962. int numSamples) throw();
  23963. /** Processes a single sample, without any locking or checking.
  23964. Use this if you need fast processing of a single value, but be aware that
  23965. this isn't thread-safe in the way that processSamples() is.
  23966. */
  23967. float processSingleSampleRaw (float sample) throw();
  23968. /** Sets the filter up to act as a low-pass filter.
  23969. */
  23970. void makeLowPass (double sampleRate,
  23971. double frequency) throw();
  23972. /** Sets the filter up to act as a high-pass filter.
  23973. */
  23974. void makeHighPass (double sampleRate,
  23975. double frequency) throw();
  23976. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  23977. The gain is a scale factor that the low frequencies are multiplied by, so values
  23978. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  23979. attenuate them.
  23980. */
  23981. void makeLowShelf (double sampleRate,
  23982. double cutOffFrequency,
  23983. double Q,
  23984. float gainFactor) throw();
  23985. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  23986. The gain is a scale factor that the high frequencies are multiplied by, so values
  23987. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  23988. attenuate them.
  23989. */
  23990. void makeHighShelf (double sampleRate,
  23991. double cutOffFrequency,
  23992. double Q,
  23993. float gainFactor) throw();
  23994. /** Sets the filter up to act as a band pass filter centred around a
  23995. frequency, with a variable Q and gain.
  23996. The gain is a scale factor that the centre frequencies are multiplied by, so
  23997. values greater than 1.0 will boost the centre frequencies, values less than
  23998. 1.0 will attenuate them.
  23999. */
  24000. void makeBandPass (double sampleRate,
  24001. double centreFrequency,
  24002. double Q,
  24003. float gainFactor) throw();
  24004. /** Clears the filter's coefficients so that it becomes inactive.
  24005. */
  24006. void makeInactive() throw();
  24007. /** Makes this filter duplicate the set-up of another one.
  24008. */
  24009. void copyCoefficientsFrom (const IIRFilter& other) throw();
  24010. juce_UseDebuggingNewOperator
  24011. protected:
  24012. CriticalSection processLock;
  24013. void setCoefficients (double c1, double c2, double c3,
  24014. double c4, double c5, double c6) throw();
  24015. bool active;
  24016. float coefficients[6];
  24017. float x1, x2, y1, y2;
  24018. // (use the copyCoefficientsFrom() method instead of this operator)
  24019. IIRFilter& operator= (const IIRFilter&);
  24020. };
  24021. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  24022. /*** End of inlined file: juce_IIRFilter.h ***/
  24023. /**
  24024. An AudioSource that performs an IIR filter on another source.
  24025. */
  24026. class JUCE_API IIRFilterAudioSource : public AudioSource
  24027. {
  24028. public:
  24029. /** Creates a IIRFilterAudioSource for a given input source.
  24030. @param inputSource the input source to read from
  24031. @param deleteInputWhenDeleted if true, the input source will be deleted when
  24032. this object is deleted
  24033. */
  24034. IIRFilterAudioSource (AudioSource* const inputSource,
  24035. const bool deleteInputWhenDeleted);
  24036. /** Destructor. */
  24037. ~IIRFilterAudioSource();
  24038. /** Changes the filter to use the same parameters as the one being passed in.
  24039. */
  24040. void setFilterParameters (const IIRFilter& newSettings);
  24041. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24042. void releaseResources();
  24043. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24044. juce_UseDebuggingNewOperator
  24045. private:
  24046. AudioSource* const input;
  24047. const bool deleteInputWhenDeleted;
  24048. OwnedArray <IIRFilter> iirFilters;
  24049. IIRFilterAudioSource (const IIRFilterAudioSource&);
  24050. IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  24051. };
  24052. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24053. /*** End of inlined file: juce_IIRFilterAudioSource.h ***/
  24054. #endif
  24055. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24056. /*** Start of inlined file: juce_MixerAudioSource.h ***/
  24057. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24058. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24059. /**
  24060. An AudioSource that mixes together the output of a set of other AudioSources.
  24061. Input sources can be added and removed while the mixer is running as long as their
  24062. prepareToPlay() and releaseResources() methods are called before and after adding
  24063. them to the mixer.
  24064. */
  24065. class JUCE_API MixerAudioSource : public AudioSource
  24066. {
  24067. public:
  24068. /** Creates a MixerAudioSource.
  24069. */
  24070. MixerAudioSource();
  24071. /** Destructor. */
  24072. ~MixerAudioSource();
  24073. /** Adds an input source to the mixer.
  24074. If the mixer is running you'll need to make sure that the input source
  24075. is ready to play by calling its prepareToPlay() method before adding it.
  24076. If the mixer is stopped, then its input sources will be automatically
  24077. prepared when the mixer's prepareToPlay() method is called.
  24078. @param newInput the source to add to the mixer
  24079. @param deleteWhenRemoved if true, then this source will be deleted when
  24080. the mixer is deleted or when removeAllInputs() is
  24081. called (unless the source is previously removed
  24082. with the removeInputSource method)
  24083. */
  24084. void addInputSource (AudioSource* newInput,
  24085. const bool deleteWhenRemoved);
  24086. /** Removes an input source.
  24087. If the mixer is running, this will remove the source but not call its
  24088. releaseResources() method, so the caller might want to do this manually.
  24089. @param input the source to remove
  24090. @param deleteSource whether to delete this source after it's been removed
  24091. */
  24092. void removeInputSource (AudioSource* input,
  24093. const bool deleteSource);
  24094. /** Removes all the input sources.
  24095. If the mixer is running, this will remove the sources but not call their
  24096. releaseResources() method, so the caller might want to do this manually.
  24097. Any sources which were added with the deleteWhenRemoved flag set will be
  24098. deleted by this method.
  24099. */
  24100. void removeAllInputs();
  24101. /** Implementation of the AudioSource method.
  24102. This will call prepareToPlay() on all its input sources.
  24103. */
  24104. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24105. /** Implementation of the AudioSource method.
  24106. This will call releaseResources() on all its input sources.
  24107. */
  24108. void releaseResources();
  24109. /** Implementation of the AudioSource method. */
  24110. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24111. juce_UseDebuggingNewOperator
  24112. private:
  24113. Array <AudioSource*> inputs;
  24114. BigInteger inputsToDelete;
  24115. CriticalSection lock;
  24116. AudioSampleBuffer tempBuffer;
  24117. double currentSampleRate;
  24118. int bufferSizeExpected;
  24119. MixerAudioSource (const MixerAudioSource&);
  24120. MixerAudioSource& operator= (const MixerAudioSource&);
  24121. };
  24122. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24123. /*** End of inlined file: juce_MixerAudioSource.h ***/
  24124. #endif
  24125. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  24126. #endif
  24127. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24128. #endif
  24129. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24130. /*** Start of inlined file: juce_ToneGeneratorAudioSource.h ***/
  24131. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24132. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24133. /**
  24134. A simple AudioSource that generates a sine wave.
  24135. */
  24136. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  24137. {
  24138. public:
  24139. /** Creates a ToneGeneratorAudioSource. */
  24140. ToneGeneratorAudioSource();
  24141. /** Destructor. */
  24142. ~ToneGeneratorAudioSource();
  24143. /** Sets the signal's amplitude. */
  24144. void setAmplitude (const float newAmplitude);
  24145. /** Sets the signal's frequency. */
  24146. void setFrequency (const double newFrequencyHz);
  24147. /** Implementation of the AudioSource method. */
  24148. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24149. /** Implementation of the AudioSource method. */
  24150. void releaseResources();
  24151. /** Implementation of the AudioSource method. */
  24152. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24153. juce_UseDebuggingNewOperator
  24154. private:
  24155. double frequency, sampleRate;
  24156. double currentPhase, phasePerSample;
  24157. float amplitude;
  24158. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  24159. ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  24160. };
  24161. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24162. /*** End of inlined file: juce_ToneGeneratorAudioSource.h ***/
  24163. #endif
  24164. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24165. /*** Start of inlined file: juce_AudioDeviceManager.h ***/
  24166. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24167. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24168. /*** Start of inlined file: juce_AudioIODeviceType.h ***/
  24169. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24170. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24171. class AudioDeviceManager;
  24172. class Component;
  24173. /**
  24174. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  24175. To get a list of available audio driver types, use the AudioDeviceManager::createAudioDeviceTypes()
  24176. method. Each of the objects returned can then be used to list the available
  24177. devices of that type. E.g.
  24178. @code
  24179. OwnedArray <AudioIODeviceType> types;
  24180. myAudioDeviceManager.createAudioDeviceTypes (types);
  24181. for (int i = 0; i < types.size(); ++i)
  24182. {
  24183. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  24184. types[i]->scanForDevices(); // This must be called before getting the list of devices
  24185. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  24186. for (int j = 0; j < deviceNames.size(); ++j)
  24187. {
  24188. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  24189. ...
  24190. }
  24191. }
  24192. @endcode
  24193. For an easier way of managing audio devices and their settings, have a look at the
  24194. AudioDeviceManager class.
  24195. @see AudioIODevice, AudioDeviceManager
  24196. */
  24197. class JUCE_API AudioIODeviceType
  24198. {
  24199. public:
  24200. /** Returns the name of this type of driver that this object manages.
  24201. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  24202. */
  24203. const String& getTypeName() const throw() { return typeName; }
  24204. /** Refreshes the object's cached list of known devices.
  24205. This must be called at least once before calling getDeviceNames() or any of
  24206. the other device creation methods.
  24207. */
  24208. virtual void scanForDevices() = 0;
  24209. /** Returns the list of available devices of this type.
  24210. The scanForDevices() method must have been called to create this list.
  24211. @param wantInputNames only really used by DirectSound where devices are split up
  24212. into inputs and outputs, this indicates whether to use
  24213. the input or output name to refer to a pair of devices.
  24214. */
  24215. virtual const StringArray getDeviceNames (bool wantInputNames = false) const = 0;
  24216. /** Returns the name of the default device.
  24217. This will be one of the names from the getDeviceNames() list.
  24218. @param forInput if true, this means that a default input device should be
  24219. returned; if false, it should return the default output
  24220. */
  24221. virtual int getDefaultDeviceIndex (bool forInput) const = 0;
  24222. /** Returns the index of a given device in the list of device names.
  24223. If asInput is true, it shows the index in the inputs list, otherwise it
  24224. looks for it in the outputs list.
  24225. */
  24226. virtual int getIndexOfDevice (AudioIODevice* device, bool asInput) const = 0;
  24227. /** Returns true if two different devices can be used for the input and output.
  24228. */
  24229. virtual bool hasSeparateInputsAndOutputs() const = 0;
  24230. /** Creates one of the devices of this type.
  24231. The deviceName must be one of the strings returned by getDeviceNames(), and
  24232. scanForDevices() must have been called before this method is used.
  24233. */
  24234. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  24235. const String& inputDeviceName) = 0;
  24236. struct DeviceSetupDetails
  24237. {
  24238. AudioDeviceManager* manager;
  24239. int minNumInputChannels, maxNumInputChannels;
  24240. int minNumOutputChannels, maxNumOutputChannels;
  24241. bool useStereoPairs;
  24242. };
  24243. /** Destructor. */
  24244. virtual ~AudioIODeviceType();
  24245. protected:
  24246. explicit AudioIODeviceType (const String& typeName);
  24247. private:
  24248. String typeName;
  24249. AudioIODeviceType (const AudioIODeviceType&);
  24250. AudioIODeviceType& operator= (const AudioIODeviceType&);
  24251. };
  24252. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24253. /*** End of inlined file: juce_AudioIODeviceType.h ***/
  24254. /*** Start of inlined file: juce_MidiInput.h ***/
  24255. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  24256. #define __JUCE_MIDIINPUT_JUCEHEADER__
  24257. /*** Start of inlined file: juce_MidiMessage.h ***/
  24258. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  24259. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  24260. /**
  24261. Encapsulates a MIDI message.
  24262. @see MidiMessageSequence, MidiOutput, MidiInput
  24263. */
  24264. class JUCE_API MidiMessage
  24265. {
  24266. public:
  24267. /** Creates a 3-byte short midi message.
  24268. @param byte1 message byte 1
  24269. @param byte2 message byte 2
  24270. @param byte3 message byte 3
  24271. @param timeStamp the time to give the midi message - this value doesn't
  24272. use any particular units, so will be application-specific
  24273. */
  24274. MidiMessage (int byte1, int byte2, int byte3, double timeStamp = 0) throw();
  24275. /** Creates a 2-byte short midi message.
  24276. @param byte1 message byte 1
  24277. @param byte2 message byte 2
  24278. @param timeStamp the time to give the midi message - this value doesn't
  24279. use any particular units, so will be application-specific
  24280. */
  24281. MidiMessage (int byte1, int byte2, double timeStamp = 0) throw();
  24282. /** Creates a 1-byte short midi message.
  24283. @param byte1 message byte 1
  24284. @param timeStamp the time to give the midi message - this value doesn't
  24285. use any particular units, so will be application-specific
  24286. */
  24287. MidiMessage (int byte1, double timeStamp = 0) throw();
  24288. /** Creates a midi message from a block of data. */
  24289. MidiMessage (const void* data, int numBytes, double timeStamp = 0);
  24290. /** Reads the next midi message from some data.
  24291. This will read as many bytes from a data stream as it needs to make a
  24292. complete message, and will return the number of bytes it used. This lets
  24293. you read a sequence of midi messages from a file or stream.
  24294. @param data the data to read from
  24295. @param maxBytesToUse the maximum number of bytes it's allowed to read
  24296. @param numBytesUsed returns the number of bytes that were actually needed
  24297. @param lastStatusByte in a sequence of midi messages, the initial byte
  24298. can be dropped from a message if it's the same as the
  24299. first byte of the previous message, so this lets you
  24300. supply the byte to use if the first byte of the message
  24301. has in fact been dropped.
  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 (const void* data, int maxBytesToUse,
  24306. int& numBytesUsed, uint8 lastStatusByte,
  24307. double timeStamp = 0);
  24308. /** Creates a copy of another midi message. */
  24309. MidiMessage (const MidiMessage& other);
  24310. /** Creates a copy of another midi message, with a different timestamp. */
  24311. MidiMessage (const MidiMessage& other, double newTimeStamp);
  24312. /** Destructor. */
  24313. ~MidiMessage();
  24314. /** Copies this message from another one. */
  24315. MidiMessage& operator= (const MidiMessage& other);
  24316. /** Returns a pointer to the raw midi data.
  24317. @see getRawDataSize
  24318. */
  24319. uint8* getRawData() const throw() { return data; }
  24320. /** Returns the number of bytes of data in the message.
  24321. @see getRawData
  24322. */
  24323. int getRawDataSize() const throw() { return size; }
  24324. /** Returns the timestamp associated with this message.
  24325. The exact meaning of this time and its units will vary, as messages are used in
  24326. a variety of different contexts.
  24327. If you're getting the message from a midi file, this could be a time in seconds, or
  24328. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  24329. If the message is being used in a MidiBuffer, it might indicate the number of
  24330. audio samples from the start of the buffer.
  24331. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  24332. for details of the way that it initialises this value.
  24333. @see setTimeStamp, addToTimeStamp
  24334. */
  24335. double getTimeStamp() const throw() { return timeStamp; }
  24336. /** Changes the message's associated timestamp.
  24337. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  24338. @see addToTimeStamp, getTimeStamp
  24339. */
  24340. void setTimeStamp (double newTimestamp) throw() { timeStamp = newTimestamp; }
  24341. /** Adds a value to the message's timestamp.
  24342. The units for the timestamp will be application-specific.
  24343. */
  24344. void addToTimeStamp (double delta) throw() { timeStamp += delta; }
  24345. /** Returns the midi channel associated with the message.
  24346. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  24347. if it's a sysex)
  24348. @see isForChannel, setChannel
  24349. */
  24350. int getChannel() const throw();
  24351. /** Returns true if the message applies to the given midi channel.
  24352. @param channelNumber the channel number to look for, in the range 1 to 16
  24353. @see getChannel, setChannel
  24354. */
  24355. bool isForChannel (int channelNumber) const throw();
  24356. /** Changes the message's midi channel.
  24357. This won't do anything for non-channel messages like sysexes.
  24358. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  24359. */
  24360. void setChannel (int newChannelNumber) throw();
  24361. /** Returns true if this is a system-exclusive message.
  24362. */
  24363. bool isSysEx() const throw();
  24364. /** Returns a pointer to the sysex data inside the message.
  24365. If this event isn't a sysex event, it'll return 0.
  24366. @see getSysExDataSize
  24367. */
  24368. const uint8* getSysExData() const throw();
  24369. /** Returns the size of the sysex data.
  24370. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  24371. @see getSysExData
  24372. */
  24373. int getSysExDataSize() const throw();
  24374. /** Returns true if this message is a 'key-down' event.
  24375. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  24376. velocity 0, it will still be considered to be a note-on and the
  24377. method will return true. If returnTrueForVelocity0 is false, then
  24378. if this is a note-on event with velocity 0, it'll be regarded as
  24379. a note-off, and the method will return false
  24380. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  24381. */
  24382. bool isNoteOn (bool returnTrueForVelocity0 = false) const throw();
  24383. /** Creates a key-down message (using a floating-point velocity).
  24384. @param channel the midi channel, in the range 1 to 16
  24385. @param noteNumber the key number, 0 to 127
  24386. @param velocity in the range 0 to 1.0
  24387. @see isNoteOn
  24388. */
  24389. static const MidiMessage noteOn (int channel, int noteNumber, float velocity) throw();
  24390. /** Creates a key-down message (using an integer velocity).
  24391. @param channel the midi channel, in the range 1 to 16
  24392. @param noteNumber the key number, 0 to 127
  24393. @param velocity in the range 0 to 127
  24394. @see isNoteOn
  24395. */
  24396. static const MidiMessage noteOn (int channel, int noteNumber, uint8 velocity) throw();
  24397. /** Returns true if this message is a 'key-up' event.
  24398. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  24399. for a note-on event with a velocity of 0.
  24400. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  24401. */
  24402. bool isNoteOff (bool returnTrueForNoteOnVelocity0 = true) const throw();
  24403. /** Creates a key-up message.
  24404. @param channel the midi channel, in the range 1 to 16
  24405. @param noteNumber the key number, 0 to 127
  24406. @see isNoteOff
  24407. */
  24408. static const MidiMessage noteOff (int channel, int noteNumber) throw();
  24409. /** Returns true if this message is a 'key-down' or 'key-up' event.
  24410. @see isNoteOn, isNoteOff
  24411. */
  24412. bool isNoteOnOrOff() const throw();
  24413. /** Returns the midi note number for note-on and note-off messages.
  24414. If the message isn't a note-on or off, the value returned will be
  24415. meaningless.
  24416. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  24417. */
  24418. int getNoteNumber() const throw();
  24419. /** Changes the midi note number of a note-on or note-off message.
  24420. If the message isn't a note on or off, this will do nothing.
  24421. */
  24422. void setNoteNumber (int newNoteNumber) throw();
  24423. /** Returns the velocity of a note-on or note-off message.
  24424. The value returned will be in the range 0 to 127.
  24425. If the message isn't a note-on or off event, it will return 0.
  24426. @see getFloatVelocity
  24427. */
  24428. uint8 getVelocity() const throw();
  24429. /** Returns the velocity of a note-on or note-off message.
  24430. The value returned will be in the range 0 to 1.0
  24431. If the message isn't a note-on or off event, it will return 0.
  24432. @see getVelocity, setVelocity
  24433. */
  24434. float getFloatVelocity() const throw();
  24435. /** Changes the velocity of a note-on or note-off message.
  24436. If the message isn't a note on or off, this will do nothing.
  24437. @param newVelocity the new velocity, in the range 0 to 1.0
  24438. @see getFloatVelocity, multiplyVelocity
  24439. */
  24440. void setVelocity (float newVelocity) throw();
  24441. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  24442. If the message isn't a note on or off, this will do nothing.
  24443. @param scaleFactor the value by which to multiply the velocity
  24444. @see setVelocity
  24445. */
  24446. void multiplyVelocity (float scaleFactor) throw();
  24447. /** Returns true if the message is a program (patch) change message.
  24448. @see getProgramChangeNumber, getGMInstrumentName
  24449. */
  24450. bool isProgramChange() const throw();
  24451. /** Returns the new program number of a program change message.
  24452. If the message isn't a program change, the value returned will be
  24453. nonsense.
  24454. @see isProgramChange, getGMInstrumentName
  24455. */
  24456. int getProgramChangeNumber() const throw();
  24457. /** Creates a program-change message.
  24458. @param channel the midi channel, in the range 1 to 16
  24459. @param programNumber the midi program number, 0 to 127
  24460. @see isProgramChange, getGMInstrumentName
  24461. */
  24462. static const MidiMessage programChange (int channel, int programNumber) throw();
  24463. /** Returns true if the message is a pitch-wheel move.
  24464. @see getPitchWheelValue, pitchWheel
  24465. */
  24466. bool isPitchWheel() const throw();
  24467. /** Returns the pitch wheel position from a pitch-wheel move message.
  24468. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  24469. If called for messages which aren't pitch wheel events, the number returned will be
  24470. nonsense.
  24471. @see isPitchWheel
  24472. */
  24473. int getPitchWheelValue() const throw();
  24474. /** Creates a pitch-wheel move message.
  24475. @param channel the midi channel, in the range 1 to 16
  24476. @param position the wheel position, in the range 0 to 16383
  24477. @see isPitchWheel
  24478. */
  24479. static const MidiMessage pitchWheel (int channel, int position) throw();
  24480. /** Returns true if the message is an aftertouch event.
  24481. For aftertouch events, use the getNoteNumber() method to find out the key
  24482. that it applies to, and getAftertouchValue() to find out the amount. Use
  24483. getChannel() to find out the channel.
  24484. @see getAftertouchValue, getNoteNumber
  24485. */
  24486. bool isAftertouch() const throw();
  24487. /** Returns the amount of aftertouch from an aftertouch messages.
  24488. The value returned is in the range 0 to 127, and will be nonsense for messages
  24489. other than aftertouch messages.
  24490. @see isAftertouch
  24491. */
  24492. int getAfterTouchValue() const throw();
  24493. /** Creates an aftertouch message.
  24494. @param channel the midi channel, in the range 1 to 16
  24495. @param noteNumber the key number, 0 to 127
  24496. @param aftertouchAmount the amount of aftertouch, 0 to 127
  24497. @see isAftertouch
  24498. */
  24499. static const MidiMessage aftertouchChange (int channel,
  24500. int noteNumber,
  24501. int aftertouchAmount) throw();
  24502. /** Returns true if the message is a channel-pressure change event.
  24503. This is like aftertouch, but common to the whole channel rather than a specific
  24504. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  24505. to find out the channel.
  24506. @see channelPressureChange
  24507. */
  24508. bool isChannelPressure() const throw();
  24509. /** Returns the pressure from a channel pressure change message.
  24510. @returns the pressure, in the range 0 to 127
  24511. @see isChannelPressure, channelPressureChange
  24512. */
  24513. int getChannelPressureValue() const throw();
  24514. /** Creates a channel-pressure change event.
  24515. @param channel the midi channel: 1 to 16
  24516. @param pressure the pressure, 0 to 127
  24517. @see isChannelPressure
  24518. */
  24519. static const MidiMessage channelPressureChange (int channel, int pressure) throw();
  24520. /** Returns true if this is a midi controller message.
  24521. @see getControllerNumber, getControllerValue, controllerEvent
  24522. */
  24523. bool isController() const throw();
  24524. /** Returns the controller number of a controller message.
  24525. The name of the controller can be looked up using the getControllerName() method.
  24526. Note that the value returned is invalid for messages that aren't controller changes.
  24527. @see isController, getControllerName, getControllerValue
  24528. */
  24529. int getControllerNumber() const throw();
  24530. /** Returns the controller value from a controller message.
  24531. A value 0 to 127 is returned to indicate the new controller position.
  24532. Note that the value returned is invalid for messages that aren't controller changes.
  24533. @see isController, getControllerNumber
  24534. */
  24535. int getControllerValue() const throw();
  24536. /** Creates a controller message.
  24537. @param channel the midi channel, in the range 1 to 16
  24538. @param controllerType the type of controller
  24539. @param value the controller value
  24540. @see isController
  24541. */
  24542. static const MidiMessage controllerEvent (int channel,
  24543. int controllerType,
  24544. int value) throw();
  24545. /** Checks whether this message is an all-notes-off message.
  24546. @see allNotesOff
  24547. */
  24548. bool isAllNotesOff() const throw();
  24549. /** Checks whether this message is an all-sound-off message.
  24550. @see allSoundOff
  24551. */
  24552. bool isAllSoundOff() const throw();
  24553. /** Creates an all-notes-off message.
  24554. @param channel the midi channel, in the range 1 to 16
  24555. @see isAllNotesOff
  24556. */
  24557. static const MidiMessage allNotesOff (int channel) throw();
  24558. /** Creates an all-sound-off message.
  24559. @param channel the midi channel, in the range 1 to 16
  24560. @see isAllSoundOff
  24561. */
  24562. static const MidiMessage allSoundOff (int channel) throw();
  24563. /** Creates an all-controllers-off message.
  24564. @param channel the midi channel, in the range 1 to 16
  24565. */
  24566. static const MidiMessage allControllersOff (int channel) throw();
  24567. /** Returns true if this event is a meta-event.
  24568. Meta-events are things like tempo changes, track names, etc.
  24569. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  24570. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  24571. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  24572. */
  24573. bool isMetaEvent() const throw();
  24574. /** Returns a meta-event's type number.
  24575. If the message isn't a meta-event, this will return -1.
  24576. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  24577. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  24578. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  24579. */
  24580. int getMetaEventType() const throw();
  24581. /** Returns a pointer to the data in a meta-event.
  24582. @see isMetaEvent, getMetaEventLength
  24583. */
  24584. const uint8* getMetaEventData() const throw();
  24585. /** Returns the length of the data for a meta-event.
  24586. @see isMetaEvent, getMetaEventData
  24587. */
  24588. int getMetaEventLength() const throw();
  24589. /** Returns true if this is a 'track' meta-event. */
  24590. bool isTrackMetaEvent() const throw();
  24591. /** Returns true if this is an 'end-of-track' meta-event. */
  24592. bool isEndOfTrackMetaEvent() const throw();
  24593. /** Creates an end-of-track meta-event.
  24594. @see isEndOfTrackMetaEvent
  24595. */
  24596. static const MidiMessage endOfTrack() throw();
  24597. /** Returns true if this is an 'track name' meta-event.
  24598. You can use the getTextFromTextMetaEvent() method to get the track's name.
  24599. */
  24600. bool isTrackNameEvent() const throw();
  24601. /** Returns true if this is a 'text' meta-event.
  24602. @see getTextFromTextMetaEvent
  24603. */
  24604. bool isTextMetaEvent() const throw();
  24605. /** Returns the text from a text meta-event.
  24606. @see isTextMetaEvent
  24607. */
  24608. const String getTextFromTextMetaEvent() const;
  24609. /** Returns true if this is a 'tempo' meta-event.
  24610. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  24611. */
  24612. bool isTempoMetaEvent() const throw();
  24613. /** Returns the tick length from a tempo meta-event.
  24614. @param timeFormat the 16-bit time format value from the midi file's header.
  24615. @returns the tick length (in seconds).
  24616. @see isTempoMetaEvent
  24617. */
  24618. double getTempoMetaEventTickLength (short timeFormat) const throw();
  24619. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  24620. @see isTempoMetaEvent, getTempoMetaEventTickLength
  24621. */
  24622. double getTempoSecondsPerQuarterNote() const throw();
  24623. /** Creates a tempo meta-event.
  24624. @see isTempoMetaEvent
  24625. */
  24626. static const MidiMessage tempoMetaEvent (int microsecondsPerQuarterNote) throw();
  24627. /** Returns true if this is a 'time-signature' meta-event.
  24628. @see getTimeSignatureInfo
  24629. */
  24630. bool isTimeSignatureMetaEvent() const throw();
  24631. /** Returns the time-signature values from a time-signature meta-event.
  24632. @see isTimeSignatureMetaEvent
  24633. */
  24634. void getTimeSignatureInfo (int& numerator, int& denominator) const throw();
  24635. /** Creates a time-signature meta-event.
  24636. @see isTimeSignatureMetaEvent
  24637. */
  24638. static const MidiMessage timeSignatureMetaEvent (int numerator, int denominator);
  24639. /** Returns true if this is a 'key-signature' meta-event.
  24640. @see getKeySignatureNumberOfSharpsOrFlats
  24641. */
  24642. bool isKeySignatureMetaEvent() const throw();
  24643. /** Returns the key from a key-signature meta-event.
  24644. @see isKeySignatureMetaEvent
  24645. */
  24646. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  24647. /** Returns true if this is a 'channel' meta-event.
  24648. A channel meta-event specifies the midi channel that should be used
  24649. for subsequent meta-events.
  24650. @see getMidiChannelMetaEventChannel
  24651. */
  24652. bool isMidiChannelMetaEvent() const throw();
  24653. /** Returns the channel number from a channel meta-event.
  24654. @returns the channel, in the range 1 to 16.
  24655. @see isMidiChannelMetaEvent
  24656. */
  24657. int getMidiChannelMetaEventChannel() const throw();
  24658. /** Creates a midi channel meta-event.
  24659. @param channel the midi channel, in the range 1 to 16
  24660. @see isMidiChannelMetaEvent
  24661. */
  24662. static const MidiMessage midiChannelMetaEvent (int channel) throw();
  24663. /** Returns true if this is an active-sense message. */
  24664. bool isActiveSense() const throw();
  24665. /** Returns true if this is a midi start event.
  24666. @see midiStart
  24667. */
  24668. bool isMidiStart() const throw();
  24669. /** Creates a midi start event. */
  24670. static const MidiMessage midiStart() throw();
  24671. /** Returns true if this is a midi continue event.
  24672. @see midiContinue
  24673. */
  24674. bool isMidiContinue() const throw();
  24675. /** Creates a midi continue event. */
  24676. static const MidiMessage midiContinue() throw();
  24677. /** Returns true if this is a midi stop event.
  24678. @see midiStop
  24679. */
  24680. bool isMidiStop() const throw();
  24681. /** Creates a midi stop event. */
  24682. static const MidiMessage midiStop() throw();
  24683. /** Returns true if this is a midi clock event.
  24684. @see midiClock, songPositionPointer
  24685. */
  24686. bool isMidiClock() const throw();
  24687. /** Creates a midi clock event. */
  24688. static const MidiMessage midiClock() throw();
  24689. /** Returns true if this is a song-position-pointer message.
  24690. @see getSongPositionPointerMidiBeat, songPositionPointer
  24691. */
  24692. bool isSongPositionPointer() const throw();
  24693. /** Returns the midi beat-number of a song-position-pointer message.
  24694. @see isSongPositionPointer, songPositionPointer
  24695. */
  24696. int getSongPositionPointerMidiBeat() const throw();
  24697. /** Creates a song-position-pointer message.
  24698. The position is a number of midi beats from the start of the song, where 1 midi
  24699. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  24700. are 4 midi beats in a quarter-note.
  24701. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  24702. */
  24703. static const MidiMessage songPositionPointer (int positionInMidiBeats) throw();
  24704. /** Returns true if this is a quarter-frame midi timecode message.
  24705. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  24706. */
  24707. bool isQuarterFrame() const throw();
  24708. /** Returns the sequence number of a quarter-frame midi timecode message.
  24709. This will be a value between 0 and 7.
  24710. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  24711. */
  24712. int getQuarterFrameSequenceNumber() const throw();
  24713. /** Returns the value from a quarter-frame message.
  24714. This will be the lower nybble of the message's data-byte, a value
  24715. between 0 and 15
  24716. */
  24717. int getQuarterFrameValue() const throw();
  24718. /** Creates a quarter-frame MTC message.
  24719. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  24720. @param value a value 0 to 15 for the lower nybble of the message's data byte
  24721. */
  24722. static const MidiMessage quarterFrame (int sequenceNumber, int value) throw();
  24723. /** SMPTE timecode types.
  24724. Used by the getFullFrameParameters() and fullFrame() methods.
  24725. */
  24726. enum SmpteTimecodeType
  24727. {
  24728. fps24 = 0,
  24729. fps25 = 1,
  24730. fps30drop = 2,
  24731. fps30 = 3
  24732. };
  24733. /** Returns true if this is a full-frame midi timecode message.
  24734. */
  24735. bool isFullFrame() const throw();
  24736. /** Extracts the timecode information from a full-frame midi timecode message.
  24737. You should only call this on messages where you've used isFullFrame() to
  24738. check that they're the right kind.
  24739. */
  24740. void getFullFrameParameters (int& hours,
  24741. int& minutes,
  24742. int& seconds,
  24743. int& frames,
  24744. SmpteTimecodeType& timecodeType) const throw();
  24745. /** Creates a full-frame MTC message.
  24746. */
  24747. static const MidiMessage fullFrame (int hours,
  24748. int minutes,
  24749. int seconds,
  24750. int frames,
  24751. SmpteTimecodeType timecodeType);
  24752. /** Types of MMC command.
  24753. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  24754. */
  24755. enum MidiMachineControlCommand
  24756. {
  24757. mmc_stop = 1,
  24758. mmc_play = 2,
  24759. mmc_deferredplay = 3,
  24760. mmc_fastforward = 4,
  24761. mmc_rewind = 5,
  24762. mmc_recordStart = 6,
  24763. mmc_recordStop = 7,
  24764. mmc_pause = 9
  24765. };
  24766. /** Checks whether this is an MMC message.
  24767. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  24768. */
  24769. bool isMidiMachineControlMessage() const throw();
  24770. /** For an MMC message, this returns its type.
  24771. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  24772. calling this method.
  24773. */
  24774. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  24775. /** Creates an MMC message.
  24776. */
  24777. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  24778. /** Checks whether this is an MMC "goto" message.
  24779. If it is, the parameters passed-in are set to the time that the message contains.
  24780. @see midiMachineControlGoto
  24781. */
  24782. bool isMidiMachineControlGoto (int& hours,
  24783. int& minutes,
  24784. int& seconds,
  24785. int& frames) const throw();
  24786. /** Creates an MMC "goto" message.
  24787. This messages tells the device to go to a specific frame.
  24788. @see isMidiMachineControlGoto
  24789. */
  24790. static const MidiMessage midiMachineControlGoto (int hours,
  24791. int minutes,
  24792. int seconds,
  24793. int frames);
  24794. /** Creates a master-volume change message.
  24795. @param volume the volume, 0 to 1.0
  24796. */
  24797. static const MidiMessage masterVolume (float volume);
  24798. /** Creates a system-exclusive message.
  24799. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  24800. */
  24801. static const MidiMessage createSysExMessage (const uint8* sysexData,
  24802. int dataSize);
  24803. /** Reads a midi variable-length integer.
  24804. @param data the data to read the number from
  24805. @param numBytesUsed on return, this will be set to the number of bytes that were read
  24806. */
  24807. static int readVariableLengthVal (const uint8* data,
  24808. int& numBytesUsed) throw();
  24809. /** Based on the first byte of a short midi message, this uses a lookup table
  24810. to return the message length (either 1, 2, or 3 bytes).
  24811. The value passed in must be 0x80 or higher.
  24812. */
  24813. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  24814. /** Returns the name of a midi note number.
  24815. E.g "C", "D#", etc.
  24816. @param noteNumber the midi note number, 0 to 127
  24817. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  24818. they'll be flattened, e.g. "Db"
  24819. @param includeOctaveNumber if true, the octave number will be appended to the string,
  24820. e.g. "C#4"
  24821. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  24822. number that will be used for middle C's octave
  24823. @see getMidiNoteInHertz
  24824. */
  24825. static const String getMidiNoteName (int noteNumber,
  24826. bool useSharps,
  24827. bool includeOctaveNumber,
  24828. int octaveNumForMiddleC) throw();
  24829. /** Returns the frequency of a midi note number.
  24830. @see getMidiNoteName
  24831. */
  24832. static const double getMidiNoteInHertz (int noteNumber) throw();
  24833. /** Returns the standard name of a GM instrument.
  24834. @param midiInstrumentNumber the program number 0 to 127
  24835. @see getProgramChangeNumber
  24836. */
  24837. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  24838. /** Returns the name of a bank of GM instruments.
  24839. @param midiBankNumber the bank, 0 to 15
  24840. */
  24841. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  24842. /** Returns the standard name of a channel 10 percussion sound.
  24843. @param midiNoteNumber the key number, 35 to 81
  24844. */
  24845. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  24846. /** Returns the name of a controller type number.
  24847. @see getControllerNumber
  24848. */
  24849. static const String getControllerName (int controllerNumber) throw();
  24850. juce_UseDebuggingNewOperator
  24851. private:
  24852. double timeStamp;
  24853. uint8* data;
  24854. int size;
  24855. union
  24856. {
  24857. uint8 asBytes[4];
  24858. uint32 asInt32;
  24859. } preallocatedData;
  24860. };
  24861. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  24862. /*** End of inlined file: juce_MidiMessage.h ***/
  24863. class MidiInput;
  24864. /**
  24865. Receives midi messages from a midi input device.
  24866. This class is overridden to handle incoming midi messages. See the MidiInput
  24867. class for more details.
  24868. @see MidiInput
  24869. */
  24870. class JUCE_API MidiInputCallback
  24871. {
  24872. public:
  24873. /** Destructor. */
  24874. virtual ~MidiInputCallback() {}
  24875. /** Receives an incoming message.
  24876. A MidiInput object will call this method when a midi event arrives. It'll be
  24877. called on a high-priority system thread, so avoid doing anything time-consuming
  24878. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  24879. for queueing incoming messages for use later.
  24880. @param source the MidiInput object that generated the message
  24881. @param message the incoming message. The message's timestamp is set to a value
  24882. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  24883. time when the message arrived.
  24884. */
  24885. virtual void handleIncomingMidiMessage (MidiInput* source,
  24886. const MidiMessage& message) = 0;
  24887. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  24888. If a long sysex message is broken up into multiple packets, this callback is made
  24889. for each packet that arrives until the message is finished, at which point
  24890. the normal handleIncomingMidiMessage() callback will be made with the entire
  24891. message.
  24892. The message passed in will contain the start of a sysex, but won't be finished
  24893. with the terminating 0xf7 byte.
  24894. */
  24895. virtual void handlePartialSysexMessage (MidiInput* source,
  24896. const uint8* messageData,
  24897. const int numBytesSoFar,
  24898. const double timestamp)
  24899. {
  24900. // (this bit is just to avoid compiler warnings about unused variables)
  24901. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  24902. }
  24903. };
  24904. /**
  24905. Represents a midi input device.
  24906. To create one of these, use the static getDevices() method to find out what inputs are
  24907. available, and then use the openDevice() method to try to open one.
  24908. @see MidiOutput
  24909. */
  24910. class JUCE_API MidiInput
  24911. {
  24912. public:
  24913. /** Returns a list of the available midi input devices.
  24914. You can open one of the devices by passing its index into the
  24915. openDevice() method.
  24916. @see getDefaultDeviceIndex, openDevice
  24917. */
  24918. static const StringArray getDevices();
  24919. /** Returns the index of the default midi input device to use.
  24920. This refers to the index in the list returned by getDevices().
  24921. */
  24922. static int getDefaultDeviceIndex();
  24923. /** Tries to open one of the midi input devices.
  24924. This will return a MidiInput object if it manages to open it. You can then
  24925. call start() and stop() on this device, and delete it when no longer needed.
  24926. If the device can't be opened, this will return a null pointer.
  24927. @param deviceIndex the index of a device from the list returned by getDevices()
  24928. @param callback the object that will receive the midi messages from this device.
  24929. @see MidiInputCallback, getDevices
  24930. */
  24931. static MidiInput* openDevice (int deviceIndex,
  24932. MidiInputCallback* callback);
  24933. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  24934. /** This will try to create a new midi input device (Not available on Windows).
  24935. This will attempt to create a new midi input device with the specified name,
  24936. for other apps to connect to.
  24937. Returns 0 if a device can't be created.
  24938. @param deviceName the name to use for the new device
  24939. @param callback the object that will receive the midi messages from this device.
  24940. */
  24941. static MidiInput* createNewDevice (const String& deviceName,
  24942. MidiInputCallback* callback);
  24943. #endif
  24944. /** Destructor. */
  24945. virtual ~MidiInput();
  24946. /** Returns the name of this device.
  24947. */
  24948. virtual const String getName() const throw() { return name; }
  24949. /** Allows you to set a custom name for the device, in case you don't like the name
  24950. it was given when created.
  24951. */
  24952. virtual void setName (const String& newName) throw() { name = newName; }
  24953. /** Starts the device running.
  24954. After calling this, the device will start sending midi messages to the
  24955. MidiInputCallback object that was specified when the openDevice() method
  24956. was called.
  24957. @see stop
  24958. */
  24959. virtual void start();
  24960. /** Stops the device running.
  24961. @see start
  24962. */
  24963. virtual void stop();
  24964. juce_UseDebuggingNewOperator
  24965. protected:
  24966. String name;
  24967. void* internal;
  24968. explicit MidiInput (const String& name);
  24969. private:
  24970. MidiInput (const MidiInput&);
  24971. MidiInput& operator= (const MidiInput&);
  24972. };
  24973. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  24974. /*** End of inlined file: juce_MidiInput.h ***/
  24975. /*** Start of inlined file: juce_MidiOutput.h ***/
  24976. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  24977. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  24978. /*** Start of inlined file: juce_MidiBuffer.h ***/
  24979. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  24980. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  24981. /**
  24982. Holds a sequence of time-stamped midi events.
  24983. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  24984. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  24985. @see MidiMessage
  24986. */
  24987. class JUCE_API MidiBuffer
  24988. {
  24989. public:
  24990. /** Creates an empty MidiBuffer. */
  24991. MidiBuffer() throw();
  24992. /** Creates a MidiBuffer containing a single midi message. */
  24993. explicit MidiBuffer (const MidiMessage& message) throw();
  24994. /** Creates a copy of another MidiBuffer. */
  24995. MidiBuffer (const MidiBuffer& other) throw();
  24996. /** Makes a copy of another MidiBuffer. */
  24997. MidiBuffer& operator= (const MidiBuffer& other) throw();
  24998. /** Destructor */
  24999. ~MidiBuffer() throw();
  25000. /** Removes all events from the buffer. */
  25001. void clear() throw();
  25002. /** Removes all events between two times from the buffer.
  25003. All events for which (start <= event position < start + numSamples) will
  25004. be removed.
  25005. */
  25006. void clear (const int start,
  25007. const int numSamples) throw();
  25008. /** Returns true if the buffer is empty.
  25009. To actually retrieve the events, use a MidiBuffer::Iterator object
  25010. */
  25011. bool isEmpty() const throw();
  25012. /** Counts the number of events in the buffer.
  25013. This is actually quite a slow operation, as it has to iterate through all
  25014. the events, so you might prefer to call isEmpty() if that's all you need
  25015. to know.
  25016. */
  25017. int getNumEvents() const throw();
  25018. /** Adds an event to the buffer.
  25019. The sample number will be used to determine the position of the event in
  25020. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  25021. ignored.
  25022. If an event is added whose sample position is the same as one or more events
  25023. already in the buffer, the new event will be placed after the existing ones.
  25024. To retrieve events, use a MidiBuffer::Iterator object
  25025. */
  25026. void addEvent (const MidiMessage& midiMessage,
  25027. const int sampleNumber) throw();
  25028. /** Adds an event to the buffer from raw midi data.
  25029. The sample number will be used to determine the position of the event in
  25030. the buffer, which is always kept sorted.
  25031. If an event is added whose sample position is the same as one or more events
  25032. already in the buffer, the new event will be placed after the existing ones.
  25033. The event data will be inspected to calculate the number of bytes in length that
  25034. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  25035. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  25036. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  25037. add an event at all.
  25038. To retrieve events, use a MidiBuffer::Iterator object
  25039. */
  25040. void addEvent (const uint8* const rawMidiData,
  25041. const int maxBytesOfMidiData,
  25042. const int sampleNumber) throw();
  25043. /** Adds some events from another buffer to this one.
  25044. @param otherBuffer the buffer containing the events you want to add
  25045. @param startSample the lowest sample number in the source buffer for which
  25046. events should be added. Any source events whose timestamp is
  25047. less than this will be ignored
  25048. @param numSamples the valid range of samples from the source buffer for which
  25049. events should be added - i.e. events in the source buffer whose
  25050. timestamp is greater than or equal to (startSample + numSamples)
  25051. will be ignored. If this value is less than 0, all events after
  25052. startSample will be taken.
  25053. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  25054. that are added to this buffer
  25055. */
  25056. void addEvents (const MidiBuffer& otherBuffer,
  25057. const int startSample,
  25058. const int numSamples,
  25059. const int sampleDeltaToAdd) throw();
  25060. /** Returns the sample number of the first event in the buffer.
  25061. If the buffer's empty, this will just return 0.
  25062. */
  25063. int getFirstEventTime() const throw();
  25064. /** Returns the sample number of the last event in the buffer.
  25065. If the buffer's empty, this will just return 0.
  25066. */
  25067. int getLastEventTime() const throw();
  25068. /** Exchanges the contents of this buffer with another one.
  25069. This is a quick operation, because no memory allocating or copying is done, it
  25070. just swaps the internal state of the two buffers.
  25071. */
  25072. void swapWith (MidiBuffer& other);
  25073. /** Preallocates some memory for the buffer to use.
  25074. This helps to avoid needing to reallocate space when the buffer has messages
  25075. added to it.
  25076. */
  25077. void ensureSize (size_t minimumNumBytes);
  25078. /**
  25079. Used to iterate through the events in a MidiBuffer.
  25080. Note that altering the buffer while an iterator is using it isn't a
  25081. safe operation.
  25082. @see MidiBuffer
  25083. */
  25084. class Iterator
  25085. {
  25086. public:
  25087. /** Creates an Iterator for this MidiBuffer. */
  25088. Iterator (const MidiBuffer& buffer) throw();
  25089. /** Destructor. */
  25090. ~Iterator() throw();
  25091. /** Repositions the iterator so that the next event retrieved will be the first
  25092. one whose sample position is at greater than or equal to the given position.
  25093. */
  25094. void setNextSamplePosition (const int samplePosition) throw();
  25095. /** Retrieves a copy of the next event from the buffer.
  25096. @param result on return, this will be the message (the MidiMessage's timestamp
  25097. is not set)
  25098. @param samplePosition on return, this will be the position of the event
  25099. @returns true if an event was found, or false if the iterator has reached
  25100. the end of the buffer
  25101. */
  25102. bool getNextEvent (MidiMessage& result,
  25103. int& samplePosition) throw();
  25104. /** Retrieves the next event from the buffer.
  25105. @param midiData on return, this pointer will be set to a block of data containing
  25106. the midi message. Note that to make it fast, this is a pointer
  25107. directly into the MidiBuffer's internal data, so is only valid
  25108. temporarily until the MidiBuffer is altered.
  25109. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  25110. midi message
  25111. @param samplePosition on return, this will be the position of the event
  25112. @returns true if an event was found, or false if the iterator has reached
  25113. the end of the buffer
  25114. */
  25115. bool getNextEvent (const uint8* &midiData,
  25116. int& numBytesOfMidiData,
  25117. int& samplePosition) throw();
  25118. juce_UseDebuggingNewOperator
  25119. private:
  25120. const MidiBuffer& buffer;
  25121. const uint8* data;
  25122. Iterator (const Iterator&);
  25123. Iterator& operator= (const Iterator&);
  25124. };
  25125. juce_UseDebuggingNewOperator
  25126. private:
  25127. friend class MidiBuffer::Iterator;
  25128. MemoryBlock data;
  25129. int bytesUsed;
  25130. uint8* getData() const throw();
  25131. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  25132. static int getEventTime (const void* d) throw();
  25133. static uint16 getEventDataSize (const void* d) throw();
  25134. static uint16 getEventTotalSize (const void* d) throw();
  25135. };
  25136. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  25137. /*** End of inlined file: juce_MidiBuffer.h ***/
  25138. /**
  25139. Represents a midi output device.
  25140. To create one of these, use the static getDevices() method to find out what
  25141. outputs are available, then use the openDevice() method to try to open one.
  25142. @see MidiInput
  25143. */
  25144. class JUCE_API MidiOutput : private Thread
  25145. {
  25146. public:
  25147. /** Returns a list of the available midi output devices.
  25148. You can open one of the devices by passing its index into the
  25149. openDevice() method.
  25150. @see getDefaultDeviceIndex, openDevice
  25151. */
  25152. static const StringArray getDevices();
  25153. /** Returns the index of the default midi output device to use.
  25154. This refers to the index in the list returned by getDevices().
  25155. */
  25156. static int getDefaultDeviceIndex();
  25157. /** Tries to open one of the midi output devices.
  25158. This will return a MidiOutput object if it manages to open it. You can then
  25159. send messages to this device, and delete it when no longer needed.
  25160. If the device can't be opened, this will return a null pointer.
  25161. @param deviceIndex the index of a device from the list returned by getDevices()
  25162. @see getDevices
  25163. */
  25164. static MidiOutput* openDevice (int deviceIndex);
  25165. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  25166. /** This will try to create a new midi output device (Not available on Windows).
  25167. This will attempt to create a new midi output device that other apps can connect
  25168. to and use as their midi input.
  25169. Returns 0 if a device can't be created.
  25170. @param deviceName the name to use for the new device
  25171. */
  25172. static MidiOutput* createNewDevice (const String& deviceName);
  25173. #endif
  25174. /** Destructor. */
  25175. virtual ~MidiOutput();
  25176. /** Makes this device output a midi message.
  25177. @see MidiMessage
  25178. */
  25179. virtual void sendMessageNow (const MidiMessage& message);
  25180. /** Sends a midi reset to the device. */
  25181. virtual void reset();
  25182. /** Returns the current volume setting for this device. */
  25183. virtual bool getVolume (float& leftVol,
  25184. float& rightVol);
  25185. /** Changes the overall volume for this device. */
  25186. virtual void setVolume (float leftVol,
  25187. float rightVol);
  25188. /** This lets you supply a block of messages that will be sent out at some point
  25189. in the future.
  25190. The MidiOutput class has an internal thread that can send out timestamped
  25191. messages - this appends a set of messages to its internal buffer, ready for
  25192. sending.
  25193. This will only work if you've already started the thread with startBackgroundThread().
  25194. A time is supplied, at which the block of messages should be sent. This time uses
  25195. the same time base as Time::getMillisecondCounter(), and must be in the future.
  25196. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  25197. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  25198. samplesPerSecondForBuffer value is needed to convert this sample position to a
  25199. real time.
  25200. */
  25201. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  25202. double millisecondCounterToStartAt,
  25203. double samplesPerSecondForBuffer);
  25204. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  25205. */
  25206. virtual void clearAllPendingMessages();
  25207. /** Starts up a background thread so that the device can send blocks of data.
  25208. Call this to get the device ready, before using sendBlockOfMessages().
  25209. */
  25210. virtual void startBackgroundThread();
  25211. /** Stops the background thread, and clears any pending midi events.
  25212. @see startBackgroundThread
  25213. */
  25214. virtual void stopBackgroundThread();
  25215. juce_UseDebuggingNewOperator
  25216. protected:
  25217. void* internal;
  25218. struct PendingMessage
  25219. {
  25220. PendingMessage (const uint8* data, int len, double sampleNumber);
  25221. MidiMessage message;
  25222. PendingMessage* next;
  25223. juce_UseDebuggingNewOperator
  25224. };
  25225. CriticalSection lock;
  25226. PendingMessage* firstMessage;
  25227. MidiOutput();
  25228. void run();
  25229. private:
  25230. MidiOutput (const MidiOutput&);
  25231. MidiOutput& operator= (const MidiOutput&);
  25232. };
  25233. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  25234. /*** End of inlined file: juce_MidiOutput.h ***/
  25235. /*** Start of inlined file: juce_ComboBox.h ***/
  25236. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  25237. #define __JUCE_COMBOBOX_JUCEHEADER__
  25238. /*** Start of inlined file: juce_Label.h ***/
  25239. #ifndef __JUCE_LABEL_JUCEHEADER__
  25240. #define __JUCE_LABEL_JUCEHEADER__
  25241. /*** Start of inlined file: juce_TextEditor.h ***/
  25242. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  25243. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  25244. /*** Start of inlined file: juce_Viewport.h ***/
  25245. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  25246. #define __JUCE_VIEWPORT_JUCEHEADER__
  25247. /*** Start of inlined file: juce_ScrollBar.h ***/
  25248. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  25249. #define __JUCE_SCROLLBAR_JUCEHEADER__
  25250. /*** Start of inlined file: juce_Button.h ***/
  25251. #ifndef __JUCE_BUTTON_JUCEHEADER__
  25252. #define __JUCE_BUTTON_JUCEHEADER__
  25253. /*** Start of inlined file: juce_TooltipWindow.h ***/
  25254. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  25255. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  25256. /*** Start of inlined file: juce_TooltipClient.h ***/
  25257. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  25258. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  25259. /**
  25260. Components that want to use pop-up tooltips should implement this interface.
  25261. A TooltipWindow will wait for the mouse to hover over a component that
  25262. implements the TooltipClient interface, and when it finds one, it will display
  25263. the tooltip returned by its getTooltip() method.
  25264. @see TooltipWindow, SettableTooltipClient
  25265. */
  25266. class JUCE_API TooltipClient
  25267. {
  25268. public:
  25269. /** Destructor. */
  25270. virtual ~TooltipClient() {}
  25271. /** Returns the string that this object wants to show as its tooltip. */
  25272. virtual const String getTooltip() = 0;
  25273. };
  25274. /**
  25275. An implementation of TooltipClient that stores the tooltip string and a method
  25276. for changing it.
  25277. This makes it easy to add a tooltip to a custom component, by simply adding this
  25278. as a base class and calling setTooltip().
  25279. Many of the Juce widgets already use this as a base class to implement their
  25280. tooltips.
  25281. @see TooltipClient, TooltipWindow
  25282. */
  25283. class JUCE_API SettableTooltipClient : public TooltipClient
  25284. {
  25285. public:
  25286. /** Destructor. */
  25287. virtual ~SettableTooltipClient() {}
  25288. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  25289. virtual const String getTooltip() { return tooltipString; }
  25290. juce_UseDebuggingNewOperator
  25291. protected:
  25292. String tooltipString;
  25293. };
  25294. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  25295. /*** End of inlined file: juce_TooltipClient.h ***/
  25296. /**
  25297. A window that displays a pop-up tooltip when the mouse hovers over another component.
  25298. To enable tooltips in your app, just create a single instance of a TooltipWindow
  25299. object.
  25300. The TooltipWindow object will then stay invisible, waiting until the mouse
  25301. hovers for the specified length of time - it will then see if it's currently
  25302. over a component which implements the TooltipClient interface, and if so,
  25303. it will make itself visible to show the tooltip in the appropriate place.
  25304. @see TooltipClient, SettableTooltipClient
  25305. */
  25306. class JUCE_API TooltipWindow : public Component,
  25307. private Timer
  25308. {
  25309. public:
  25310. /** Creates a tooltip window.
  25311. Make sure your app only creates one instance of this class, otherwise you'll
  25312. get multiple overlaid tooltips appearing. The window will initially be invisible
  25313. and will make itself visible when it needs to display a tip.
  25314. To change the style of tooltips, see the LookAndFeel class for its tooltip
  25315. methods.
  25316. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  25317. otherwise the tooltip will be added to the given parent
  25318. component.
  25319. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  25320. before a tooltip will be shown
  25321. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  25322. */
  25323. explicit TooltipWindow (Component* parentComponent = 0,
  25324. int millisecondsBeforeTipAppears = 700);
  25325. /** Destructor. */
  25326. ~TooltipWindow();
  25327. /** Changes the time before the tip appears.
  25328. This lets you change the value that was set in the constructor.
  25329. */
  25330. void setMillisecondsBeforeTipAppears (int newTimeMs = 700) throw();
  25331. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  25332. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25333. methods.
  25334. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25335. */
  25336. enum ColourIds
  25337. {
  25338. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  25339. textColourId = 0x1001c00, /**< The colour to use for the text. */
  25340. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  25341. };
  25342. juce_UseDebuggingNewOperator
  25343. private:
  25344. int millisecondsBeforeTipAppears;
  25345. Point<int> lastMousePos;
  25346. int mouseClicks;
  25347. unsigned int lastCompChangeTime, lastHideTime;
  25348. Component* lastComponentUnderMouse;
  25349. bool changedCompsSinceShown;
  25350. String tipShowing, lastTipUnderMouse;
  25351. void paint (Graphics& g);
  25352. void mouseEnter (const MouseEvent& e);
  25353. void timerCallback();
  25354. static const String getTipFor (Component* c);
  25355. void showFor (const String& tip);
  25356. void hide();
  25357. TooltipWindow (const TooltipWindow&);
  25358. TooltipWindow& operator= (const TooltipWindow&);
  25359. };
  25360. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  25361. /*** End of inlined file: juce_TooltipWindow.h ***/
  25362. class Button;
  25363. /**
  25364. Used to receive callbacks when a button is clicked.
  25365. @see Button::addButtonListener, Button::removeButtonListener
  25366. */
  25367. class JUCE_API ButtonListener
  25368. {
  25369. public:
  25370. /** Destructor. */
  25371. virtual ~ButtonListener() {}
  25372. /** Called when the button is clicked. */
  25373. virtual void buttonClicked (Button* button) = 0;
  25374. /** Called when the button's state changes. */
  25375. virtual void buttonStateChanged (Button*) {}
  25376. };
  25377. /**
  25378. A base class for buttons.
  25379. This contains all the logic for button behaviours such as enabling/disabling,
  25380. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  25381. and radio groups, etc.
  25382. @see TextButton, DrawableButton, ToggleButton
  25383. */
  25384. class JUCE_API Button : public Component,
  25385. public SettableTooltipClient,
  25386. public ApplicationCommandManagerListener,
  25387. public Value::Listener,
  25388. private KeyListener
  25389. {
  25390. protected:
  25391. /** Creates a button.
  25392. @param buttonName the text to put in the button (the component's name is also
  25393. initially set to this string, but these can be changed later
  25394. using the setName() and setButtonText() methods)
  25395. */
  25396. explicit Button (const String& buttonName);
  25397. public:
  25398. /** Destructor. */
  25399. virtual ~Button();
  25400. /** Changes the button's text.
  25401. @see getButtonText
  25402. */
  25403. void setButtonText (const String& newText);
  25404. /** Returns the text displayed in the button.
  25405. @see setButtonText
  25406. */
  25407. const String getButtonText() const { return text; }
  25408. /** Returns true if the button is currently being held down by the mouse.
  25409. @see isOver
  25410. */
  25411. bool isDown() const throw();
  25412. /** Returns true if the mouse is currently over the button.
  25413. This will be also be true if the mouse is being held down.
  25414. @see isDown
  25415. */
  25416. bool isOver() const throw();
  25417. /** A button has an on/off state associated with it, and this changes that.
  25418. By default buttons are 'off' and for simple buttons that you click to perform
  25419. an action you won't change this. Toggle buttons, however will want to
  25420. change their state when turned on or off.
  25421. @param shouldBeOn whether to set the button's toggle state to be on or
  25422. off. If it's a member of a button group, this will
  25423. always try to turn it on, and to turn off any other
  25424. buttons in the group
  25425. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  25426. the button will be repainted but no notification will
  25427. be sent
  25428. @see getToggleState, setRadioGroupId
  25429. */
  25430. void setToggleState (bool shouldBeOn,
  25431. bool sendChangeNotification);
  25432. /** Returns true if the button in 'on'.
  25433. By default buttons are 'off' and for simple buttons that you click to perform
  25434. an action you won't change this. Toggle buttons, however will want to
  25435. change their state when turned on or off.
  25436. @see setToggleState
  25437. */
  25438. bool getToggleState() const throw() { return isOn.getValue(); }
  25439. /** Returns the Value object that represents the botton's toggle state.
  25440. You can use this Value object to connect the button's state to external values or setters,
  25441. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  25442. your own Value object.
  25443. @see getToggleState, Value
  25444. */
  25445. Value& getToggleStateValue() { return isOn; }
  25446. /** This tells the button to automatically flip the toggle state when
  25447. the button is clicked.
  25448. If set to true, then before the clicked() callback occurs, the toggle-state
  25449. of the button is flipped.
  25450. */
  25451. void setClickingTogglesState (bool shouldToggle) throw();
  25452. /** Returns true if this button is set to be an automatic toggle-button.
  25453. This returns the last value that was passed to setClickingTogglesState().
  25454. */
  25455. bool getClickingTogglesState() const throw();
  25456. /** Enables the button to act as a member of a mutually-exclusive group
  25457. of 'radio buttons'.
  25458. If the group ID is set to a non-zero number, then this button will
  25459. act as part of a group of buttons with the same ID, only one of
  25460. which can be 'on' at the same time. Note that when it's part of
  25461. a group, clicking a toggle-button that's 'on' won't turn it off.
  25462. To find other buttons with the same ID, this button will search through
  25463. its sibling components for ToggleButtons, so all the buttons for a
  25464. particular group must be placed inside the same parent component.
  25465. Set the group ID back to zero if you want it to act as a normal toggle
  25466. button again.
  25467. @see getRadioGroupId
  25468. */
  25469. void setRadioGroupId (int newGroupId);
  25470. /** Returns the ID of the group to which this button belongs.
  25471. (See setRadioGroupId() for an explanation of this).
  25472. */
  25473. int getRadioGroupId() const throw() { return radioGroupId; }
  25474. /** Registers a listener to receive events when this button's state changes.
  25475. If the listener is already registered, this will not register it again.
  25476. @see removeButtonListener
  25477. */
  25478. void addButtonListener (ButtonListener* newListener);
  25479. /** Removes a previously-registered button listener
  25480. @see addButtonListener
  25481. */
  25482. void removeButtonListener (ButtonListener* listener);
  25483. /** Causes the button to act as if it's been clicked.
  25484. This will asynchronously make the button draw itself going down and up, and
  25485. will then call back the clicked() method as if mouse was clicked on it.
  25486. @see clicked
  25487. */
  25488. virtual void triggerClick();
  25489. /** Sets a command ID for this button to automatically invoke when it's clicked.
  25490. When the button is pressed, it will use the given manager to trigger the
  25491. command ID.
  25492. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  25493. before this button is. To disable the command triggering, call this method and
  25494. pass 0 for the parameters.
  25495. If generateTooltip is true, then the button's tooltip will be automatically
  25496. generated based on the name of this command and its current shortcut key.
  25497. @see addShortcut, getCommandID
  25498. */
  25499. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  25500. int commandID,
  25501. bool generateTooltip);
  25502. /** Returns the command ID that was set by setCommandToTrigger().
  25503. */
  25504. int getCommandID() const throw() { return commandID; }
  25505. /** Assigns a shortcut key to trigger the button.
  25506. The button registers itself with its top-level parent component for keypresses.
  25507. Note that a different way of linking buttons to keypresses is by using the
  25508. setCommandToTrigger() method to invoke a command.
  25509. @see clearShortcuts
  25510. */
  25511. void addShortcut (const KeyPress& key);
  25512. /** Removes all key shortcuts that had been set for this button.
  25513. @see addShortcut
  25514. */
  25515. void clearShortcuts();
  25516. /** Returns true if the given keypress is a shortcut for this button.
  25517. @see addShortcut
  25518. */
  25519. bool isRegisteredForShortcut (const KeyPress& key) const;
  25520. /** Sets an auto-repeat speed for the button when it is held down.
  25521. (Auto-repeat is disabled by default).
  25522. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  25523. triggering the next click. If this is zero, auto-repeat
  25524. is disabled
  25525. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  25526. triggered
  25527. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  25528. get faster, the longer the button is held down, up to the
  25529. minimum interval specified here
  25530. */
  25531. void setRepeatSpeed (int initialDelayInMillisecs,
  25532. int repeatDelayInMillisecs,
  25533. int minimumDelayInMillisecs = -1) throw();
  25534. /** Sets whether the button click should happen when the mouse is pressed or released.
  25535. By default the button is only considered to have been clicked when the mouse is
  25536. released, but setting this to true will make it call the clicked() method as soon
  25537. as the button is pressed.
  25538. This is useful if the button is being used to show a pop-up menu, as it allows
  25539. the click to be used as a drag onto the menu.
  25540. */
  25541. void setTriggeredOnMouseDown (bool isTriggeredOnMouseDown) throw();
  25542. /** Returns the number of milliseconds since the last time the button
  25543. went into the 'down' state.
  25544. */
  25545. uint32 getMillisecondsSinceButtonDown() const throw();
  25546. /** (overridden from Component to do special stuff). */
  25547. void setVisible (bool shouldBeVisible);
  25548. /** Sets the tooltip for this button.
  25549. @see TooltipClient, TooltipWindow
  25550. */
  25551. void setTooltip (const String& newTooltip);
  25552. // (implementation of the TooltipClient method)
  25553. const String getTooltip();
  25554. /** A combination of these flags are used by setConnectedEdges().
  25555. */
  25556. enum ConnectedEdgeFlags
  25557. {
  25558. ConnectedOnLeft = 1,
  25559. ConnectedOnRight = 2,
  25560. ConnectedOnTop = 4,
  25561. ConnectedOnBottom = 8
  25562. };
  25563. /** Hints about which edges of the button might be connected to adjoining buttons.
  25564. The value passed in is a bitwise combination of any of the values in the
  25565. ConnectedEdgeFlags enum.
  25566. E.g. if you are placing two buttons adjacent to each other, you could use this to
  25567. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  25568. without rounded corners on the edges that connect. It's only a hint, so the
  25569. LookAndFeel can choose to ignore it if it's not relevent for this type of
  25570. button.
  25571. */
  25572. void setConnectedEdges (int connectedEdgeFlags);
  25573. /** Returns the set of flags passed into setConnectedEdges(). */
  25574. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  25575. /** Indicates whether the button adjoins another one on its left edge.
  25576. @see setConnectedEdges
  25577. */
  25578. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  25579. /** Indicates whether the button adjoins another one on its right edge.
  25580. @see setConnectedEdges
  25581. */
  25582. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  25583. /** Indicates whether the button adjoins another one on its top edge.
  25584. @see setConnectedEdges
  25585. */
  25586. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  25587. /** Indicates whether the button adjoins another one on its bottom edge.
  25588. @see setConnectedEdges
  25589. */
  25590. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  25591. /** Used by setState(). */
  25592. enum ButtonState
  25593. {
  25594. buttonNormal,
  25595. buttonOver,
  25596. buttonDown
  25597. };
  25598. /** Can be used to force the button into a particular state.
  25599. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  25600. from happening.
  25601. The state that you set here will only last until it is automatically changed when the mouse
  25602. enters or exits the button, or the mouse-button is pressed or released.
  25603. */
  25604. void setState (const ButtonState newState);
  25605. juce_UseDebuggingNewOperator
  25606. protected:
  25607. /** This method is called when the button has been clicked.
  25608. Subclasses can override this to perform whatever they actions they need
  25609. to do.
  25610. Alternatively, a ButtonListener can be added to the button, and these listeners
  25611. will be called when the click occurs.
  25612. @see triggerClick
  25613. */
  25614. virtual void clicked();
  25615. /** This method is called when the button has been clicked.
  25616. By default it just calls clicked(), but you might want to override it to handle
  25617. things like clicking when a modifier key is pressed, etc.
  25618. @see ModifierKeys
  25619. */
  25620. virtual void clicked (const ModifierKeys& modifiers);
  25621. /** Subclasses should override this to actually paint the button's contents.
  25622. It's better to use this than the paint method, because it gives you information
  25623. about the over/down state of the button.
  25624. @param g the graphics context to use
  25625. @param isMouseOverButton true if the button is either in the 'over' or
  25626. 'down' state
  25627. @param isButtonDown true if the button should be drawn in the 'down' position
  25628. */
  25629. virtual void paintButton (Graphics& g,
  25630. bool isMouseOverButton,
  25631. bool isButtonDown) = 0;
  25632. /** Called when the button's up/down/over state changes.
  25633. Subclasses can override this if they need to do something special when the button
  25634. goes up or down.
  25635. @see isDown, isOver
  25636. */
  25637. virtual void buttonStateChanged();
  25638. /** @internal */
  25639. virtual void internalClickCallback (const ModifierKeys& modifiers);
  25640. /** @internal */
  25641. void handleCommandMessage (int commandId);
  25642. /** @internal */
  25643. void mouseEnter (const MouseEvent& e);
  25644. /** @internal */
  25645. void mouseExit (const MouseEvent& e);
  25646. /** @internal */
  25647. void mouseDown (const MouseEvent& e);
  25648. /** @internal */
  25649. void mouseDrag (const MouseEvent& e);
  25650. /** @internal */
  25651. void mouseUp (const MouseEvent& e);
  25652. /** @internal */
  25653. bool keyPressed (const KeyPress& key);
  25654. /** @internal */
  25655. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  25656. /** @internal */
  25657. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  25658. /** @internal */
  25659. void paint (Graphics& g);
  25660. /** @internal */
  25661. void parentHierarchyChanged();
  25662. /** @internal */
  25663. void focusGained (FocusChangeType cause);
  25664. /** @internal */
  25665. void focusLost (FocusChangeType cause);
  25666. /** @internal */
  25667. void enablementChanged();
  25668. /** @internal */
  25669. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  25670. /** @internal */
  25671. void applicationCommandListChanged();
  25672. /** @internal */
  25673. void valueChanged (Value& value);
  25674. private:
  25675. Array <KeyPress> shortcuts;
  25676. Component::SafePointer<Component> keySource;
  25677. String text;
  25678. ListenerList <ButtonListener> buttonListeners;
  25679. class RepeatTimer;
  25680. friend class RepeatTimer;
  25681. friend class ScopedPointer <RepeatTimer>;
  25682. ScopedPointer <RepeatTimer> repeatTimer;
  25683. uint32 buttonPressTime, lastTimeCallbackTime;
  25684. ApplicationCommandManager* commandManagerToUse;
  25685. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  25686. int radioGroupId, commandID, connectedEdgeFlags;
  25687. ButtonState buttonState;
  25688. Value isOn;
  25689. bool lastToggleState : 1;
  25690. bool clickTogglesState : 1;
  25691. bool needsToRelease : 1;
  25692. bool needsRepainting : 1;
  25693. bool isKeyDown : 1;
  25694. bool triggerOnMouseDown : 1;
  25695. bool generateTooltip : 1;
  25696. void repeatTimerCallback();
  25697. RepeatTimer& getRepeatTimer();
  25698. ButtonState updateState (const MouseEvent* const e);
  25699. bool isShortcutPressed() const;
  25700. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  25701. void flashButtonState();
  25702. void sendClickMessage (const ModifierKeys& modifiers);
  25703. void sendStateMessage();
  25704. Button (const Button&);
  25705. Button& operator= (const Button&);
  25706. };
  25707. #endif // __JUCE_BUTTON_JUCEHEADER__
  25708. /*** End of inlined file: juce_Button.h ***/
  25709. class ScrollBar;
  25710. /**
  25711. A class for receiving events from a ScrollBar.
  25712. You can register a ScrollBarListener with a ScrollBar using the ScrollBar::addListener()
  25713. method, and it will be called when the bar's position changes.
  25714. @see ScrollBar::addListener, ScrollBar::removeListener
  25715. */
  25716. class JUCE_API ScrollBarListener
  25717. {
  25718. public:
  25719. /** Destructor. */
  25720. virtual ~ScrollBarListener() {}
  25721. /** Called when a ScrollBar is moved.
  25722. @param scrollBarThatHasMoved the bar that has moved
  25723. @param newRangeStart the new range start of this bar
  25724. */
  25725. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  25726. double newRangeStart) = 0;
  25727. };
  25728. /**
  25729. A scrollbar component.
  25730. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  25731. sets the range of values it can represent. Then you can use setCurrentRange() to
  25732. change the position and size of the scrollbar's 'thumb'.
  25733. Registering a ScrollBarListener with the scrollbar will allow you to find out when
  25734. the user moves it, and you can use the getCurrentRangeStart() to find out where
  25735. they moved it to.
  25736. The scrollbar will adjust its own visibility according to whether its thumb size
  25737. allows it to actually be scrolled.
  25738. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  25739. instead of handling a scrollbar directly.
  25740. @see ScrollBarListener
  25741. */
  25742. class JUCE_API ScrollBar : public Component,
  25743. public AsyncUpdater,
  25744. private Timer
  25745. {
  25746. public:
  25747. /** Creates a Scrollbar.
  25748. @param isVertical whether it should be a vertical or horizontal bar
  25749. @param buttonsAreVisible whether to show the up/down or left/right buttons
  25750. */
  25751. ScrollBar (bool isVertical,
  25752. bool buttonsAreVisible = true);
  25753. /** Destructor. */
  25754. ~ScrollBar();
  25755. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  25756. bool isVertical() const throw() { return vertical; }
  25757. /** Changes the scrollbar's direction.
  25758. You'll also need to resize the bar appropriately - this just changes its internal
  25759. layout.
  25760. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  25761. */
  25762. void setOrientation (bool shouldBeVertical);
  25763. /** Shows or hides the scrollbar's buttons. */
  25764. void setButtonVisibility (bool buttonsAreVisible);
  25765. /** Tells the scrollbar whether to make itself invisible when not needed.
  25766. The default behaviour is for a scrollbar to become invisible when the thumb
  25767. fills the whole of its range (i.e. when it can't be moved). Setting this
  25768. value to false forces the bar to always be visible.
  25769. @see autoHides()
  25770. */
  25771. void setAutoHide (bool shouldHideWhenFullRange);
  25772. /** Returns true if this scrollbar is set to auto-hide when its thumb is as big
  25773. as its maximum range.
  25774. @see setAutoHide
  25775. */
  25776. bool autoHides() const throw();
  25777. /** Sets the minimum and maximum values that the bar will move between.
  25778. The bar's thumb will always be constrained so that the entire thumb lies
  25779. within this range.
  25780. @see setCurrentRange
  25781. */
  25782. void setRangeLimits (const Range<double>& newRangeLimit);
  25783. /** Sets the minimum and maximum values that the bar will move between.
  25784. The bar's thumb will always be constrained so that the entire thumb lies
  25785. within this range.
  25786. @see setCurrentRange
  25787. */
  25788. void setRangeLimits (double minimum, double maximum);
  25789. /** Returns the current limits on the thumb position.
  25790. @see setRangeLimits
  25791. */
  25792. const Range<double> getRangeLimit() const throw() { return totalRange; }
  25793. /** Returns the lower value that the thumb can be set to.
  25794. This is the value set by setRangeLimits().
  25795. */
  25796. double getMinimumRangeLimit() const throw() { return totalRange.getStart(); }
  25797. /** Returns the upper value that the thumb can be set to.
  25798. This is the value set by setRangeLimits().
  25799. */
  25800. double getMaximumRangeLimit() const throw() { return totalRange.getEnd(); }
  25801. /** Changes the position of the scrollbar's 'thumb'.
  25802. If this method call actually changes the scrollbar's position, it will trigger an
  25803. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  25804. are registered.
  25805. @see getCurrentRange. setCurrentRangeStart
  25806. */
  25807. void setCurrentRange (const Range<double>& newRange);
  25808. /** Changes the position of the scrollbar's 'thumb'.
  25809. This sets both the position and size of the thumb - to just set the position without
  25810. changing the size, you can use setCurrentRangeStart().
  25811. If this method call actually changes the scrollbar's position, it will trigger an
  25812. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  25813. are registered.
  25814. @param newStart the top (or left) of the thumb, in the range
  25815. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  25816. value is beyond these limits, it will be clipped.
  25817. @param newSize the size of the thumb, such that
  25818. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  25819. size is beyond these limits, it will be clipped.
  25820. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  25821. */
  25822. void setCurrentRange (double newStart, double newSize);
  25823. /** Moves the bar's thumb position.
  25824. This will move the thumb position without changing the thumb size. Note
  25825. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  25826. If this method call actually changes the scrollbar's position, it will trigger an
  25827. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  25828. are registered.
  25829. @see setCurrentRange
  25830. */
  25831. void setCurrentRangeStart (double newStart);
  25832. /** Returns the current thumb range.
  25833. @see getCurrentRange, setCurrentRange
  25834. */
  25835. const Range<double> getCurrentRange() const throw() { return visibleRange; }
  25836. /** Returns the position of the top of the thumb.
  25837. @see getCurrentRange, setCurrentRangeStart
  25838. */
  25839. double getCurrentRangeStart() const throw() { return visibleRange.getStart(); }
  25840. /** Returns the current size of the thumb.
  25841. @see getCurrentRange, setCurrentRange
  25842. */
  25843. double getCurrentRangeSize() const throw() { return visibleRange.getLength(); }
  25844. /** Sets the amount by which the up and down buttons will move the bar.
  25845. The value here is in terms of the total range, and is added or subtracted
  25846. from the thumb position when the user clicks an up/down (or left/right) button.
  25847. */
  25848. void setSingleStepSize (double newSingleStepSize);
  25849. /** Moves the scrollbar by a number of single-steps.
  25850. This will move the bar by a multiple of its single-step interval (as
  25851. specified using the setSingleStepSize() method).
  25852. A positive value here will move the bar down or to the right, a negative
  25853. value moves it up or to the left.
  25854. */
  25855. void moveScrollbarInSteps (int howManySteps);
  25856. /** Moves the scroll bar up or down in pages.
  25857. This will move the bar by a multiple of its current thumb size, effectively
  25858. doing a page-up or down.
  25859. A positive value here will move the bar down or to the right, a negative
  25860. value moves it up or to the left.
  25861. */
  25862. void moveScrollbarInPages (int howManyPages);
  25863. /** Scrolls to the top (or left).
  25864. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  25865. */
  25866. void scrollToTop();
  25867. /** Scrolls to the bottom (or right).
  25868. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  25869. */
  25870. void scrollToBottom();
  25871. /** Changes the delay before the up and down buttons autorepeat when they are held
  25872. down.
  25873. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  25874. @see Button::setRepeatSpeed
  25875. */
  25876. void setButtonRepeatSpeed (int initialDelayInMillisecs,
  25877. int repeatDelayInMillisecs,
  25878. int minimumDelayInMillisecs = -1);
  25879. /** A set of colour IDs to use to change the colour of various aspects of the component.
  25880. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25881. methods.
  25882. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25883. */
  25884. enum ColourIds
  25885. {
  25886. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  25887. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  25888. 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. */
  25889. };
  25890. /** Registers a listener that will be called when the scrollbar is moved. */
  25891. void addListener (ScrollBarListener* listener);
  25892. /** Deregisters a previously-registered listener. */
  25893. void removeListener (ScrollBarListener* listener);
  25894. /** @internal */
  25895. bool keyPressed (const KeyPress& key);
  25896. /** @internal */
  25897. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  25898. /** @internal */
  25899. void lookAndFeelChanged();
  25900. /** @internal */
  25901. void handleAsyncUpdate();
  25902. /** @internal */
  25903. void mouseDown (const MouseEvent& e);
  25904. /** @internal */
  25905. void mouseDrag (const MouseEvent& e);
  25906. /** @internal */
  25907. void mouseUp (const MouseEvent& e);
  25908. /** @internal */
  25909. void paint (Graphics& g);
  25910. /** @internal */
  25911. void resized();
  25912. juce_UseDebuggingNewOperator
  25913. private:
  25914. Range <double> totalRange, visibleRange;
  25915. double singleStepSize, dragStartRange;
  25916. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  25917. int dragStartMousePos, lastMousePos;
  25918. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  25919. bool vertical, isDraggingThumb, autohides;
  25920. class ScrollbarButton;
  25921. ScrollbarButton* upButton;
  25922. ScrollbarButton* downButton;
  25923. ListenerList <ScrollBarListener> listeners;
  25924. void updateThumbPosition();
  25925. void timerCallback();
  25926. ScrollBar (const ScrollBar&);
  25927. ScrollBar& operator= (const ScrollBar&);
  25928. };
  25929. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  25930. /*** End of inlined file: juce_ScrollBar.h ***/
  25931. /**
  25932. A Viewport is used to contain a larger child component, and allows the child
  25933. to be automatically scrolled around.
  25934. To use a Viewport, just create one and set the component that goes inside it
  25935. using the setViewedComponent() method. When the child component changes size,
  25936. the Viewport will adjust its scrollbars accordingly.
  25937. A subclass of the viewport can be created which will receive calls to its
  25938. visibleAreaChanged() method when the subcomponent changes position or size.
  25939. */
  25940. class JUCE_API Viewport : public Component,
  25941. private ComponentListener,
  25942. private ScrollBarListener
  25943. {
  25944. public:
  25945. /** Creates a Viewport.
  25946. The viewport is initially empty - use the setViewedComponent() method to
  25947. add a child component for it to manage.
  25948. */
  25949. explicit Viewport (const String& componentName = String::empty);
  25950. /** Destructor. */
  25951. ~Viewport();
  25952. /** Sets the component that this viewport will contain and scroll around.
  25953. This will add the given component to this Viewport and position it at
  25954. (0, 0).
  25955. (Don't add or remove any child components directly using the normal
  25956. Component::addChildComponent() methods).
  25957. @param newViewedComponent the component to add to this viewport (this pointer
  25958. may be null). The component passed in will be deleted
  25959. by the Viewport when it's no longer needed
  25960. @see getViewedComponent
  25961. */
  25962. void setViewedComponent (Component* newViewedComponent);
  25963. /** Returns the component that's currently being used inside the Viewport.
  25964. @see setViewedComponent
  25965. */
  25966. Component* getViewedComponent() const throw() { return contentComp; }
  25967. /** Changes the position of the viewed component.
  25968. The inner component will be moved so that the pixel at the top left of
  25969. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  25970. within the inner component.
  25971. This will update the scrollbars and might cause a call to visibleAreaChanged().
  25972. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  25973. */
  25974. void setViewPosition (int xPixelsOffset, int yPixelsOffset);
  25975. /** Changes the view position as a proportion of the distance it can move.
  25976. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  25977. visible area in the top-left, and (1, 1) would put it as far down and
  25978. to the right as it's possible to go whilst keeping the child component
  25979. on-screen.
  25980. */
  25981. void setViewPositionProportionately (double proportionX, double proportionY);
  25982. /** If the specified position is at the edges of the viewport, this method scrolls
  25983. the viewport to bring that position nearer to the centre.
  25984. Call this if you're dragging an object inside a viewport and want to make it scroll
  25985. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  25986. useful when auto-scrolling.
  25987. @param mouseX the x position, relative to the Viewport's top-left
  25988. @param mouseY the y position, relative to the Viewport's top-left
  25989. @param distanceFromEdge specifies how close to an edge the position needs to be
  25990. before the viewport should scroll in that direction
  25991. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  25992. to scroll by.
  25993. @returns true if the viewport was scrolled
  25994. */
  25995. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  25996. /** Returns the position within the child component of the top-left of its visible area.
  25997. */
  25998. const Point<int> getViewPosition() const throw() { return lastVisibleArea.getPosition(); }
  25999. /** Returns the position within the child component of the top-left of its visible area.
  26000. @see getViewWidth, setViewPosition
  26001. */
  26002. int getViewPositionX() const throw() { return lastVisibleArea.getX(); }
  26003. /** Returns the position within the child component of the top-left of its visible area.
  26004. @see getViewHeight, setViewPosition
  26005. */
  26006. int getViewPositionY() const throw() { return lastVisibleArea.getY(); }
  26007. /** Returns the width of the visible area of the child component.
  26008. This may be less than the width of this Viewport if there's a vertical scrollbar
  26009. or if the child component is itself smaller.
  26010. */
  26011. int getViewWidth() const throw() { return lastVisibleArea.getWidth(); }
  26012. /** Returns the height of the visible area of the child component.
  26013. This may be less than the height of this Viewport if there's a horizontal scrollbar
  26014. or if the child component is itself smaller.
  26015. */
  26016. int getViewHeight() const throw() { return lastVisibleArea.getHeight(); }
  26017. /** Returns the width available within this component for the contents.
  26018. This will be the width of the viewport component minus the width of a
  26019. vertical scrollbar (if visible).
  26020. */
  26021. int getMaximumVisibleWidth() const;
  26022. /** Returns the height available within this component for the contents.
  26023. This will be the height of the viewport component minus the space taken up
  26024. by a horizontal scrollbar (if visible).
  26025. */
  26026. int getMaximumVisibleHeight() const;
  26027. /** Callback method that is called when the visible area changes.
  26028. This will be called when the visible area is moved either be scrolling or
  26029. by calls to setViewPosition(), etc.
  26030. */
  26031. virtual void visibleAreaChanged (int visibleX, int visibleY,
  26032. int visibleW, int visibleH);
  26033. /** Turns scrollbars on or off.
  26034. If set to false, the scrollbars won't ever appear. When true (the default)
  26035. they will appear only when needed.
  26036. */
  26037. void setScrollBarsShown (bool showVerticalScrollbarIfNeeded,
  26038. bool showHorizontalScrollbarIfNeeded);
  26039. /** True if the vertical scrollbar is enabled.
  26040. @see setScrollBarsShown
  26041. */
  26042. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  26043. /** True if the horizontal scrollbar is enabled.
  26044. @see setScrollBarsShown
  26045. */
  26046. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  26047. /** Changes the width of the scrollbars.
  26048. If this isn't specified, the default width from the LookAndFeel class will be used.
  26049. @see LookAndFeel::getDefaultScrollbarWidth
  26050. */
  26051. void setScrollBarThickness (int thickness);
  26052. /** Returns the thickness of the scrollbars.
  26053. @see setScrollBarThickness
  26054. */
  26055. int getScrollBarThickness() const;
  26056. /** Changes the distance that a single-step click on a scrollbar button
  26057. will move the viewport.
  26058. */
  26059. void setSingleStepSizes (int stepX, int stepY);
  26060. /** Shows or hides the buttons on any scrollbars that are used.
  26061. @see ScrollBar::setButtonVisibility
  26062. */
  26063. void setScrollBarButtonVisibility (bool buttonsVisible);
  26064. /** Returns a pointer to the scrollbar component being used.
  26065. Handy if you need to customise the bar somehow.
  26066. */
  26067. ScrollBar* getVerticalScrollBar() throw() { return &verticalScrollBar; }
  26068. /** Returns a pointer to the scrollbar component being used.
  26069. Handy if you need to customise the bar somehow.
  26070. */
  26071. ScrollBar* getHorizontalScrollBar() throw() { return &horizontalScrollBar; }
  26072. juce_UseDebuggingNewOperator
  26073. /** @internal */
  26074. void resized();
  26075. /** @internal */
  26076. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  26077. /** @internal */
  26078. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26079. /** @internal */
  26080. bool keyPressed (const KeyPress& key);
  26081. /** @internal */
  26082. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  26083. /** @internal */
  26084. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26085. private:
  26086. Component::SafePointer<Component> contentComp;
  26087. Rectangle<int> lastVisibleArea;
  26088. int scrollBarThickness;
  26089. int singleStepX, singleStepY;
  26090. bool showHScrollbar, showVScrollbar;
  26091. Component contentHolder;
  26092. ScrollBar verticalScrollBar;
  26093. ScrollBar horizontalScrollBar;
  26094. void updateVisibleArea();
  26095. Viewport (const Viewport&);
  26096. Viewport& operator= (const Viewport&);
  26097. };
  26098. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  26099. /*** End of inlined file: juce_Viewport.h ***/
  26100. /*** Start of inlined file: juce_PopupMenu.h ***/
  26101. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  26102. #define __JUCE_POPUPMENU_JUCEHEADER__
  26103. class PopupMenuCustomComponent;
  26104. /** Creates and displays a popup-menu.
  26105. To show a popup-menu, you create one of these, add some items to it, then
  26106. call its show() method, which returns the id of the item the user selects.
  26107. E.g. @code
  26108. void MyWidget::mouseDown (const MouseEvent& e)
  26109. {
  26110. PopupMenu m;
  26111. m.addItem (1, "item 1");
  26112. m.addItem (2, "item 2");
  26113. const int result = m.show();
  26114. if (result == 0)
  26115. {
  26116. // user dismissed the menu without picking anything
  26117. }
  26118. else if (result == 1)
  26119. {
  26120. // user picked item 1
  26121. }
  26122. else if (result == 2)
  26123. {
  26124. // user picked item 2
  26125. }
  26126. }
  26127. @endcode
  26128. Submenus are easy too: @code
  26129. void MyWidget::mouseDown (const MouseEvent& e)
  26130. {
  26131. PopupMenu subMenu;
  26132. subMenu.addItem (1, "item 1");
  26133. subMenu.addItem (2, "item 2");
  26134. PopupMenu mainMenu;
  26135. mainMenu.addItem (3, "item 3");
  26136. mainMenu.addSubMenu ("other choices", subMenu);
  26137. const int result = m.show();
  26138. ...etc
  26139. }
  26140. @endcode
  26141. */
  26142. class JUCE_API PopupMenu
  26143. {
  26144. public:
  26145. /** Creates an empty popup menu. */
  26146. PopupMenu();
  26147. /** Creates a copy of another menu. */
  26148. PopupMenu (const PopupMenu& other);
  26149. /** Destructor. */
  26150. ~PopupMenu();
  26151. /** Copies this menu from another one. */
  26152. PopupMenu& operator= (const PopupMenu& other);
  26153. /** Resets the menu, removing all its items. */
  26154. void clear();
  26155. /** Appends a new text item for this menu to show.
  26156. @param itemResultId the number that will be returned from the show() method
  26157. if the user picks this item. The value should never be
  26158. zero, because that's used to indicate that the user didn't
  26159. select anything.
  26160. @param itemText the text to show.
  26161. @param isActive if false, the item will be shown 'greyed-out' and can't be
  26162. picked
  26163. @param isTicked if true, the item will be shown with a tick next to it
  26164. @param iconToUse if this is non-zero, it should be an image that will be
  26165. displayed to the left of the item. This method will take its
  26166. own copy of the image passed-in, so there's no need to keep
  26167. it hanging around.
  26168. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  26169. */
  26170. void addItem (int itemResultId,
  26171. const String& itemText,
  26172. bool isActive = true,
  26173. bool isTicked = false,
  26174. const Image& iconToUse = Image());
  26175. /** Adds an item that represents one of the commands in a command manager object.
  26176. @param commandManager the manager to use to trigger the command and get information
  26177. about it
  26178. @param commandID the ID of the command
  26179. @param displayName if this is non-empty, then this string will be used instead of
  26180. the command's registered name
  26181. */
  26182. void addCommandItem (ApplicationCommandManager* commandManager,
  26183. int commandID,
  26184. const String& displayName = String::empty);
  26185. /** Appends a text item with a special colour.
  26186. This is the same as addItem(), but specifies a colour to use for the
  26187. text, which will override the default colours that are used by the
  26188. current look-and-feel. See addItem() for a description of the parameters.
  26189. */
  26190. void addColouredItem (int itemResultId,
  26191. const String& itemText,
  26192. const Colour& itemTextColour,
  26193. bool isActive = true,
  26194. bool isTicked = false,
  26195. const Image& iconToUse = Image());
  26196. /** Appends a custom menu item.
  26197. This will add a user-defined component to use as a menu item. The component
  26198. passed in will be deleted by this menu when it's no longer needed.
  26199. @see PopupMenuCustomComponent
  26200. */
  26201. void addCustomItem (int itemResultId, PopupMenuCustomComponent* customComponent);
  26202. /** Appends a custom menu item that can't be used to trigger a result.
  26203. This will add a user-defined component to use as a menu item. Unlike the
  26204. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  26205. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  26206. delete the component when it's finished, so it's the caller's responsibility
  26207. to manage the component that is passed-in.
  26208. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  26209. detection of a mouse-click on your component, and use that to trigger the
  26210. menu ID specified in itemResultId. If this is false, the menu item can't
  26211. be triggered, so itemResultId is not used.
  26212. @see PopupMenuCustomComponent
  26213. */
  26214. void addCustomItem (int itemResultId,
  26215. Component* customComponent,
  26216. int idealWidth, int idealHeight,
  26217. bool triggerMenuItemAutomaticallyWhenClicked);
  26218. /** Appends a sub-menu.
  26219. If the menu that's passed in is empty, it will appear as an inactive item.
  26220. */
  26221. void addSubMenu (const String& subMenuName,
  26222. const PopupMenu& subMenu,
  26223. bool isActive = true,
  26224. const Image& iconToUse = Image(),
  26225. bool isTicked = false);
  26226. /** Appends a separator to the menu, to help break it up into sections.
  26227. The menu class is smart enough not to display separators at the top or bottom
  26228. of the menu, and it will replace mutliple adjacent separators with a single
  26229. one, so your code can be quite free and easy about adding these, and it'll
  26230. always look ok.
  26231. */
  26232. void addSeparator();
  26233. /** Adds a non-clickable text item to the menu.
  26234. This is a bold-font items which can be used as a header to separate the items
  26235. into named groups.
  26236. */
  26237. void addSectionHeader (const String& title);
  26238. /** Returns the number of items that the menu currently contains.
  26239. (This doesn't count separators).
  26240. */
  26241. int getNumItems() const throw();
  26242. /** Returns true if the menu contains a command item that triggers the given command. */
  26243. bool containsCommandItem (int commandID) const;
  26244. /** Returns true if the menu contains any items that can be used. */
  26245. bool containsAnyActiveItems() const throw();
  26246. /** Displays the menu and waits for the user to pick something.
  26247. This will display the menu modally, and return the ID of the item that the
  26248. user picks. If they click somewhere off the menu to get rid of it without
  26249. choosing anything, this will return 0.
  26250. The current location of the mouse will be used as the position to show the
  26251. menu - to explicitly set the menu's position, use showAt() instead. Depending
  26252. on where this point is on the screen, the menu will appear above, below or
  26253. to the side of the point.
  26254. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  26255. then when the menu first appears, it will make sure
  26256. that this item is visible. So if the menu has too many
  26257. items to fit on the screen, it will be scrolled to a
  26258. position where this item is visible.
  26259. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  26260. than this if some items are too long to fit.
  26261. @param maximumNumColumns if there are too many items to fit on-screen in a single
  26262. vertical column, the menu may be laid out as a series of
  26263. columns - this is the maximum number allowed. To use the
  26264. default value for this (probably about 7), you can pass
  26265. in zero.
  26266. @param standardItemHeight if this is non-zero, it will be used as the standard
  26267. height for menu items (apart from custom items)
  26268. @see showAt
  26269. */
  26270. int show (int itemIdThatMustBeVisible = 0,
  26271. int minimumWidth = 0,
  26272. int maximumNumColumns = 0,
  26273. int standardItemHeight = 0);
  26274. /** Displays the menu at a specific location.
  26275. This is the same as show(), but uses a specific location (in global screen
  26276. co-ordinates) rather than the current mouse position.
  26277. Note that the co-ordinates don't specify the top-left of the menu - they
  26278. indicate a point of interest, and the menu will position itself nearby to
  26279. this point, trying to keep it fully on-screen.
  26280. @see show()
  26281. */
  26282. int showAt (int screenX,
  26283. int screenY,
  26284. int itemIdThatMustBeVisible = 0,
  26285. int minimumWidth = 0,
  26286. int maximumNumColumns = 0,
  26287. int standardItemHeight = 0);
  26288. /** Displays the menu as if it's attached to a component such as a button.
  26289. This is similar to showAt(), but will position it next to the given component, e.g.
  26290. so that the menu's edge is aligned with that of the component. This is intended for
  26291. things like buttons that trigger a pop-up menu.
  26292. */
  26293. int showAt (Component* componentToAttachTo,
  26294. int itemIdThatMustBeVisible = 0,
  26295. int minimumWidth = 0,
  26296. int maximumNumColumns = 0,
  26297. int standardItemHeight = 0);
  26298. /** Closes any menus that are currently open.
  26299. This might be useful if you have a situation where your window is being closed
  26300. by some means other than a user action, and you'd like to make sure that menus
  26301. aren't left hanging around.
  26302. */
  26303. static void JUCE_CALLTYPE dismissAllActiveMenus();
  26304. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  26305. This can be called before show() if you need a customised menu. Be careful
  26306. not to delete the LookAndFeel object before the menu has been deleted.
  26307. */
  26308. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  26309. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  26310. These constants can be used either via the LookAndFeel::setColour()
  26311. method for the look and feel that is set for this menu with setLookAndFeel()
  26312. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  26313. */
  26314. enum ColourIds
  26315. {
  26316. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  26317. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  26318. colour is specified when the item is added). */
  26319. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  26320. addSectionHeader() method). */
  26321. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  26322. highlighted menu item. */
  26323. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  26324. highlighted item. */
  26325. };
  26326. /**
  26327. Allows you to iterate through the items in a pop-up menu, and examine
  26328. their properties.
  26329. To use this, just create one and repeatedly call its next() method. When this
  26330. returns true, all the member variables of the iterator are filled-out with
  26331. information describing the menu item. When it returns false, the end of the
  26332. list has been reached.
  26333. */
  26334. class JUCE_API MenuItemIterator
  26335. {
  26336. public:
  26337. /** Creates an iterator that will scan through the items in the specified
  26338. menu.
  26339. Be careful not to add any items to a menu while it is being iterated,
  26340. or things could get out of step.
  26341. */
  26342. MenuItemIterator (const PopupMenu& menu);
  26343. /** Destructor. */
  26344. ~MenuItemIterator();
  26345. /** Returns true if there is another item, and sets up all this object's
  26346. member variables to reflect that item's properties.
  26347. */
  26348. bool next();
  26349. String itemName;
  26350. const PopupMenu* subMenu;
  26351. int itemId;
  26352. bool isSeparator;
  26353. bool isTicked;
  26354. bool isEnabled;
  26355. bool isCustomComponent;
  26356. bool isSectionHeader;
  26357. const Colour* customColour;
  26358. Image customImage;
  26359. ApplicationCommandManager* commandManager;
  26360. juce_UseDebuggingNewOperator
  26361. private:
  26362. const PopupMenu& menu;
  26363. int index;
  26364. MenuItemIterator (const MenuItemIterator&);
  26365. MenuItemIterator& operator= (const MenuItemIterator&);
  26366. };
  26367. juce_UseDebuggingNewOperator
  26368. private:
  26369. class Item;
  26370. class ItemComponent;
  26371. class Window;
  26372. friend class MenuItemIterator;
  26373. friend class ItemComponent;
  26374. friend class Window;
  26375. friend class PopupMenuCustomComponent;
  26376. friend class OwnedArray <Item>;
  26377. friend class ScopedPointer <Window>;
  26378. OwnedArray <Item> items;
  26379. LookAndFeel* lookAndFeel;
  26380. bool separatorPending;
  26381. void addSeparatorIfPending();
  26382. int showMenu (int x, int y, int w, int h,
  26383. int itemIdThatMustBeVisible,
  26384. int minimumWidth,
  26385. int maximumNumColumns,
  26386. int standardItemHeight,
  26387. bool alignToRectangle,
  26388. Component* componentAttachedTo);
  26389. friend class MenuBarComponent;
  26390. Component* createMenuComponent (int x, int y, int w, int h,
  26391. int itemIdThatMustBeVisible,
  26392. int minimumWidth,
  26393. int maximumNumColumns,
  26394. int standardItemHeight,
  26395. bool alignToRectangle,
  26396. Component* menuBarComponent,
  26397. ApplicationCommandManager** managerOfChosenCommand,
  26398. Component* componentAttachedTo);
  26399. };
  26400. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  26401. /*** End of inlined file: juce_PopupMenu.h ***/
  26402. /*** Start of inlined file: juce_TextInputTarget.h ***/
  26403. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  26404. #define __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  26405. /** An abstract base class that is implemented by components that wish to be used
  26406. as text editors.
  26407. This class allows different types of text editor component to provide a uniform
  26408. interface, which can be used by things like OS-specific input methods, on-screen
  26409. keyboards, etc.
  26410. */
  26411. class JUCE_API TextInputTarget
  26412. {
  26413. public:
  26414. /** */
  26415. TextInputTarget() {}
  26416. /** Destructor. */
  26417. virtual ~TextInputTarget() {}
  26418. /** Returns true if this input target is currently accepting input.
  26419. For example, a text editor might return false if it's in read-only mode.
  26420. */
  26421. virtual bool isTextInputActive() const = 0;
  26422. /** Returns the extents of the selected text region, or an empty range if
  26423. nothing is selected,
  26424. */
  26425. virtual const Range<int> getHighlightedRegion() const = 0;
  26426. /** Sets the currently-selected text region.
  26427. */
  26428. virtual void setHighlightedRegion (const Range<int>& newRange) = 0;
  26429. /** Returns a specified sub-section of the text.
  26430. */
  26431. virtual const String getTextInRange (const Range<int>& range) const = 0;
  26432. /** Inserts some text, overwriting the selected text region, if there is one. */
  26433. virtual void insertTextAtCaret (const String& textToInsert) = 0;
  26434. };
  26435. #endif // __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  26436. /*** End of inlined file: juce_TextInputTarget.h ***/
  26437. class TextEditor;
  26438. /**
  26439. Receives callbacks from a TextEditor component when it changes.
  26440. @see TextEditor::addListener
  26441. */
  26442. class JUCE_API TextEditorListener
  26443. {
  26444. public:
  26445. /** Destructor. */
  26446. virtual ~TextEditorListener() {}
  26447. /** Called when the user changes the text in some way. */
  26448. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  26449. /** Called when the user presses the return key. */
  26450. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  26451. /** Called when the user presses the escape key. */
  26452. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  26453. /** Called when the text editor loses focus. */
  26454. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  26455. };
  26456. /**
  26457. A component containing text that can be edited.
  26458. A TextEditor can either be in single- or multi-line mode, and supports mixed
  26459. fonts and colours.
  26460. @see TextEditorListener, Label
  26461. */
  26462. class JUCE_API TextEditor : public Component,
  26463. public TextInputTarget,
  26464. public SettableTooltipClient
  26465. {
  26466. public:
  26467. /** Creates a new, empty text editor.
  26468. @param componentName the name to pass to the component for it to use as its name
  26469. @param passwordCharacter if this is not zero, this character will be used as a replacement
  26470. for all characters that are drawn on screen - e.g. to create
  26471. a password-style textbox containing circular blobs instead of text,
  26472. you could set this value to 0x25cf, which is the unicode character
  26473. for a black splodge (not all fonts include this, though), or 0x2022,
  26474. which is a bullet (probably the best choice for linux).
  26475. */
  26476. explicit TextEditor (const String& componentName = String::empty,
  26477. juce_wchar passwordCharacter = 0);
  26478. /** Destructor. */
  26479. virtual ~TextEditor();
  26480. /** Puts the editor into either multi- or single-line mode.
  26481. By default, the editor will be in single-line mode, so use this if you need a multi-line
  26482. editor.
  26483. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  26484. on if you want a multi-line editor with line-breaks.
  26485. @see isMultiLine, setReturnKeyStartsNewLine
  26486. */
  26487. void setMultiLine (bool shouldBeMultiLine,
  26488. bool shouldWordWrap = true);
  26489. /** Returns true if the editor is in multi-line mode.
  26490. */
  26491. bool isMultiLine() const;
  26492. /** Changes the behaviour of the return key.
  26493. If set to true, the return key will insert a new-line into the text; if false
  26494. it will trigger a call to the TextEditorListener::textEditorReturnKeyPressed()
  26495. method. By default this is set to false, and when true it will only insert
  26496. new-lines when in multi-line mode (see setMultiLine()).
  26497. */
  26498. void setReturnKeyStartsNewLine (bool shouldStartNewLine);
  26499. /** Returns the value set by setReturnKeyStartsNewLine().
  26500. See setReturnKeyStartsNewLine() for more info.
  26501. */
  26502. bool getReturnKeyStartsNewLine() const { return returnKeyStartsNewLine; }
  26503. /** Indicates whether the tab key should be accepted and used to input a tab character,
  26504. or whether it gets ignored.
  26505. By default the tab key is ignored, so that it can be used to switch keyboard focus
  26506. between components.
  26507. */
  26508. void setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed);
  26509. /** Returns true if the tab key is being used for input.
  26510. @see setTabKeyUsedAsCharacter
  26511. */
  26512. bool isTabKeyUsedAsCharacter() const { return tabKeyUsed; }
  26513. /** Changes the editor to read-only mode.
  26514. By default, the text editor is not read-only. If you're making it read-only, you
  26515. might also want to call setCaretVisible (false) to get rid of the caret.
  26516. The text can still be highlighted and copied when in read-only mode.
  26517. @see isReadOnly, setCaretVisible
  26518. */
  26519. void setReadOnly (bool shouldBeReadOnly);
  26520. /** Returns true if the editor is in read-only mode.
  26521. */
  26522. bool isReadOnly() const;
  26523. /** Makes the caret visible or invisible.
  26524. By default the caret is visible.
  26525. @see setCaretColour, setCaretPosition
  26526. */
  26527. void setCaretVisible (bool shouldBeVisible);
  26528. /** Returns true if the caret is enabled.
  26529. @see setCaretVisible
  26530. */
  26531. bool isCaretVisible() const { return caretVisible; }
  26532. /** Enables/disables a vertical scrollbar.
  26533. (This only applies when in multi-line mode). When the text gets too long to fit
  26534. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  26535. this is enabled, the scrollbar will be hidden unless it's needed.
  26536. By default the scrollbar is enabled.
  26537. */
  26538. void setScrollbarsShown (bool shouldBeEnabled);
  26539. /** Returns true if scrollbars are enabled.
  26540. @see setScrollbarsShown
  26541. */
  26542. bool areScrollbarsShown() const { return scrollbarVisible; }
  26543. /** Changes the password character used to disguise the text.
  26544. @param passwordCharacter if this is not zero, this character will be used as a replacement
  26545. for all characters that are drawn on screen - e.g. to create
  26546. a password-style textbox containing circular blobs instead of text,
  26547. you could set this value to 0x25cf, which is the unicode character
  26548. for a black splodge (not all fonts include this, though), or 0x2022,
  26549. which is a bullet (probably the best choice for linux).
  26550. */
  26551. void setPasswordCharacter (juce_wchar passwordCharacter);
  26552. /** Returns the current password character.
  26553. @see setPasswordCharacter
  26554. */
  26555. juce_wchar getPasswordCharacter() const { return passwordCharacter; }
  26556. /** Allows a right-click menu to appear for the editor.
  26557. (This defaults to being enabled).
  26558. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  26559. of options such as cut/copy/paste, undo/redo, etc.
  26560. */
  26561. void setPopupMenuEnabled (bool menuEnabled);
  26562. /** Returns true if the right-click menu is enabled.
  26563. @see setPopupMenuEnabled
  26564. */
  26565. bool isPopupMenuEnabled() const { return popupMenuEnabled; }
  26566. /** Returns true if a popup-menu is currently being displayed.
  26567. */
  26568. bool isPopupMenuCurrentlyActive() const { return menuActive; }
  26569. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  26570. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26571. methods.
  26572. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26573. */
  26574. enum ColourIds
  26575. {
  26576. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  26577. transparent if necessary. */
  26578. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  26579. that because the editor can contain multiple colours, calling this
  26580. method won't change the colour of existing text - to do that, call
  26581. applyFontToAllText() after calling this method.*/
  26582. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  26583. the text - this can be transparent if you don't want to show any
  26584. highlighting.*/
  26585. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  26586. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  26587. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  26588. the edge of the component. */
  26589. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  26590. the edge of the component when it has focus. */
  26591. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  26592. around the edge of the editor. */
  26593. };
  26594. /** Sets the font to use for newly added text.
  26595. This will change the font that will be used next time any text is added or entered
  26596. into the editor. It won't change the font of any existing text - to do that, use
  26597. applyFontToAllText() instead.
  26598. @see applyFontToAllText
  26599. */
  26600. void setFont (const Font& newFont);
  26601. /** Applies a font to all the text in the editor.
  26602. This will also set the current font to use for any new text that's added.
  26603. @see setFont
  26604. */
  26605. void applyFontToAllText (const Font& newFont);
  26606. /** Returns the font that's currently being used for new text.
  26607. @see setFont
  26608. */
  26609. const Font getFont() const;
  26610. /** If set to true, focusing on the editor will highlight all its text.
  26611. (Set to false by default).
  26612. This is useful for boxes where you expect the user to re-enter all the
  26613. text when they focus on the component, rather than editing what's already there.
  26614. */
  26615. void setSelectAllWhenFocused (bool b);
  26616. /** Sets limits on the characters that can be entered.
  26617. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  26618. limit is set
  26619. @param allowedCharacters if this is non-empty, then only characters that occur in
  26620. this string are allowed to be entered into the editor.
  26621. */
  26622. void setInputRestrictions (int maxTextLength,
  26623. const String& allowedCharacters = String::empty);
  26624. /** When the text editor is empty, it can be set to display a message.
  26625. This is handy for things like telling the user what to type in the box - the
  26626. string is only displayed, it's not taken to actually be the contents of
  26627. the editor.
  26628. */
  26629. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse);
  26630. /** Changes the size of the scrollbars that are used.
  26631. Handy if you need smaller scrollbars for a small text box.
  26632. */
  26633. void setScrollBarThickness (int newThicknessPixels);
  26634. /** Shows or hides the buttons on any scrollbars that are used.
  26635. @see ScrollBar::setButtonVisibility
  26636. */
  26637. void setScrollBarButtonVisibility (bool buttonsVisible);
  26638. /** Registers a listener to be told when things happen to the text.
  26639. @see removeListener
  26640. */
  26641. void addListener (TextEditorListener* newListener);
  26642. /** Deregisters a listener.
  26643. @see addListener
  26644. */
  26645. void removeListener (TextEditorListener* listenerToRemove);
  26646. /** Returns the entire contents of the editor. */
  26647. const String getText() const;
  26648. /** Returns a section of the contents of the editor. */
  26649. const String getTextInRange (const Range<int>& textRange) const;
  26650. /** Returns true if there are no characters in the editor.
  26651. This is more efficient than calling getText().isEmpty().
  26652. */
  26653. bool isEmpty() const;
  26654. /** Sets the entire content of the editor.
  26655. This will clear the editor and insert the given text (using the current text colour
  26656. and font). You can set the current text colour using
  26657. @code setColour (TextEditor::textColourId, ...);
  26658. @endcode
  26659. @param newText the text to add
  26660. @param sendTextChangeMessage if true, this will cause a change message to
  26661. be sent to all the listeners.
  26662. @see insertText
  26663. */
  26664. void setText (const String& newText,
  26665. bool sendTextChangeMessage = true);
  26666. /** Returns a Value object that can be used to get or set the text.
  26667. Bear in mind that this operate quite slowly if your text box contains large
  26668. amounts of text, as it needs to dynamically build the string that's involved. It's
  26669. best used for small text boxes.
  26670. */
  26671. Value& getTextValue();
  26672. /** Inserts some text at the current cursor position.
  26673. If a section of the text is highlighted, it will be replaced by
  26674. this string, otherwise it will be inserted.
  26675. To delete a section of text, you can use setHighlightedRegion() to
  26676. highlight it, and call insertTextAtCursor (String::empty).
  26677. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  26678. */
  26679. void insertTextAtCaret (const String& textToInsert);
  26680. /** Deletes all the text from the editor. */
  26681. void clear();
  26682. /** Deletes the currently selected region, and puts it on the clipboard.
  26683. @see copy, paste, SystemClipboard
  26684. */
  26685. void cut();
  26686. /** Copies any currently selected region to the clipboard.
  26687. @see cut, paste, SystemClipboard
  26688. */
  26689. void copy();
  26690. /** Pastes the contents of the clipboard into the editor at the cursor position.
  26691. @see cut, copy, SystemClipboard
  26692. */
  26693. void paste();
  26694. /** Moves the caret to be in front of a given character.
  26695. @see getCaretPosition
  26696. */
  26697. void setCaretPosition (int newIndex);
  26698. /** Returns the current index of the caret.
  26699. @see setCaretPosition
  26700. */
  26701. int getCaretPosition() const;
  26702. /** Attempts to scroll the text editor so that the caret ends up at
  26703. a specified position.
  26704. This won't affect the caret's position within the text, it tries to scroll
  26705. the entire editor vertically and horizontally so that the caret is sitting
  26706. at the given position (relative to the top-left of this component).
  26707. Depending on the amount of text available, it might not be possible to
  26708. scroll far enough for the caret to reach this exact position, but it
  26709. will go as far as it can in that direction.
  26710. */
  26711. void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);
  26712. /** Get the graphical position of the caret.
  26713. The rectangle returned is relative to the component's top-left corner.
  26714. @see scrollEditorToPositionCaret
  26715. */
  26716. const Rectangle<int> getCaretRectangle();
  26717. /** Selects a section of the text. */
  26718. void setHighlightedRegion (const Range<int>& newSelection);
  26719. /** Returns the range of characters that are selected.
  26720. If nothing is selected, this will return an empty range.
  26721. @see setHighlightedRegion
  26722. */
  26723. const Range<int> getHighlightedRegion() const { return selection; }
  26724. /** Returns the section of text that is currently selected. */
  26725. const String getHighlightedText() const;
  26726. /** Finds the index of the character at a given position.
  26727. The co-ordinates are relative to the component's top-left.
  26728. */
  26729. int getTextIndexAt (int x, int y);
  26730. /** Counts the number of characters in the text.
  26731. This is quicker than getting the text as a string if you just need to know
  26732. the length.
  26733. */
  26734. int getTotalNumChars() const;
  26735. /** Returns the total width of the text, as it is currently laid-out.
  26736. This may be larger than the size of the TextEditor, and can change when
  26737. the TextEditor is resized or the text changes.
  26738. */
  26739. int getTextWidth() const;
  26740. /** Returns the maximum height of the text, as it is currently laid-out.
  26741. This may be larger than the size of the TextEditor, and can change when
  26742. the TextEditor is resized or the text changes.
  26743. */
  26744. int getTextHeight() const;
  26745. /** Changes the size of the gap at the top and left-edge of the editor.
  26746. By default there's a gap of 4 pixels.
  26747. */
  26748. void setIndents (int newLeftIndent, int newTopIndent);
  26749. /** Changes the size of border left around the edge of the component.
  26750. @see getBorder
  26751. */
  26752. void setBorder (const BorderSize& border);
  26753. /** Returns the size of border around the edge of the component.
  26754. @see setBorder
  26755. */
  26756. const BorderSize getBorder() const;
  26757. /** Used to disable the auto-scrolling which keeps the cursor visible.
  26758. If true (the default), the editor will scroll when the cursor moves offscreen. If
  26759. set to false, it won't.
  26760. */
  26761. void setScrollToShowCursor (bool shouldScrollToShowCursor);
  26762. /** @internal */
  26763. void paint (Graphics& g);
  26764. /** @internal */
  26765. void paintOverChildren (Graphics& g);
  26766. /** @internal */
  26767. void mouseDown (const MouseEvent& e);
  26768. /** @internal */
  26769. void mouseUp (const MouseEvent& e);
  26770. /** @internal */
  26771. void mouseDrag (const MouseEvent& e);
  26772. /** @internal */
  26773. void mouseDoubleClick (const MouseEvent& e);
  26774. /** @internal */
  26775. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26776. /** @internal */
  26777. bool keyPressed (const KeyPress& key);
  26778. /** @internal */
  26779. bool keyStateChanged (bool isKeyDown);
  26780. /** @internal */
  26781. void focusGained (FocusChangeType cause);
  26782. /** @internal */
  26783. void focusLost (FocusChangeType cause);
  26784. /** @internal */
  26785. void resized();
  26786. /** @internal */
  26787. void enablementChanged();
  26788. /** @internal */
  26789. void colourChanged();
  26790. /** @internal */
  26791. bool isTextInputActive() const;
  26792. juce_UseDebuggingNewOperator
  26793. protected:
  26794. /** This adds the items to the popup menu.
  26795. By default it adds the cut/copy/paste items, but you can override this if
  26796. you need to replace these with your own items.
  26797. If you want to add your own items to the existing ones, you can override this,
  26798. call the base class's addPopupMenuItems() method, then append your own items.
  26799. When the menu has been shown, performPopupMenuAction() will be called to
  26800. perform the item that the user has chosen.
  26801. The default menu items will be added using item IDs in the range
  26802. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  26803. menu IDs.
  26804. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  26805. a pointer to the info about it, or may be null if the menu is being triggered
  26806. by some other means.
  26807. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  26808. */
  26809. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  26810. const MouseEvent* mouseClickEvent);
  26811. /** This is called to perform one of the items that was shown on the popup menu.
  26812. If you've overridden addPopupMenuItems(), you should also override this
  26813. to perform the actions that you've added.
  26814. If you've overridden addPopupMenuItems() but have still left the default items
  26815. on the menu, remember to call the superclass's performPopupMenuAction()
  26816. so that it can perform the default actions if that's what the user clicked on.
  26817. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  26818. */
  26819. virtual void performPopupMenuAction (int menuItemID);
  26820. /** Scrolls the minimum distance needed to get the caret into view. */
  26821. void scrollToMakeSureCursorIsVisible();
  26822. /** @internal */
  26823. void moveCaret (int newCaretPos);
  26824. /** @internal */
  26825. void moveCursorTo (int newPosition, bool isSelecting);
  26826. /** Used internally to dispatch a text-change message. */
  26827. void textChanged();
  26828. /** Begins a new transaction in the UndoManager.
  26829. */
  26830. void newTransaction();
  26831. /** Used internally to trigger an undo or redo. */
  26832. void doUndoRedo (bool isRedo);
  26833. /** Can be overridden to intercept return key presses directly */
  26834. virtual void returnPressed();
  26835. /** Can be overridden to intercept escape key presses directly */
  26836. virtual void escapePressed();
  26837. /** @internal */
  26838. void handleCommandMessage (int commandId);
  26839. private:
  26840. class Iterator;
  26841. class UniformTextSection;
  26842. class TextHolderComponent;
  26843. class InsertAction;
  26844. class RemoveAction;
  26845. friend class InsertAction;
  26846. friend class RemoveAction;
  26847. ScopedPointer <Viewport> viewport;
  26848. TextHolderComponent* textHolder;
  26849. BorderSize borderSize;
  26850. bool readOnly : 1;
  26851. bool multiline : 1;
  26852. bool wordWrap : 1;
  26853. bool returnKeyStartsNewLine : 1;
  26854. bool caretVisible : 1;
  26855. bool popupMenuEnabled : 1;
  26856. bool selectAllTextWhenFocused : 1;
  26857. bool scrollbarVisible : 1;
  26858. bool wasFocused : 1;
  26859. bool caretFlashState : 1;
  26860. bool keepCursorOnScreen : 1;
  26861. bool tabKeyUsed : 1;
  26862. bool menuActive : 1;
  26863. bool valueTextNeedsUpdating : 1;
  26864. UndoManager undoManager;
  26865. float cursorX, cursorY, cursorHeight;
  26866. int maxTextLength;
  26867. Range<int> selection;
  26868. int leftIndent, topIndent;
  26869. unsigned int lastTransactionTime;
  26870. Font currentFont;
  26871. mutable int totalNumChars;
  26872. int caretPosition;
  26873. Array <UniformTextSection*> sections;
  26874. String textToShowWhenEmpty;
  26875. Colour colourForTextWhenEmpty;
  26876. juce_wchar passwordCharacter;
  26877. Value textValue;
  26878. enum
  26879. {
  26880. notDragging,
  26881. draggingSelectionStart,
  26882. draggingSelectionEnd
  26883. } dragType;
  26884. String allowedCharacters;
  26885. ListenerList <TextEditorListener> listeners;
  26886. void coalesceSimilarSections();
  26887. void splitSection (int sectionIndex, int charToSplitAt);
  26888. void clearInternal (UndoManager* um);
  26889. void insert (const String& text, int insertIndex, const Font& font,
  26890. const Colour& colour, UndoManager* um, int caretPositionToMoveTo);
  26891. void reinsert (int insertIndex, const Array <UniformTextSection*>& sections);
  26892. void remove (const Range<int>& range, UndoManager* um, int caretPositionToMoveTo);
  26893. void getCharPosition (int index, float& x, float& y, float& lineHeight) const;
  26894. void updateCaretPosition();
  26895. void textWasChangedByValue();
  26896. int indexAtPosition (float x, float y);
  26897. int findWordBreakAfter (int position) const;
  26898. int findWordBreakBefore (int position) const;
  26899. friend class TextHolderComponent;
  26900. friend class TextEditorViewport;
  26901. void drawContent (Graphics& g);
  26902. void updateTextHolderSize();
  26903. float getWordWrapWidth() const;
  26904. void timerCallbackInt();
  26905. void repaintCaret();
  26906. void repaintText (const Range<int>& range);
  26907. UndoManager* getUndoManager() throw();
  26908. TextEditor (const TextEditor&);
  26909. TextEditor& operator= (const TextEditor&);
  26910. };
  26911. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  26912. /*** End of inlined file: juce_TextEditor.h ***/
  26913. class Label;
  26914. /**
  26915. A class for receiving events from a Label.
  26916. You can register a LabelListener with a Label using the Label::addListener()
  26917. method, and it will be called when the text of the label changes, either because
  26918. of a call to Label::setText() or by the user editing the text (if the label is
  26919. editable).
  26920. @see Label::addListener, Label::removeListener
  26921. */
  26922. class JUCE_API LabelListener
  26923. {
  26924. public:
  26925. /** Destructor. */
  26926. virtual ~LabelListener() {}
  26927. /** Called when a Label's text has changed.
  26928. */
  26929. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  26930. };
  26931. /**
  26932. A component that displays a text string, and can optionally become a text
  26933. editor when clicked.
  26934. */
  26935. class JUCE_API Label : public Component,
  26936. public SettableTooltipClient,
  26937. protected TextEditorListener,
  26938. private ComponentListener,
  26939. private Value::Listener
  26940. {
  26941. public:
  26942. /** Creates a Label.
  26943. @param componentName the name to give the component
  26944. @param labelText the text to show in the label
  26945. */
  26946. Label (const String& componentName = String::empty,
  26947. const String& labelText = String::empty);
  26948. /** Destructor. */
  26949. ~Label();
  26950. /** Changes the label text.
  26951. If broadcastChangeMessage is true and the new text is different to the current
  26952. text, then the class will broadcast a change message to any LabelListeners that
  26953. are registered.
  26954. */
  26955. void setText (const String& newText,
  26956. bool broadcastChangeMessage);
  26957. /** Returns the label's current text.
  26958. @param returnActiveEditorContents if this is true and the label is currently
  26959. being edited, then this method will return the
  26960. text as it's being shown in the editor. If false,
  26961. then the value returned here won't be updated until
  26962. the user has finished typing and pressed the return
  26963. key.
  26964. */
  26965. const String getText (bool returnActiveEditorContents = false) const throw();
  26966. /** Returns the text content as a Value object.
  26967. You can call Value::referTo() on this object to make the label read and control
  26968. a Value object that you supply.
  26969. */
  26970. Value& getTextValue() { return textValue; }
  26971. /** Changes the font to use to draw the text.
  26972. @see getFont
  26973. */
  26974. void setFont (const Font& newFont) throw();
  26975. /** Returns the font currently being used.
  26976. @see setFont
  26977. */
  26978. const Font& getFont() const throw();
  26979. /** A set of colour IDs to use to change the colour of various aspects of the label.
  26980. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26981. methods.
  26982. Note that you can also use the constants from TextEditor::ColourIds to change the
  26983. colour of the text editor that is opened when a label is editable.
  26984. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26985. */
  26986. enum ColourIds
  26987. {
  26988. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  26989. textColourId = 0x1000281, /**< The colour for the text. */
  26990. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  26991. Leave this transparent to not have an outline. */
  26992. };
  26993. /** Sets the style of justification to be used for positioning the text.
  26994. (The default is Justification::centredLeft)
  26995. */
  26996. void setJustificationType (const Justification& justification) throw();
  26997. /** Returns the type of justification, as set in setJustificationType(). */
  26998. const Justification getJustificationType() const throw() { return justification; }
  26999. /** Changes the gap that is left between the edge of the component and the text.
  27000. By default there's a small gap left at the sides of the component to allow for
  27001. the drawing of the border, but you can change this if necessary.
  27002. */
  27003. void setBorderSize (int horizontalBorder, int verticalBorder);
  27004. /** Returns the size of the horizontal gap being left around the text.
  27005. */
  27006. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  27007. /** Returns the size of the vertical gap being left around the text.
  27008. */
  27009. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  27010. /** Makes this label "stick to" another component.
  27011. This will cause the label to follow another component around, staying
  27012. either to its left or above it.
  27013. @param owner the component to follow
  27014. @param onLeft if true, the label will stay on the left of its component; if
  27015. false, it will stay above it.
  27016. */
  27017. void attachToComponent (Component* owner, bool onLeft);
  27018. /** If this label has been attached to another component using attachToComponent, this
  27019. returns the other component.
  27020. Returns 0 if the label is not attached.
  27021. */
  27022. Component* getAttachedComponent() const;
  27023. /** If the label is attached to the left of another component, this returns true.
  27024. Returns false if the label is above the other component. This is only relevent if
  27025. attachToComponent() has been called.
  27026. */
  27027. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  27028. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  27029. using ellipsis.
  27030. @see Graphics::drawFittedText
  27031. */
  27032. void setMinimumHorizontalScale (float newScale);
  27033. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  27034. /** Registers a listener that will be called when the label's text changes. */
  27035. void addListener (LabelListener* listener) throw();
  27036. /** Deregisters a previously-registered listener. */
  27037. void removeListener (LabelListener* listener) throw();
  27038. /** Makes the label turn into a TextEditor when clicked.
  27039. By default this is turned off.
  27040. If turned on, then single- or double-clicking will turn the label into
  27041. an editor. If the user then changes the text, then the ChangeBroadcaster
  27042. base class will be used to send change messages to any listeners that
  27043. have registered.
  27044. If the user changes the text, the textWasEdited() method will be called
  27045. afterwards, and subclasses can override this if they need to do anything
  27046. special.
  27047. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  27048. @param editOnDoubleClick if true, a double-click is needed to start editing
  27049. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  27050. edited will discard any changes; if false, then this will
  27051. commit the changes.
  27052. @see showEditor, setEditorColours, TextEditor
  27053. */
  27054. void setEditable (bool editOnSingleClick,
  27055. bool editOnDoubleClick = false,
  27056. bool lossOfFocusDiscardsChanges = false) throw();
  27057. /** Returns true if this option was set using setEditable(). */
  27058. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  27059. /** Returns true if this option was set using setEditable(). */
  27060. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  27061. /** Returns true if this option has been set in a call to setEditable(). */
  27062. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  27063. /** Returns true if the user can edit this label's text. */
  27064. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  27065. /** Makes the editor appear as if the label had been clicked by the user.
  27066. @see textWasEdited, setEditable
  27067. */
  27068. void showEditor();
  27069. /** Hides the editor if it was being shown.
  27070. @param discardCurrentEditorContents if true, the label's text will be
  27071. reset to whatever it was before the editor
  27072. was shown; if false, the current contents of the
  27073. editor will be used to set the label's text
  27074. before it is hidden.
  27075. */
  27076. void hideEditor (bool discardCurrentEditorContents);
  27077. /** Returns true if the editor is currently focused and active. */
  27078. bool isBeingEdited() const throw();
  27079. juce_UseDebuggingNewOperator
  27080. protected:
  27081. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  27082. Subclasses can override this if they need to customise this component in some way.
  27083. */
  27084. virtual TextEditor* createEditorComponent();
  27085. /** Called after the user changes the text.
  27086. */
  27087. virtual void textWasEdited();
  27088. /** Called when the text has been altered.
  27089. */
  27090. virtual void textWasChanged();
  27091. /** Called when the text editor has just appeared, due to a user click or other
  27092. focus change.
  27093. */
  27094. virtual void editorShown (TextEditor* editorComponent);
  27095. /** Called when the text editor is going to be deleted, after editing has finished.
  27096. */
  27097. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  27098. /** @internal */
  27099. void paint (Graphics& g);
  27100. /** @internal */
  27101. void resized();
  27102. /** @internal */
  27103. void mouseUp (const MouseEvent& e);
  27104. /** @internal */
  27105. void mouseDoubleClick (const MouseEvent& e);
  27106. /** @internal */
  27107. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  27108. /** @internal */
  27109. void componentParentHierarchyChanged (Component& component);
  27110. /** @internal */
  27111. void componentVisibilityChanged (Component& component);
  27112. /** @internal */
  27113. void inputAttemptWhenModal();
  27114. /** @internal */
  27115. void focusGained (FocusChangeType);
  27116. /** @internal */
  27117. void enablementChanged();
  27118. /** @internal */
  27119. KeyboardFocusTraverser* createFocusTraverser();
  27120. /** @internal */
  27121. void textEditorTextChanged (TextEditor& editor);
  27122. /** @internal */
  27123. void textEditorReturnKeyPressed (TextEditor& editor);
  27124. /** @internal */
  27125. void textEditorEscapeKeyPressed (TextEditor& editor);
  27126. /** @internal */
  27127. void textEditorFocusLost (TextEditor& editor);
  27128. /** @internal */
  27129. void colourChanged();
  27130. /** @internal */
  27131. void valueChanged (Value&);
  27132. private:
  27133. Value textValue;
  27134. String lastTextValue;
  27135. Font font;
  27136. Justification justification;
  27137. ScopedPointer <TextEditor> editor;
  27138. ListenerList <LabelListener> listeners;
  27139. Component::SafePointer<Component> ownerComponent;
  27140. int horizontalBorderSize, verticalBorderSize;
  27141. float minimumHorizontalScale;
  27142. bool editSingleClick : 1;
  27143. bool editDoubleClick : 1;
  27144. bool lossOfFocusDiscardsChanges : 1;
  27145. bool leftOfOwnerComp : 1;
  27146. bool updateFromTextEditorContents();
  27147. void callChangeListeners();
  27148. Label (const Label&);
  27149. Label& operator= (const Label&);
  27150. };
  27151. #endif // __JUCE_LABEL_JUCEHEADER__
  27152. /*** End of inlined file: juce_Label.h ***/
  27153. class ComboBox;
  27154. /**
  27155. A class for receiving events from a ComboBox.
  27156. You can register a ComboBoxListener with a ComboBox using the ComboBox::addListener()
  27157. method, and it will be called when the selected item in the box changes.
  27158. @see ComboBox::addListener, ComboBox::removeListener
  27159. */
  27160. class JUCE_API ComboBoxListener
  27161. {
  27162. public:
  27163. /** Destructor. */
  27164. virtual ~ComboBoxListener() {}
  27165. /** Called when a ComboBox has its selected item changed.
  27166. */
  27167. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  27168. };
  27169. /**
  27170. A component that lets the user choose from a drop-down list of choices.
  27171. The combo-box has a list of text strings, each with an associated id number,
  27172. that will be shown in the drop-down list when the user clicks on the component.
  27173. The currently selected choice is displayed in the combo-box, and this can
  27174. either be read-only text, or editable.
  27175. To find out when the user selects a different item or edits the text, you
  27176. can register a ComboBoxListener to receive callbacks.
  27177. @see ComboBoxListener
  27178. */
  27179. class JUCE_API ComboBox : public Component,
  27180. public SettableTooltipClient,
  27181. private LabelListener,
  27182. private AsyncUpdater,
  27183. private Value::Listener
  27184. {
  27185. public:
  27186. /** Creates a combo-box.
  27187. On construction, the text field will be empty, so you should call the
  27188. setSelectedId() or setText() method to choose the initial value before
  27189. displaying it.
  27190. @param componentName the name to set for the component (see Component::setName())
  27191. */
  27192. explicit ComboBox (const String& componentName = String::empty);
  27193. /** Destructor. */
  27194. ~ComboBox();
  27195. /** Sets whether the test in the combo-box is editable.
  27196. The default state for a new ComboBox is non-editable, and can only be changed
  27197. by choosing from the drop-down list.
  27198. */
  27199. void setEditableText (bool isEditable);
  27200. /** Returns true if the text is directly editable.
  27201. @see setEditableText
  27202. */
  27203. bool isTextEditable() const throw();
  27204. /** Sets the style of justification to be used for positioning the text.
  27205. The default is Justification::centredLeft. The text is displayed using a
  27206. Label component inside the ComboBox.
  27207. */
  27208. void setJustificationType (const Justification& justification) throw();
  27209. /** Returns the current justification for the text box.
  27210. @see setJustificationType
  27211. */
  27212. const Justification getJustificationType() const throw();
  27213. /** Adds an item to be shown in the drop-down list.
  27214. @param newItemText the text of the item to show in the list
  27215. @param newItemId an associated ID number that can be set or retrieved - see
  27216. getSelectedId() and setSelectedId()
  27217. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  27218. */
  27219. void addItem (const String& newItemText,
  27220. int newItemId) throw();
  27221. /** Adds a separator line to the drop-down list.
  27222. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  27223. */
  27224. void addSeparator() throw();
  27225. /** Adds a heading to the drop-down list, so that you can group the items into
  27226. different sections.
  27227. The headings are indented slightly differently to set them apart from the
  27228. items on the list, and obviously can't be selected. You might want to add
  27229. separators between your sections too.
  27230. @see addItem, addSeparator
  27231. */
  27232. void addSectionHeading (const String& headingName) throw();
  27233. /** This allows items in the drop-down list to be selectively disabled.
  27234. When you add an item, it's enabled by default, but you can call this
  27235. method to change its status.
  27236. If you disable an item which is already selected, this won't change the
  27237. current selection - it just stops the user choosing that item from the list.
  27238. */
  27239. void setItemEnabled (int itemId,
  27240. bool shouldBeEnabled) throw();
  27241. /** Changes the text for an existing item.
  27242. */
  27243. void changeItemText (int itemId,
  27244. const String& newText) throw();
  27245. /** Removes all the items from the drop-down list.
  27246. If this call causes the content to be cleared, then a change-message
  27247. will be broadcast unless dontSendChangeMessage is true.
  27248. @see addItem, removeItem, getNumItems
  27249. */
  27250. void clear (bool dontSendChangeMessage = false);
  27251. /** Returns the number of items that have been added to the list.
  27252. Note that this doesn't include headers or separators.
  27253. */
  27254. int getNumItems() const throw();
  27255. /** Returns the text for one of the items in the list.
  27256. Note that this doesn't include headers or separators.
  27257. @param index the item's index from 0 to (getNumItems() - 1)
  27258. */
  27259. const String getItemText (int index) const throw();
  27260. /** Returns the ID for one of the items in the list.
  27261. Note that this doesn't include headers or separators.
  27262. @param index the item's index from 0 to (getNumItems() - 1)
  27263. */
  27264. int getItemId (int index) const throw();
  27265. /** Returns the index in the list of a particular item ID.
  27266. If no such ID is found, this will return -1.
  27267. */
  27268. int indexOfItemId (int itemId) const throw();
  27269. /** Returns the ID of the item that's currently shown in the box.
  27270. If no item is selected, or if the text is editable and the user
  27271. has entered something which isn't one of the items in the list, then
  27272. this will return 0.
  27273. @see setSelectedId, getSelectedItemIndex, getText
  27274. */
  27275. int getSelectedId() const throw();
  27276. /** Returns a Value object that can be used to get or set the selected item's ID.
  27277. You can call Value::referTo() on this object to make the combo box control
  27278. another Value object.
  27279. */
  27280. Value& getSelectedIdAsValue() throw() { return currentId; }
  27281. /** Sets one of the items to be the current selection.
  27282. This will set the ComboBox's text to that of the item that matches
  27283. this ID.
  27284. @param newItemId the new item to select
  27285. @param dontSendChangeMessage if set to true, this method won't trigger a
  27286. change notification
  27287. @see getSelectedId, setSelectedItemIndex, setText
  27288. */
  27289. void setSelectedId (int newItemId,
  27290. bool dontSendChangeMessage = false) throw();
  27291. /** Returns the index of the item that's currently shown in the box.
  27292. If no item is selected, or if the text is editable and the user
  27293. has entered something which isn't one of the items in the list, then
  27294. this will return -1.
  27295. @see setSelectedItemIndex, getSelectedId, getText
  27296. */
  27297. int getSelectedItemIndex() const throw();
  27298. /** Sets one of the items to be the current selection.
  27299. This will set the ComboBox's text to that of the item at the given
  27300. index in the list.
  27301. @param newItemIndex the new item to select
  27302. @param dontSendChangeMessage if set to true, this method won't trigger a
  27303. change notification
  27304. @see getSelectedItemIndex, setSelectedId, setText
  27305. */
  27306. void setSelectedItemIndex (int newItemIndex,
  27307. bool dontSendChangeMessage = false) throw();
  27308. /** Returns the text that is currently shown in the combo-box's text field.
  27309. If the ComboBox has editable text, then this text may have been edited
  27310. by the user; otherwise it will be one of the items from the list, or
  27311. possibly an empty string if nothing was selected.
  27312. @see setText, getSelectedId, getSelectedItemIndex
  27313. */
  27314. const String getText() const throw();
  27315. /** Sets the contents of the combo-box's text field.
  27316. The text passed-in will be set as the current text regardless of whether
  27317. it is one of the items in the list. If the current text isn't one of the
  27318. items, then getSelectedId() will return -1, otherwise it wil return
  27319. the approriate ID.
  27320. @param newText the text to select
  27321. @param dontSendChangeMessage if set to true, this method won't trigger a
  27322. change notification
  27323. @see getText
  27324. */
  27325. void setText (const String& newText,
  27326. bool dontSendChangeMessage = false) throw();
  27327. /** Programmatically opens the text editor to allow the user to edit the current item.
  27328. This is the same effect as when the box is clicked-on.
  27329. @see Label::showEditor();
  27330. */
  27331. void showEditor();
  27332. /** Registers a listener that will be called when the box's content changes. */
  27333. void addListener (ComboBoxListener* listener) throw();
  27334. /** Deregisters a previously-registered listener. */
  27335. void removeListener (ComboBoxListener* listener) throw();
  27336. /** Sets a message to display when there is no item currently selected.
  27337. @see getTextWhenNothingSelected
  27338. */
  27339. void setTextWhenNothingSelected (const String& newMessage) throw();
  27340. /** Returns the text that is shown when no item is selected.
  27341. @see setTextWhenNothingSelected
  27342. */
  27343. const String getTextWhenNothingSelected() const throw();
  27344. /** Sets the message to show when there are no items in the list, and the user clicks
  27345. on the drop-down box.
  27346. By default it just says "no choices", but this lets you change it to something more
  27347. meaningful.
  27348. */
  27349. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  27350. /** Returns the text shown when no items have been added to the list.
  27351. @see setTextWhenNoChoicesAvailable
  27352. */
  27353. const String getTextWhenNoChoicesAvailable() const throw();
  27354. /** Gives the ComboBox a tooltip. */
  27355. void setTooltip (const String& newTooltip);
  27356. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  27357. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  27358. methods.
  27359. To change the colours of the menu that pops up
  27360. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  27361. */
  27362. enum ColourIds
  27363. {
  27364. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  27365. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  27366. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  27367. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  27368. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  27369. };
  27370. /** @internal */
  27371. void labelTextChanged (Label*);
  27372. /** @internal */
  27373. void enablementChanged();
  27374. /** @internal */
  27375. void colourChanged();
  27376. /** @internal */
  27377. void focusGained (Component::FocusChangeType cause);
  27378. /** @internal */
  27379. void focusLost (Component::FocusChangeType cause);
  27380. /** @internal */
  27381. void handleAsyncUpdate();
  27382. /** @internal */
  27383. const String getTooltip() { return label->getTooltip(); }
  27384. /** @internal */
  27385. void mouseDown (const MouseEvent&);
  27386. /** @internal */
  27387. void mouseDrag (const MouseEvent&);
  27388. /** @internal */
  27389. void mouseUp (const MouseEvent&);
  27390. /** @internal */
  27391. void lookAndFeelChanged();
  27392. /** @internal */
  27393. void paint (Graphics&);
  27394. /** @internal */
  27395. void resized();
  27396. /** @internal */
  27397. bool keyStateChanged (bool isKeyDown);
  27398. /** @internal */
  27399. bool keyPressed (const KeyPress&);
  27400. /** @internal */
  27401. void valueChanged (Value&);
  27402. juce_UseDebuggingNewOperator
  27403. private:
  27404. struct ItemInfo
  27405. {
  27406. String name;
  27407. int itemId;
  27408. bool isEnabled : 1, isHeading : 1;
  27409. bool isSeparator() const throw();
  27410. bool isRealItem() const throw();
  27411. };
  27412. OwnedArray <ItemInfo> items;
  27413. Value currentId;
  27414. int lastCurrentId;
  27415. bool isButtonDown, separatorPending, menuActive, textIsCustom;
  27416. ListenerList <ComboBoxListener> listeners;
  27417. ScopedPointer<Label> label;
  27418. String textWhenNothingSelected, noChoicesMessage;
  27419. void showPopup();
  27420. ItemInfo* getItemForId (int itemId) const throw();
  27421. ItemInfo* getItemForIndex (int index) const throw();
  27422. ComboBox (const ComboBox&);
  27423. ComboBox& operator= (const ComboBox&);
  27424. };
  27425. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  27426. /*** End of inlined file: juce_ComboBox.h ***/
  27427. /**
  27428. Manages the state of some audio and midi i/o devices.
  27429. This class keeps tracks of a currently-selected audio device, through
  27430. with which it continuously streams data from an audio callback, as well as
  27431. one or more midi inputs.
  27432. The idea is that your application will create one global instance of this object,
  27433. and let it take care of creating and deleting specific types of audio devices
  27434. internally. So when the device is changed, your callbacks will just keep running
  27435. without having to worry about this.
  27436. The manager can save and reload all of its device settings as XML, which
  27437. makes it very easy for you to save and reload the audio setup of your
  27438. application.
  27439. And to make it easy to let the user change its settings, there's a component
  27440. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  27441. device selection/sample-rate/latency controls.
  27442. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  27443. call addAudioCallback() to register your audio callback with it, and use that to process
  27444. your audio data.
  27445. The manager also acts as a handy hub for incoming midi messages, allowing a
  27446. listener to register for messages from either a specific midi device, or from whatever
  27447. the current default midi input device is. The listener then doesn't have to worry about
  27448. re-registering with different midi devices if they are changed or deleted.
  27449. And yet another neat trick is that amount of CPU time being used is measured and
  27450. available with the getCpuUsage() method.
  27451. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  27452. listeners whenever one of its settings is changed.
  27453. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  27454. */
  27455. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  27456. {
  27457. public:
  27458. /** Creates a default AudioDeviceManager.
  27459. Initially no audio device will be selected. You should call the initialise() method
  27460. and register an audio callback with setAudioCallback() before it'll be able to
  27461. actually make any noise.
  27462. */
  27463. AudioDeviceManager();
  27464. /** Destructor. */
  27465. ~AudioDeviceManager();
  27466. /**
  27467. This structure holds a set of properties describing the current audio setup.
  27468. @see AudioDeviceManager::setAudioDeviceSetup()
  27469. */
  27470. struct JUCE_API AudioDeviceSetup
  27471. {
  27472. AudioDeviceSetup();
  27473. bool operator== (const AudioDeviceSetup& other) const;
  27474. /** The name of the audio device used for output.
  27475. The name has to be one of the ones listed by the AudioDeviceManager's currently
  27476. selected device type.
  27477. This may be the same as the input device.
  27478. */
  27479. String outputDeviceName;
  27480. /** The name of the audio device used for input.
  27481. This may be the same as the output device.
  27482. */
  27483. String inputDeviceName;
  27484. /** The current sample rate.
  27485. This rate is used for both the input and output devices.
  27486. */
  27487. double sampleRate;
  27488. /** The buffer size, in samples.
  27489. This buffer size is used for both the input and output devices.
  27490. */
  27491. int bufferSize;
  27492. /** The set of active input channels.
  27493. The bits that are set in this array indicate the channels of the
  27494. input device that are active.
  27495. */
  27496. BigInteger inputChannels;
  27497. /** If this is true, it indicates that the inputChannels array
  27498. should be ignored, and instead, the device's default channels
  27499. should be used.
  27500. */
  27501. bool useDefaultInputChannels;
  27502. /** The set of active output channels.
  27503. The bits that are set in this array indicate the channels of the
  27504. input device that are active.
  27505. */
  27506. BigInteger outputChannels;
  27507. /** If this is true, it indicates that the outputChannels array
  27508. should be ignored, and instead, the device's default channels
  27509. should be used.
  27510. */
  27511. bool useDefaultOutputChannels;
  27512. };
  27513. /** Opens a set of audio devices ready for use.
  27514. This will attempt to open either a default audio device, or one that was
  27515. previously saved as XML.
  27516. @param numInputChannelsNeeded a minimum number of input channels needed
  27517. by your app.
  27518. @param numOutputChannelsNeeded a minimum number of output channels to open
  27519. @param savedState either a previously-saved state that was produced
  27520. by createStateXml(), or 0 if you want the manager
  27521. to choose the best device to open.
  27522. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  27523. fails to open, then a default device will be used
  27524. instead. If false, then on failure, no device is
  27525. opened.
  27526. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  27527. name, then that will be used as the default device
  27528. (assuming that there wasn't one specified in the XML).
  27529. The string can actually be a simple wildcard, containing "*"
  27530. and "?" characters
  27531. @param preferredSetupOptions if this is non-null, the structure will be used as the
  27532. set of preferred settings when opening the device. If you
  27533. use this parameter, the preferredDefaultDeviceName
  27534. field will be ignored
  27535. @returns an error message if anything went wrong, or an empty string if it worked ok.
  27536. */
  27537. const String initialise (int numInputChannelsNeeded,
  27538. int numOutputChannelsNeeded,
  27539. const XmlElement* savedState,
  27540. bool selectDefaultDeviceOnFailure,
  27541. const String& preferredDefaultDeviceName = String::empty,
  27542. const AudioDeviceSetup* preferredSetupOptions = 0);
  27543. /** Returns some XML representing the current state of the manager.
  27544. This stores the current device, its samplerate, block size, etc, and
  27545. can be restored later with initialise().
  27546. */
  27547. XmlElement* createStateXml() const;
  27548. /** Returns the current device properties that are in use.
  27549. @see setAudioDeviceSetup
  27550. */
  27551. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  27552. /** Changes the current device or its settings.
  27553. If you want to change a device property, like the current sample rate or
  27554. block size, you can call getAudioDeviceSetup() to retrieve the current
  27555. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  27556. and pass it back into this method to apply the new settings.
  27557. @param newSetup the settings that you'd like to use
  27558. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  27559. settings will be taken as having been explicitly chosen by the
  27560. user, and the next time createStateXml() is called, these settings
  27561. will be returned. If it's false, then the device is treated as a
  27562. temporary or default device, and a call to createStateXml() will
  27563. return either the last settings that were made with treatAsChosenDevice
  27564. as true, or the last XML settings that were passed into initialise().
  27565. @returns an error message if anything went wrong, or an empty string if it worked ok.
  27566. @see getAudioDeviceSetup
  27567. */
  27568. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  27569. bool treatAsChosenDevice);
  27570. /** Returns the currently-active audio device. */
  27571. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  27572. /** Returns the type of audio device currently in use.
  27573. @see setCurrentAudioDeviceType
  27574. */
  27575. const String getCurrentAudioDeviceType() const { return currentDeviceType; }
  27576. /** Returns the currently active audio device type object.
  27577. Don't keep a copy of this pointer - it's owned by the device manager and could
  27578. change at any time.
  27579. */
  27580. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  27581. /** Changes the class of audio device being used.
  27582. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  27583. this because there's only one type: CoreAudio.
  27584. For a list of types, see getAvailableDeviceTypes().
  27585. */
  27586. void setCurrentAudioDeviceType (const String& type,
  27587. bool treatAsChosenDevice);
  27588. /** Closes the currently-open device.
  27589. You can call restartLastAudioDevice() later to reopen it in the same state
  27590. that it was just in.
  27591. */
  27592. void closeAudioDevice();
  27593. /** Tries to reload the last audio device that was running.
  27594. Note that this only reloads the last device that was running before
  27595. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  27596. and can only be called after a device has been opened with SetAudioDevice().
  27597. If a device is already open, this call will do nothing.
  27598. */
  27599. void restartLastAudioDevice();
  27600. /** Registers an audio callback to be used.
  27601. The manager will redirect callbacks from whatever audio device is currently
  27602. in use to all registered callback objects. If more than one callback is
  27603. active, they will all be given the same input data, and their outputs will
  27604. be summed.
  27605. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  27606. object before returning.
  27607. To remove a callback, use removeAudioCallback().
  27608. */
  27609. void addAudioCallback (AudioIODeviceCallback* newCallback);
  27610. /** Deregisters a previously added callback.
  27611. If necessary, this method will invoke audioDeviceStopped() on the callback
  27612. object before returning.
  27613. @see addAudioCallback
  27614. */
  27615. void removeAudioCallback (AudioIODeviceCallback* callback);
  27616. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  27617. Returns a value between 0 and 1.0
  27618. */
  27619. double getCpuUsage() const;
  27620. /** Enables or disables a midi input device.
  27621. The list of devices can be obtained with the MidiInput::getDevices() method.
  27622. Any incoming messages from enabled input devices will be forwarded on to all the
  27623. listeners that have been registered with the addMidiInputCallback() method. They
  27624. can either register for messages from a particular device, or from just the
  27625. "default" midi input.
  27626. Routing the midi input via an AudioDeviceManager means that when a listener
  27627. registers for the default midi input, this default device can be changed by the
  27628. manager without the listeners having to know about it or re-register.
  27629. It also means that a listener can stay registered for a midi input that is disabled
  27630. or not present, so that when the input is re-enabled, the listener will start
  27631. receiving messages again.
  27632. @see addMidiInputCallback, isMidiInputEnabled
  27633. */
  27634. void setMidiInputEnabled (const String& midiInputDeviceName,
  27635. bool enabled);
  27636. /** Returns true if a given midi input device is being used.
  27637. @see setMidiInputEnabled
  27638. */
  27639. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  27640. /** Registers a listener for callbacks when midi events arrive from a midi input.
  27641. The device name can be empty to indicate that it wants events from whatever the
  27642. current "default" device is. Or it can be the name of one of the midi input devices
  27643. (see MidiInput::getDevices() for the names).
  27644. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  27645. events forwarded on to listeners.
  27646. */
  27647. void addMidiInputCallback (const String& midiInputDeviceName,
  27648. MidiInputCallback* callback);
  27649. /** Removes a listener that was previously registered with addMidiInputCallback().
  27650. */
  27651. void removeMidiInputCallback (const String& midiInputDeviceName,
  27652. MidiInputCallback* callback);
  27653. /** Sets a midi output device to use as the default.
  27654. The list of devices can be obtained with the MidiOutput::getDevices() method.
  27655. The specified device will be opened automatically and can be retrieved with the
  27656. getDefaultMidiOutput() method.
  27657. Pass in an empty string to deselect all devices. For the default device, you
  27658. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  27659. @see getDefaultMidiOutput, getDefaultMidiOutputName
  27660. */
  27661. void setDefaultMidiOutput (const String& deviceName);
  27662. /** Returns the name of the default midi output.
  27663. @see setDefaultMidiOutput, getDefaultMidiOutput
  27664. */
  27665. const String getDefaultMidiOutputName() const { return defaultMidiOutputName; }
  27666. /** Returns the current default midi output device.
  27667. If no device has been selected, or the device can't be opened, this will
  27668. return 0.
  27669. @see getDefaultMidiOutputName
  27670. */
  27671. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  27672. /** Returns a list of the types of device supported.
  27673. */
  27674. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  27675. /** Creates a list of available types.
  27676. This will add a set of new AudioIODeviceType objects to the specified list, to
  27677. represent each available types of device.
  27678. You can override this if your app needs to do something specific, like avoid
  27679. using DirectSound devices, etc.
  27680. */
  27681. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  27682. /** Plays a beep through the current audio device.
  27683. This is here to allow the audio setup UI panels to easily include a "test"
  27684. button so that the user can check where the audio is coming from.
  27685. */
  27686. void playTestSound();
  27687. /** Turns on level-measuring.
  27688. When enabled, the device manager will measure the peak input level
  27689. across all channels, and you can get this level by calling getCurrentInputLevel().
  27690. This is mainly intended for audio setup UI panels to use to create a mic
  27691. level display, so that the user can check that they've selected the right
  27692. device.
  27693. A simple filter is used to make the level decay smoothly, but this is
  27694. only intended for giving rough feedback, and not for any kind of accurate
  27695. measurement.
  27696. */
  27697. void enableInputLevelMeasurement (bool enableMeasurement);
  27698. /** Returns the current input level.
  27699. To use this, you must first enable it by calling enableInputLevelMeasurement().
  27700. See enableInputLevelMeasurement() for more info.
  27701. */
  27702. double getCurrentInputLevel() const;
  27703. juce_UseDebuggingNewOperator
  27704. private:
  27705. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  27706. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  27707. AudioDeviceSetup currentSetup;
  27708. ScopedPointer <AudioIODevice> currentAudioDevice;
  27709. SortedSet <AudioIODeviceCallback*> callbacks;
  27710. int numInputChansNeeded, numOutputChansNeeded;
  27711. String currentDeviceType;
  27712. BigInteger inputChannels, outputChannels;
  27713. ScopedPointer <XmlElement> lastExplicitSettings;
  27714. mutable bool listNeedsScanning;
  27715. bool useInputNames;
  27716. int inputLevelMeasurementEnabledCount;
  27717. double inputLevel;
  27718. ScopedPointer <AudioSampleBuffer> testSound;
  27719. int testSoundPosition;
  27720. AudioSampleBuffer tempBuffer;
  27721. StringArray midiInsFromXml;
  27722. OwnedArray <MidiInput> enabledMidiInputs;
  27723. Array <MidiInputCallback*> midiCallbacks;
  27724. Array <MidiInput*> midiCallbackDevices;
  27725. String defaultMidiOutputName;
  27726. ScopedPointer <MidiOutput> defaultMidiOutput;
  27727. CriticalSection audioCallbackLock, midiCallbackLock;
  27728. double cpuUsageMs, timeToCpuScale;
  27729. class CallbackHandler : public AudioIODeviceCallback,
  27730. public MidiInputCallback
  27731. {
  27732. public:
  27733. AudioDeviceManager* owner;
  27734. void audioDeviceIOCallback (const float** inputChannelData,
  27735. int totalNumInputChannels,
  27736. float** outputChannelData,
  27737. int totalNumOutputChannels,
  27738. int numSamples);
  27739. void audioDeviceAboutToStart (AudioIODevice*);
  27740. void audioDeviceStopped();
  27741. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  27742. };
  27743. CallbackHandler callbackHandler;
  27744. friend class CallbackHandler;
  27745. void audioDeviceIOCallbackInt (const float** inputChannelData,
  27746. int totalNumInputChannels,
  27747. float** outputChannelData,
  27748. int totalNumOutputChannels,
  27749. int numSamples);
  27750. void audioDeviceAboutToStartInt (AudioIODevice* device);
  27751. void audioDeviceStoppedInt();
  27752. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  27753. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  27754. const BigInteger& ins, const BigInteger& outs);
  27755. void stopDevice();
  27756. void updateXml();
  27757. void createDeviceTypesIfNeeded();
  27758. void scanDevicesIfNeeded();
  27759. void deleteCurrentDevice();
  27760. double chooseBestSampleRate (double preferred) const;
  27761. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  27762. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  27763. AudioDeviceManager (const AudioDeviceManager&);
  27764. AudioDeviceManager& operator= (const AudioDeviceManager&);
  27765. };
  27766. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  27767. /*** End of inlined file: juce_AudioDeviceManager.h ***/
  27768. #endif
  27769. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  27770. #endif
  27771. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  27772. #endif
  27773. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  27774. #endif
  27775. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  27776. #endif
  27777. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  27778. /*** Start of inlined file: juce_AudioDataConverters.h ***/
  27779. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  27780. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  27781. /**
  27782. A set of routines to convert buffers of 32-bit floating point data to and from
  27783. various integer formats.
  27784. */
  27785. class JUCE_API AudioDataConverters
  27786. {
  27787. public:
  27788. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  27789. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  27790. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  27791. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  27792. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27793. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27794. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27795. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27796. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  27797. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  27798. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  27799. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  27800. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27801. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27802. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27803. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27804. enum DataFormat
  27805. {
  27806. int16LE,
  27807. int16BE,
  27808. int24LE,
  27809. int24BE,
  27810. int32LE,
  27811. int32BE,
  27812. float32LE,
  27813. float32BE,
  27814. };
  27815. static void convertFloatToFormat (DataFormat destFormat,
  27816. const float* source, void* dest, int numSamples);
  27817. static void convertFormatToFloat (DataFormat sourceFormat,
  27818. const void* source, float* dest, int numSamples);
  27819. static void interleaveSamples (const float** source, float* dest,
  27820. int numSamples, int numChannels);
  27821. static void deinterleaveSamples (const float* source, float** dest,
  27822. int numSamples, int numChannels);
  27823. private:
  27824. AudioDataConverters();
  27825. AudioDataConverters (const AudioDataConverters&);
  27826. AudioDataConverters& operator= (const AudioDataConverters&);
  27827. };
  27828. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  27829. /*** End of inlined file: juce_AudioDataConverters.h ***/
  27830. #endif
  27831. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27832. #endif
  27833. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  27834. #endif
  27835. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  27836. #endif
  27837. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  27838. /*** Start of inlined file: juce_MidiFile.h ***/
  27839. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  27840. #define __JUCE_MIDIFILE_JUCEHEADER__
  27841. /*** Start of inlined file: juce_MidiMessageSequence.h ***/
  27842. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  27843. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  27844. /**
  27845. A sequence of timestamped midi messages.
  27846. This allows the sequence to be manipulated, and also to be read from and
  27847. written to a standard midi file.
  27848. @see MidiMessage, MidiFile
  27849. */
  27850. class JUCE_API MidiMessageSequence
  27851. {
  27852. public:
  27853. /** Creates an empty midi sequence object. */
  27854. MidiMessageSequence();
  27855. /** Creates a copy of another sequence. */
  27856. MidiMessageSequence (const MidiMessageSequence& other);
  27857. /** Replaces this sequence with another one. */
  27858. MidiMessageSequence& operator= (const MidiMessageSequence& other);
  27859. /** Destructor. */
  27860. ~MidiMessageSequence();
  27861. /** Structure used to hold midi events in the sequence.
  27862. These structures act as 'handles' on the events as they are moved about in
  27863. the list, and make it quick to find the matching note-offs for note-on events.
  27864. @see MidiMessageSequence::getEventPointer
  27865. */
  27866. class MidiEventHolder
  27867. {
  27868. public:
  27869. /** Destructor. */
  27870. ~MidiEventHolder();
  27871. /** The message itself, whose timestamp is used to specify the event's time.
  27872. */
  27873. MidiMessage message;
  27874. /** The matching note-off event (if this is a note-on event).
  27875. If this isn't a note-on, this pointer will be null.
  27876. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  27877. note-offs up-to-date after events have been moved around in the sequence
  27878. or deleted.
  27879. */
  27880. MidiEventHolder* noteOffObject;
  27881. juce_UseDebuggingNewOperator
  27882. private:
  27883. friend class MidiMessageSequence;
  27884. MidiEventHolder (const MidiMessage& message);
  27885. };
  27886. /** Clears the sequence. */
  27887. void clear();
  27888. /** Returns the number of events in the sequence. */
  27889. int getNumEvents() const;
  27890. /** Returns a pointer to one of the events. */
  27891. MidiEventHolder* getEventPointer (int index) const;
  27892. /** Returns the time of the note-up that matches the note-on at this index.
  27893. If the event at this index isn't a note-on, it'll just return 0.
  27894. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  27895. */
  27896. double getTimeOfMatchingKeyUp (int index) const;
  27897. /** Returns the index of the note-up that matches the note-on at this index.
  27898. If the event at this index isn't a note-on, it'll just return -1.
  27899. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  27900. */
  27901. int getIndexOfMatchingKeyUp (int index) const;
  27902. /** Returns the index of an event. */
  27903. int getIndexOf (MidiEventHolder* event) const;
  27904. /** Returns the index of the first event on or after the given timestamp.
  27905. If the time is beyond the end of the sequence, this will return the
  27906. number of events.
  27907. */
  27908. int getNextIndexAtTime (double timeStamp) const;
  27909. /** Returns the timestamp of the first event in the sequence.
  27910. @see getEndTime
  27911. */
  27912. double getStartTime() const;
  27913. /** Returns the timestamp of the last event in the sequence.
  27914. @see getStartTime
  27915. */
  27916. double getEndTime() const;
  27917. /** Returns the timestamp of the event at a given index.
  27918. If the index is out-of-range, this will return 0.0
  27919. */
  27920. double getEventTime (int index) const;
  27921. /** Inserts a midi message into the sequence.
  27922. The index at which the new message gets inserted will depend on its timestamp,
  27923. because the sequence is kept sorted.
  27924. Remember to call updateMatchedPairs() after adding note-on events.
  27925. @param newMessage the new message to add (an internal copy will be made)
  27926. @param timeAdjustment an optional value to add to the timestamp of the message
  27927. that will be inserted
  27928. @see updateMatchedPairs
  27929. */
  27930. void addEvent (const MidiMessage& newMessage,
  27931. double timeAdjustment = 0);
  27932. /** Deletes one of the events in the sequence.
  27933. Remember to call updateMatchedPairs() after removing events.
  27934. @param index the index of the event to delete
  27935. @param deleteMatchingNoteUp whether to also remove the matching note-off
  27936. if the event you're removing is a note-on
  27937. */
  27938. void deleteEvent (int index, bool deleteMatchingNoteUp);
  27939. /** Merges another sequence into this one.
  27940. Remember to call updateMatchedPairs() after using this method.
  27941. @param other the sequence to add from
  27942. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  27943. as they are read from the other sequence
  27944. @param firstAllowableDestTime events will not be added if their time is earlier
  27945. than this time. (This is after their time has been adjusted
  27946. by the timeAdjustmentDelta)
  27947. @param endOfAllowableDestTimes events will not be added if their time is equal to
  27948. or greater than this time. (This is after their time has
  27949. been adjusted by the timeAdjustmentDelta)
  27950. */
  27951. void addSequence (const MidiMessageSequence& other,
  27952. double timeAdjustmentDelta,
  27953. double firstAllowableDestTime,
  27954. double endOfAllowableDestTimes);
  27955. /** Makes sure all the note-on and note-off pairs are up-to-date.
  27956. Call this after moving messages about or deleting/adding messages, and it
  27957. will scan the list and make sure all the note-offs in the MidiEventHolder
  27958. structures are pointing at the correct ones.
  27959. */
  27960. void updateMatchedPairs();
  27961. /** Copies all the messages for a particular midi channel to another sequence.
  27962. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  27963. @param destSequence the sequence that the chosen events should be copied to
  27964. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  27965. channel) will also be copied across.
  27966. @see extractSysExMessages
  27967. */
  27968. void extractMidiChannelMessages (int channelNumberToExtract,
  27969. MidiMessageSequence& destSequence,
  27970. bool alsoIncludeMetaEvents) const;
  27971. /** Copies all midi sys-ex messages to another sequence.
  27972. @param destSequence this is the sequence to which any sys-exes in this sequence
  27973. will be added
  27974. @see extractMidiChannelMessages
  27975. */
  27976. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  27977. /** Removes any messages in this sequence that have a specific midi channel.
  27978. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  27979. */
  27980. void deleteMidiChannelMessages (int channelNumberToRemove);
  27981. /** Removes any sys-ex messages from this sequence.
  27982. */
  27983. void deleteSysExMessages();
  27984. /** Adds an offset to the timestamps of all events in the sequence.
  27985. @param deltaTime the amount to add to each timestamp.
  27986. */
  27987. void addTimeToMessages (double deltaTime);
  27988. /** Scans through the sequence to determine the state of any midi controllers at
  27989. a given time.
  27990. This will create a sequence of midi controller changes that can be
  27991. used to set all midi controllers to the state they would be in at the
  27992. specified time within this sequence.
  27993. As well as controllers, it will also recreate the midi program number
  27994. and pitch bend position.
  27995. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  27996. for other channels will be ignored.
  27997. @param time the time at which you want to find out the state - there are
  27998. no explicit units for this time measurement, it's the same units
  27999. as used for the timestamps of the messages
  28000. @param resultMessages an array to which midi controller-change messages will be added. This
  28001. will be the minimum number of controller changes to recreate the
  28002. state at the required time.
  28003. */
  28004. void createControllerUpdatesForTime (int channelNumber, double time,
  28005. OwnedArray<MidiMessage>& resultMessages);
  28006. /** Swaps this sequence with another one. */
  28007. void swapWith (MidiMessageSequence& other) throw();
  28008. juce_UseDebuggingNewOperator
  28009. /** @internal */
  28010. static int compareElements (const MidiMessageSequence::MidiEventHolder* first,
  28011. const MidiMessageSequence::MidiEventHolder* second) throw();
  28012. private:
  28013. friend class MidiFile;
  28014. OwnedArray <MidiEventHolder> list;
  28015. void sort();
  28016. };
  28017. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  28018. /*** End of inlined file: juce_MidiMessageSequence.h ***/
  28019. /**
  28020. Reads/writes standard midi format files.
  28021. To read a midi file, create a MidiFile object and call its readFrom() method. You
  28022. can then get the individual midi tracks from it using the getTrack() method.
  28023. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  28024. to it using the addTrack() method, and then call its writeTo() method to stream
  28025. it out.
  28026. @see MidiMessageSequence
  28027. */
  28028. class JUCE_API MidiFile
  28029. {
  28030. public:
  28031. /** Creates an empty MidiFile object.
  28032. */
  28033. MidiFile();
  28034. /** Destructor. */
  28035. ~MidiFile();
  28036. /** Returns the number of tracks in the file.
  28037. @see getTrack, addTrack
  28038. */
  28039. int getNumTracks() const throw();
  28040. /** Returns a pointer to one of the tracks in the file.
  28041. @returns a pointer to the track, or 0 if the index is out-of-range
  28042. @see getNumTracks, addTrack
  28043. */
  28044. const MidiMessageSequence* getTrack (const int index) const throw();
  28045. /** Adds a midi track to the file.
  28046. This will make its own internal copy of the sequence that is passed-in.
  28047. @see getNumTracks, getTrack
  28048. */
  28049. void addTrack (const MidiMessageSequence& trackSequence);
  28050. /** Removes all midi tracks from the file.
  28051. @see getNumTracks
  28052. */
  28053. void clear();
  28054. /** Returns the raw time format code that will be written to a stream.
  28055. After reading a midi file, this method will return the time-format that
  28056. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  28057. or setSmpteTimeFormat() methods.
  28058. If the value returned is positive, it indicates the number of midi ticks
  28059. per quarter-note - see setTicksPerQuarterNote().
  28060. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  28061. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  28062. */
  28063. short getTimeFormat() const throw();
  28064. /** Sets the time format to use when this file is written to a stream.
  28065. If this is called, the file will be written as bars/beats using the
  28066. specified resolution, rather than SMPTE absolute times, as would be
  28067. used if setSmpteTimeFormat() had been called instead.
  28068. @param ticksPerQuarterNote e.g. 96, 960
  28069. @see setSmpteTimeFormat
  28070. */
  28071. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  28072. /** Sets the time format to use when this file is written to a stream.
  28073. If this is called, the file will be written using absolute times, rather
  28074. than bars/beats as would be the case if setTicksPerBeat() had been called
  28075. instead.
  28076. @param framesPerSecond must be 24, 25, 29 or 30
  28077. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  28078. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  28079. timing, setSmpteTimeFormat (25, 40)
  28080. @see setTicksPerBeat
  28081. */
  28082. void setSmpteTimeFormat (const int framesPerSecond,
  28083. const int subframeResolution) throw();
  28084. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  28085. Useful for finding the positions of all the tempo changes in a file.
  28086. @param tempoChangeEvents a list to which all the events will be added
  28087. */
  28088. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  28089. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  28090. Useful for finding the positions of all the tempo changes in a file.
  28091. @param timeSigEvents a list to which all the events will be added
  28092. */
  28093. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  28094. /** Returns the latest timestamp in any of the tracks.
  28095. (Useful for finding the length of the file).
  28096. */
  28097. double getLastTimestamp() const;
  28098. /** Reads a midi file format stream.
  28099. After calling this, you can get the tracks that were read from the file by using the
  28100. getNumTracks() and getTrack() methods.
  28101. The timestamps of the midi events in the tracks will represent their positions in
  28102. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  28103. method.
  28104. @returns true if the stream was read successfully
  28105. */
  28106. bool readFrom (InputStream& sourceStream);
  28107. /** Writes the midi tracks as a standard midi file.
  28108. @returns true if the operation succeeded.
  28109. */
  28110. bool writeTo (OutputStream& destStream);
  28111. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  28112. This will use the midi time format and tempo/time signature info in the
  28113. tracks to convert all the timestamps to absolute values in seconds.
  28114. */
  28115. void convertTimestampTicksToSeconds();
  28116. juce_UseDebuggingNewOperator
  28117. /** @internal */
  28118. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  28119. const MidiMessageSequence::MidiEventHolder* const second);
  28120. private:
  28121. OwnedArray <MidiMessageSequence> tracks;
  28122. short timeFormat;
  28123. MidiFile (const MidiFile&);
  28124. MidiFile& operator= (const MidiFile&);
  28125. void readNextTrack (const uint8* data, int size);
  28126. void writeTrack (OutputStream& mainOut, const int trackNum);
  28127. };
  28128. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  28129. /*** End of inlined file: juce_MidiFile.h ***/
  28130. #endif
  28131. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28132. /*** Start of inlined file: juce_MidiKeyboardState.h ***/
  28133. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28134. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28135. class MidiKeyboardState;
  28136. /**
  28137. Receives events from a MidiKeyboardState object.
  28138. @see MidiKeyboardState
  28139. */
  28140. class JUCE_API MidiKeyboardStateListener
  28141. {
  28142. public:
  28143. MidiKeyboardStateListener() throw() {}
  28144. virtual ~MidiKeyboardStateListener() {}
  28145. /** Called when one of the MidiKeyboardState's keys is pressed.
  28146. This will be called synchronously when the state is either processing a
  28147. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  28148. when a note is being played with its MidiKeyboardState::noteOn() method.
  28149. Note that this callback could happen from an audio callback thread, so be
  28150. careful not to block, and avoid any UI activity in the callback.
  28151. */
  28152. virtual void handleNoteOn (MidiKeyboardState* source,
  28153. int midiChannel, int midiNoteNumber, float velocity) = 0;
  28154. /** Called when one of the MidiKeyboardState's keys is released.
  28155. This will be called synchronously when the state is either processing a
  28156. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  28157. when a note is being played with its MidiKeyboardState::noteOff() method.
  28158. Note that this callback could happen from an audio callback thread, so be
  28159. careful not to block, and avoid any UI activity in the callback.
  28160. */
  28161. virtual void handleNoteOff (MidiKeyboardState* source,
  28162. int midiChannel, int midiNoteNumber) = 0;
  28163. };
  28164. /**
  28165. Represents a piano keyboard, keeping track of which keys are currently pressed.
  28166. This object can parse a stream of midi events, using them to update its idea
  28167. of which keys are pressed for each individiual midi channel.
  28168. When keys go up or down, it can broadcast these events to listener objects.
  28169. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  28170. methods, and midi messages for these events will be merged into the
  28171. midi stream that gets processed by processNextMidiBuffer().
  28172. */
  28173. class JUCE_API MidiKeyboardState
  28174. {
  28175. public:
  28176. MidiKeyboardState();
  28177. ~MidiKeyboardState();
  28178. /** Resets the state of the object.
  28179. All internal data for all the channels is reset, but no events are sent as a
  28180. result.
  28181. If you want to release any keys that are currently down, and to send out note-up
  28182. midi messages for this, use the allNotesOff() method instead.
  28183. */
  28184. void reset();
  28185. /** Returns true if the given midi key is currently held down for the given midi channel.
  28186. The channel number must be between 1 and 16. If you want to see if any notes are
  28187. on for a range of channels, use the isNoteOnForChannels() method.
  28188. */
  28189. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  28190. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  28191. The channel mask has a bit set for each midi channel you want to test for - bit
  28192. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  28193. If a note is on for at least one of the specified channels, this returns true.
  28194. */
  28195. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  28196. /** Turns a specified note on.
  28197. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  28198. next call to processNextMidiBuffer().
  28199. It will also trigger a synchronous callback to the listeners to tell them that the key has
  28200. gone down.
  28201. */
  28202. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  28203. /** Turns a specified note off.
  28204. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  28205. next call to processNextMidiBuffer().
  28206. It will also trigger a synchronous callback to the listeners to tell them that the key has
  28207. gone up.
  28208. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  28209. */
  28210. void noteOff (const int midiChannel, const int midiNoteNumber);
  28211. /** This will turn off any currently-down notes for the given midi channel.
  28212. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  28213. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  28214. and events being added to the midi stream.
  28215. */
  28216. void allNotesOff (const int midiChannel);
  28217. /** Looks at a key-up/down event and uses it to update the state of this object.
  28218. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  28219. instead.
  28220. */
  28221. void processNextMidiEvent (const MidiMessage& message);
  28222. /** Scans a midi stream for up/down events and adds its own events to it.
  28223. This will look for any up/down events and use them to update the internal state,
  28224. synchronously making suitable callbacks to the listeners.
  28225. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  28226. and noteOff() calls will be added into the buffer.
  28227. Only the section of the buffer whose timestamps are between startSample and
  28228. (startSample + numSamples) will be affected, and any events added will be placed
  28229. between these times.
  28230. If you're going to use this method, you'll need to keep calling it regularly for
  28231. it to work satisfactorily.
  28232. To process a single midi event at a time, use the processNextMidiEvent() method
  28233. instead.
  28234. */
  28235. void processNextMidiBuffer (MidiBuffer& buffer,
  28236. const int startSample,
  28237. const int numSamples,
  28238. const bool injectIndirectEvents);
  28239. /** Registers a listener for callbacks when keys go up or down.
  28240. @see removeListener
  28241. */
  28242. void addListener (MidiKeyboardStateListener* const listener) throw();
  28243. /** Deregisters a listener.
  28244. @see addListener
  28245. */
  28246. void removeListener (MidiKeyboardStateListener* const listener) throw();
  28247. juce_UseDebuggingNewOperator
  28248. private:
  28249. CriticalSection lock;
  28250. uint16 noteStates [128];
  28251. MidiBuffer eventsToAdd;
  28252. Array <MidiKeyboardStateListener*> listeners;
  28253. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  28254. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  28255. MidiKeyboardState (const MidiKeyboardState&);
  28256. MidiKeyboardState& operator= (const MidiKeyboardState&);
  28257. };
  28258. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28259. /*** End of inlined file: juce_MidiKeyboardState.h ***/
  28260. #endif
  28261. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  28262. #endif
  28263. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28264. /*** Start of inlined file: juce_MidiMessageCollector.h ***/
  28265. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28266. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28267. /**
  28268. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  28269. processing by a block-based audio callback.
  28270. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  28271. so it can easily use a midi input or keyboard component as its source.
  28272. @see MidiMessage, MidiInput
  28273. */
  28274. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  28275. public MidiInputCallback
  28276. {
  28277. public:
  28278. /** Creates a MidiMessageCollector. */
  28279. MidiMessageCollector();
  28280. /** Destructor. */
  28281. ~MidiMessageCollector();
  28282. /** Clears any messages from the queue.
  28283. You need to call this method before starting to use the collector, so that
  28284. it knows the correct sample rate to use.
  28285. */
  28286. void reset (double sampleRate);
  28287. /** Takes an incoming real-time message and adds it to the queue.
  28288. The message's timestamp is taken, and it will be ready for retrieval as part
  28289. of the block returned by the next call to removeNextBlockOfMessages().
  28290. This method is fully thread-safe when overlapping calls are made with
  28291. removeNextBlockOfMessages().
  28292. */
  28293. void addMessageToQueue (const MidiMessage& message);
  28294. /** Removes all the pending messages from the queue as a buffer.
  28295. This will also correct the messages' timestamps to make sure they're in
  28296. the range 0 to numSamples - 1.
  28297. This call should be made regularly by something like an audio processing
  28298. callback, because the time that it happens is used in calculating the
  28299. midi event positions.
  28300. This method is fully thread-safe when overlapping calls are made with
  28301. addMessageToQueue().
  28302. */
  28303. void removeNextBlockOfMessages (MidiBuffer& destBuffer, int numSamples);
  28304. /** @internal */
  28305. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  28306. /** @internal */
  28307. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  28308. /** @internal */
  28309. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  28310. juce_UseDebuggingNewOperator
  28311. private:
  28312. double lastCallbackTime;
  28313. CriticalSection midiCallbackLock;
  28314. MidiBuffer incomingMessages;
  28315. double sampleRate;
  28316. MidiMessageCollector (const MidiMessageCollector&);
  28317. MidiMessageCollector& operator= (const MidiMessageCollector&);
  28318. };
  28319. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28320. /*** End of inlined file: juce_MidiMessageCollector.h ***/
  28321. #endif
  28322. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  28323. #endif
  28324. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  28325. /*** Start of inlined file: juce_AudioUnitPluginFormat.h ***/
  28326. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  28327. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  28328. /*** Start of inlined file: juce_AudioPluginFormat.h ***/
  28329. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  28330. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  28331. /*** Start of inlined file: juce_AudioPluginInstance.h ***/
  28332. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  28333. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  28334. /*** Start of inlined file: juce_AudioProcessor.h ***/
  28335. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  28336. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  28337. /*** Start of inlined file: juce_AudioProcessorEditor.h ***/
  28338. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  28339. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  28340. class AudioProcessor;
  28341. /**
  28342. Base class for the component that acts as the GUI for an AudioProcessor.
  28343. Derive your editor component from this class, and create an instance of it
  28344. by overriding the AudioProcessor::createEditor() method.
  28345. @see AudioProcessor, GenericAudioProcessorEditor
  28346. */
  28347. class JUCE_API AudioProcessorEditor : public Component
  28348. {
  28349. protected:
  28350. /** Creates an editor for the specified processor.
  28351. */
  28352. AudioProcessorEditor (AudioProcessor* const owner);
  28353. public:
  28354. /** Destructor. */
  28355. ~AudioProcessorEditor();
  28356. /** Returns a pointer to the processor that this editor represents. */
  28357. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  28358. private:
  28359. AudioProcessor* const owner;
  28360. AudioProcessorEditor (const AudioProcessorEditor&);
  28361. AudioProcessorEditor& operator= (const AudioProcessorEditor&);
  28362. };
  28363. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  28364. /*** End of inlined file: juce_AudioProcessorEditor.h ***/
  28365. /*** Start of inlined file: juce_AudioProcessorListener.h ***/
  28366. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  28367. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  28368. class AudioProcessor;
  28369. /**
  28370. Base class for listeners that want to know about changes to an AudioProcessor.
  28371. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  28372. @see AudioProcessor
  28373. */
  28374. class JUCE_API AudioProcessorListener
  28375. {
  28376. public:
  28377. /** Destructor. */
  28378. virtual ~AudioProcessorListener() {}
  28379. /** Receives a callback when a parameter is changed.
  28380. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  28381. many audio processors will change their parameter during their audio callback.
  28382. This means that not only has your handler code got to be completely thread-safe,
  28383. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  28384. this event on your message thread, use this callback to trigger an AsyncUpdater
  28385. or ChangeBroadcaster which you can respond to on the message thread.
  28386. */
  28387. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  28388. int parameterIndex,
  28389. float newValue) = 0;
  28390. /** Called to indicate that something else in the plugin has changed, like its
  28391. program, number of parameters, etc.
  28392. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  28393. call it during their audio callback. This means that not only has your handler code
  28394. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  28395. blocking. If you need to handle this event on your message thread, use this callback
  28396. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  28397. message thread.
  28398. */
  28399. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  28400. /** Indicates that a parameter change gesture has started.
  28401. E.g. if the user is dragging a slider, this would be called when they first
  28402. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  28403. called when they release it.
  28404. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  28405. call it during their audio callback. This means that not only has your handler code
  28406. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  28407. blocking. If you need to handle this event on your message thread, use this callback
  28408. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  28409. message thread.
  28410. @see audioProcessorParameterChangeGestureEnd
  28411. */
  28412. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  28413. int parameterIndex);
  28414. /** Indicates that a parameter change gesture has finished.
  28415. E.g. if the user is dragging a slider, this would be called when they release
  28416. the mouse button.
  28417. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  28418. call it during their audio callback. This means that not only has your handler code
  28419. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  28420. blocking. If you need to handle this event on your message thread, use this callback
  28421. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  28422. message thread.
  28423. @see audioPluginParameterChangeGestureStart
  28424. */
  28425. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  28426. int parameterIndex);
  28427. };
  28428. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  28429. /*** End of inlined file: juce_AudioProcessorListener.h ***/
  28430. /*** Start of inlined file: juce_AudioPlayHead.h ***/
  28431. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28432. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28433. /**
  28434. A subclass of AudioPlayHead can supply information about the position and
  28435. status of a moving play head during audio playback.
  28436. One of these can be supplied to an AudioProcessor object so that it can find
  28437. out about the position of the audio that it is rendering.
  28438. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  28439. */
  28440. class JUCE_API AudioPlayHead
  28441. {
  28442. protected:
  28443. AudioPlayHead() {}
  28444. public:
  28445. virtual ~AudioPlayHead() {}
  28446. /** Frame rate types. */
  28447. enum FrameRateType
  28448. {
  28449. fps24 = 0,
  28450. fps25 = 1,
  28451. fps2997 = 2,
  28452. fps30 = 3,
  28453. fps2997drop = 4,
  28454. fps30drop = 5,
  28455. fpsUnknown = 99
  28456. };
  28457. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  28458. */
  28459. struct CurrentPositionInfo
  28460. {
  28461. /** The tempo in BPM */
  28462. double bpm;
  28463. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  28464. int timeSigNumerator;
  28465. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  28466. int timeSigDenominator;
  28467. /** The current play position, in seconds from the start of the edit. */
  28468. double timeInSeconds;
  28469. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  28470. double editOriginTime;
  28471. /** The current play position in pulses-per-quarter-note.
  28472. This is the number of quarter notes since the edit start.
  28473. */
  28474. double ppqPosition;
  28475. /** The position of the start of the last bar, in pulses-per-quarter-note.
  28476. This is the number of quarter notes from the start of the edit to the
  28477. start of the current bar.
  28478. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  28479. it's not available, the value will be 0.
  28480. */
  28481. double ppqPositionOfLastBarStart;
  28482. /** The video frame rate, if applicable. */
  28483. FrameRateType frameRate;
  28484. /** True if the transport is currently playing. */
  28485. bool isPlaying;
  28486. /** True if the transport is currently recording.
  28487. (When isRecording is true, then isPlaying will also be true).
  28488. */
  28489. bool isRecording;
  28490. bool operator== (const CurrentPositionInfo& other) const throw();
  28491. bool operator!= (const CurrentPositionInfo& other) const throw();
  28492. void resetToDefault();
  28493. };
  28494. /** Fills-in the given structure with details about the transport's
  28495. position at the start of the current processing block.
  28496. */
  28497. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  28498. };
  28499. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28500. /*** End of inlined file: juce_AudioPlayHead.h ***/
  28501. /**
  28502. Base class for audio processing filters or plugins.
  28503. This is intended to act as a base class of audio filter that is general enough to
  28504. be wrapped as a VST, AU, RTAS, etc, or used internally.
  28505. It is also used by the plugin hosting code as the wrapper around an instance
  28506. of a loaded plugin.
  28507. Derive your filter class from this base class, and if you're building a plugin,
  28508. you should implement a global function called createPluginFilter() which creates
  28509. and returns a new instance of your subclass.
  28510. */
  28511. class JUCE_API AudioProcessor
  28512. {
  28513. protected:
  28514. /** Constructor.
  28515. You can also do your initialisation tasks in the initialiseFilterInfo()
  28516. call, which will be made after this object has been created.
  28517. */
  28518. AudioProcessor();
  28519. public:
  28520. /** Destructor. */
  28521. virtual ~AudioProcessor();
  28522. /** Returns the name of this processor.
  28523. */
  28524. virtual const String getName() const = 0;
  28525. /** Called before playback starts, to let the filter prepare itself.
  28526. The sample rate is the target sample rate, and will remain constant until
  28527. playback stops.
  28528. The estimatedSamplesPerBlock value is a HINT about the typical number of
  28529. samples that will be processed for each callback, but isn't any kind
  28530. of guarantee. The actual block sizes that the host uses may be different
  28531. each time the callback happens, and may be more or less than this value.
  28532. */
  28533. virtual void prepareToPlay (double sampleRate,
  28534. int estimatedSamplesPerBlock) = 0;
  28535. /** Called after playback has stopped, to let the filter free up any resources it
  28536. no longer needs.
  28537. */
  28538. virtual void releaseResources() = 0;
  28539. /** Renders the next block.
  28540. When this method is called, the buffer contains a number of channels which is
  28541. at least as great as the maximum number of input and output channels that
  28542. this filter is using. It will be filled with the filter's input data and
  28543. should be replaced with the filter's output.
  28544. So for example if your filter has 2 input channels and 4 output channels, then
  28545. the buffer will contain 4 channels, the first two being filled with the
  28546. input data. Your filter should read these, do its processing, and replace
  28547. the contents of all 4 channels with its output.
  28548. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  28549. all filled with data, and your filter should overwrite the first 2 of these
  28550. with its output. But be VERY careful not to write anything to the last 3
  28551. channels, as these might be mapped to memory that the host assumes is read-only!
  28552. Note that if you have more outputs than inputs, then only those channels that
  28553. correspond to an input channel are guaranteed to contain sensible data - e.g.
  28554. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  28555. but the last two channels may contain garbage, so you should be careful not to
  28556. let this pass through without being overwritten or cleared.
  28557. Also note that the buffer may have more channels than are strictly necessary,
  28558. but your should only read/write from the ones that your filter is supposed to
  28559. be using.
  28560. The number of samples in these buffers is NOT guaranteed to be the same for every
  28561. callback, and may be more or less than the estimated value given to prepareToPlay().
  28562. Your code must be able to cope with variable-sized blocks, or you're going to get
  28563. clicks and crashes!
  28564. If the filter is receiving a midi input, then the midiMessages array will be filled
  28565. with the midi messages for this block. Each message's timestamp will indicate the
  28566. message's time, as a number of samples from the start of the block.
  28567. Any messages left in the midi buffer when this method has finished are assumed to
  28568. be the filter's midi output. This means that your filter should be careful to
  28569. clear any incoming messages from the array if it doesn't want them to be passed-on.
  28570. Be very careful about what you do in this callback - it's going to be called by
  28571. the audio thread, so any kind of interaction with the UI is absolutely
  28572. out of the question. If you change a parameter in here and need to tell your UI to
  28573. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  28574. the UI components register as listeners, and then call sendChangeMessage() inside the
  28575. processBlock() method to send out an asynchronous message. You could also use
  28576. the AsyncUpdater class in a similar way.
  28577. */
  28578. virtual void processBlock (AudioSampleBuffer& buffer,
  28579. MidiBuffer& midiMessages) = 0;
  28580. /** Returns the current AudioPlayHead object that should be used to find
  28581. out the state and position of the playhead.
  28582. You can call this from your processBlock() method, and use the AudioPlayHead
  28583. object to get the details about the time of the start of the block currently
  28584. being processed.
  28585. If the host hasn't supplied a playhead object, this will return 0.
  28586. */
  28587. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  28588. /** Returns the current sample rate.
  28589. This can be called from your processBlock() method - it's not guaranteed
  28590. to be valid at any other time, and may return 0 if it's unknown.
  28591. */
  28592. double getSampleRate() const throw() { return sampleRate; }
  28593. /** Returns the current typical block size that is being used.
  28594. This can be called from your processBlock() method - it's not guaranteed
  28595. to be valid at any other time.
  28596. Remember it's not the ONLY block size that may be used when calling
  28597. processBlock, it's just the normal one. The actual block sizes used may be
  28598. larger or smaller than this, and will vary between successive calls.
  28599. */
  28600. int getBlockSize() const throw() { return blockSize; }
  28601. /** Returns the number of input channels that the host will be sending the filter.
  28602. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  28603. number of channels that your filter would prefer to have, and this method lets
  28604. you know how many the host is actually using.
  28605. Note that this method is only valid during or after the prepareToPlay()
  28606. method call. Until that point, the number of channels will be unknown.
  28607. */
  28608. int getNumInputChannels() const throw() { return numInputChannels; }
  28609. /** Returns the number of output channels that the host will be sending the filter.
  28610. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  28611. number of channels that your filter would prefer to have, and this method lets
  28612. you know how many the host is actually using.
  28613. Note that this method is only valid during or after the prepareToPlay()
  28614. method call. Until that point, the number of channels will be unknown.
  28615. */
  28616. int getNumOutputChannels() const throw() { return numOutputChannels; }
  28617. /** Returns the name of one of the input channels, as returned by the host.
  28618. The host might not supply very useful names for channels, and this might be
  28619. something like "1", "2", "left", "right", etc.
  28620. */
  28621. virtual const String getInputChannelName (const int channelIndex) const = 0;
  28622. /** Returns the name of one of the output channels, as returned by the host.
  28623. The host might not supply very useful names for channels, and this might be
  28624. something like "1", "2", "left", "right", etc.
  28625. */
  28626. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  28627. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  28628. virtual bool isInputChannelStereoPair (int index) const = 0;
  28629. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  28630. virtual bool isOutputChannelStereoPair (int index) const = 0;
  28631. /** This returns the number of samples delay that the filter imposes on the audio
  28632. passing through it.
  28633. The host will call this to find the latency - the filter itself should set this value
  28634. by calling setLatencySamples() as soon as it can during its initialisation.
  28635. */
  28636. int getLatencySamples() const throw() { return latencySamples; }
  28637. /** The filter should call this to set the number of samples delay that it introduces.
  28638. The filter should call this as soon as it can during initialisation, and can call it
  28639. later if the value changes.
  28640. */
  28641. void setLatencySamples (const int newLatency);
  28642. /** Returns true if the processor wants midi messages. */
  28643. virtual bool acceptsMidi() const = 0;
  28644. /** Returns true if the processor produces midi messages. */
  28645. virtual bool producesMidi() const = 0;
  28646. /** This returns a critical section that will automatically be locked while the host
  28647. is calling the processBlock() method.
  28648. Use it from your UI or other threads to lock access to variables that are used
  28649. by the process callback, but obviously be careful not to keep it locked for
  28650. too long, because that could cause stuttering playback. If you need to do something
  28651. that'll take a long time and need the processing to stop while it happens, use the
  28652. suspendProcessing() method instead.
  28653. @see suspendProcessing
  28654. */
  28655. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  28656. /** Enables and disables the processing callback.
  28657. If you need to do something time-consuming on a thread and would like to make sure
  28658. the audio processing callback doesn't happen until you've finished, use this
  28659. to disable the callback and re-enable it again afterwards.
  28660. E.g.
  28661. @code
  28662. void loadNewPatch()
  28663. {
  28664. suspendProcessing (true);
  28665. ..do something that takes ages..
  28666. suspendProcessing (false);
  28667. }
  28668. @endcode
  28669. If the host tries to make an audio callback while processing is suspended, the
  28670. filter will return an empty buffer, but won't block the audio thread like it would
  28671. do if you use the getCallbackLock() critical section to synchronise access.
  28672. If you're going to use this, your processBlock() method must call isSuspended() and
  28673. check whether it's suspended or not. If it is, then it should skip doing any real
  28674. processing, either emitting silence or passing the input through unchanged.
  28675. @see getCallbackLock
  28676. */
  28677. void suspendProcessing (const bool shouldBeSuspended);
  28678. /** Returns true if processing is currently suspended.
  28679. @see suspendProcessing
  28680. */
  28681. bool isSuspended() const throw() { return suspended; }
  28682. /** A plugin can override this to be told when it should reset any playing voices.
  28683. The default implementation does nothing, but a host may call this to tell the
  28684. plugin that it should stop any tails or sounds that have been left running.
  28685. */
  28686. virtual void reset();
  28687. /** Returns true if the processor is being run in an offline mode for rendering.
  28688. If the processor is being run live on realtime signals, this returns false.
  28689. If the mode is unknown, this will assume it's realtime and return false.
  28690. This value may be unreliable until the prepareToPlay() method has been called,
  28691. and could change each time prepareToPlay() is called.
  28692. @see setNonRealtime()
  28693. */
  28694. bool isNonRealtime() const throw() { return nonRealtime; }
  28695. /** Called by the host to tell this processor whether it's being used in a non-realime
  28696. capacity for offline rendering or bouncing.
  28697. Whatever value is passed-in will be
  28698. */
  28699. void setNonRealtime (const bool isNonRealtime) throw();
  28700. /** Creates the filter's UI.
  28701. This can return 0 if you want a UI-less filter, in which case the host may create
  28702. a generic UI that lets the user twiddle the parameters directly.
  28703. If you do want to pass back a component, the component should be created and set to
  28704. the correct size before returning it.
  28705. Remember not to do anything silly like allowing your filter to keep a pointer to
  28706. the component that gets created - it could be deleted later without any warning, which
  28707. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  28708. The correct way to handle the connection between an editor component and its
  28709. filter is to use something like a ChangeBroadcaster so that the editor can
  28710. register itself as a listener, and be told when a change occurs. This lets them
  28711. safely unregister themselves when they are deleted.
  28712. Here are a few things to bear in mind when writing an editor:
  28713. - Initially there won't be an editor, until the user opens one, or they might
  28714. not open one at all. Your filter mustn't rely on it being there.
  28715. - An editor object may be deleted and a replacement one created again at any time.
  28716. - It's safe to assume that an editor will be deleted before its filter.
  28717. */
  28718. virtual AudioProcessorEditor* createEditor() = 0;
  28719. /** Returns the active editor, if there is one.
  28720. Bear in mind this can return 0, even if an editor has previously been
  28721. opened.
  28722. */
  28723. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  28724. /** Returns the active editor, or if there isn't one, it will create one.
  28725. This may call createEditor() internally to create the component.
  28726. */
  28727. AudioProcessorEditor* createEditorIfNeeded();
  28728. /** This must return the correct value immediately after the object has been
  28729. created, and mustn't change the number of parameters later.
  28730. */
  28731. virtual int getNumParameters() = 0;
  28732. /** Returns the name of a particular parameter. */
  28733. virtual const String getParameterName (int parameterIndex) = 0;
  28734. /** Called by the host to find out the value of one of the filter's parameters.
  28735. The host will expect the value returned to be between 0 and 1.0.
  28736. This could be called quite frequently, so try to make your code efficient.
  28737. It's also likely to be called by non-UI threads, so the code in here should
  28738. be thread-aware.
  28739. */
  28740. virtual float getParameter (int parameterIndex) = 0;
  28741. /** Returns the value of a parameter as a text string. */
  28742. virtual const String getParameterText (int parameterIndex) = 0;
  28743. /** The host will call this method to change the value of one of the filter's parameters.
  28744. The host may call this at any time, including during the audio processing
  28745. callback, so the filter has to process this very fast and avoid blocking.
  28746. If you want to set the value of a parameter internally, e.g. from your
  28747. editor component, then don't call this directly - instead, use the
  28748. setParameterNotifyingHost() method, which will also send a message to
  28749. the host telling it about the change. If the message isn't sent, the host
  28750. won't be able to automate your parameters properly.
  28751. The value passed will be between 0 and 1.0.
  28752. */
  28753. virtual void setParameter (int parameterIndex,
  28754. float newValue) = 0;
  28755. /** Your filter can call this when it needs to change one of its parameters.
  28756. This could happen when the editor or some other internal operation changes
  28757. a parameter. This method will call the setParameter() method to change the
  28758. value, and will then send a message to the host telling it about the change.
  28759. Note that to make sure the host correctly handles automation, you should call
  28760. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  28761. tell the host when the user has started and stopped changing the parameter.
  28762. */
  28763. void setParameterNotifyingHost (int parameterIndex,
  28764. float newValue);
  28765. /** Returns true if the host can automate this parameter.
  28766. By default, this returns true for all parameters.
  28767. */
  28768. virtual bool isParameterAutomatable (int parameterIndex) const;
  28769. /** Should return true if this parameter is a "meta" parameter.
  28770. A meta-parameter is a parameter that changes other params. It is used
  28771. by some hosts (e.g. AudioUnit hosts).
  28772. By default this returns false.
  28773. */
  28774. virtual bool isMetaParameter (int parameterIndex) const;
  28775. /** Sends a signal to the host to tell it that the user is about to start changing this
  28776. parameter.
  28777. This allows the host to know when a parameter is actively being held by the user, and
  28778. it may use this information to help it record automation.
  28779. If you call this, it must be matched by a later call to endParameterChangeGesture().
  28780. */
  28781. void beginParameterChangeGesture (int parameterIndex);
  28782. /** Tells the host that the user has finished changing this parameter.
  28783. This allows the host to know when a parameter is actively being held by the user, and
  28784. it may use this information to help it record automation.
  28785. A call to this method must follow a call to beginParameterChangeGesture().
  28786. */
  28787. void endParameterChangeGesture (int parameterIndex);
  28788. /** The filter can call this when something (apart from a parameter value) has changed.
  28789. It sends a hint to the host that something like the program, number of parameters,
  28790. etc, has changed, and that it should update itself.
  28791. */
  28792. void updateHostDisplay();
  28793. /** Returns the number of preset programs the filter supports.
  28794. The value returned must be valid as soon as this object is created, and
  28795. must not change over its lifetime.
  28796. This value shouldn't be less than 1.
  28797. */
  28798. virtual int getNumPrograms() = 0;
  28799. /** Returns the number of the currently active program.
  28800. */
  28801. virtual int getCurrentProgram() = 0;
  28802. /** Called by the host to change the current program.
  28803. */
  28804. virtual void setCurrentProgram (int index) = 0;
  28805. /** Must return the name of a given program. */
  28806. virtual const String getProgramName (int index) = 0;
  28807. /** Called by the host to rename a program.
  28808. */
  28809. virtual void changeProgramName (int index, const String& newName) = 0;
  28810. /** The host will call this method when it wants to save the filter's internal state.
  28811. This must copy any info about the filter's state into the block of memory provided,
  28812. so that the host can store this and later restore it using setStateInformation().
  28813. Note that there's also a getCurrentProgramStateInformation() method, which only
  28814. stores the current program, not the state of the entire filter.
  28815. See also the helper function copyXmlToBinary() for storing settings as XML.
  28816. @see getCurrentProgramStateInformation
  28817. */
  28818. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  28819. /** The host will call this method if it wants to save the state of just the filter's
  28820. current program.
  28821. Unlike getStateInformation, this should only return the current program's state.
  28822. Not all hosts support this, and if you don't implement it, the base class
  28823. method just calls getStateInformation() instead. If you do implement it, be
  28824. sure to also implement getCurrentProgramStateInformation.
  28825. @see getStateInformation, setCurrentProgramStateInformation
  28826. */
  28827. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  28828. /** This must restore the filter's state from a block of data previously created
  28829. using getStateInformation().
  28830. Note that there's also a setCurrentProgramStateInformation() method, which tries
  28831. to restore just the current program, not the state of the entire filter.
  28832. See also the helper function getXmlFromBinary() for loading settings as XML.
  28833. @see setCurrentProgramStateInformation
  28834. */
  28835. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  28836. /** The host will call this method if it wants to restore the state of just the filter's
  28837. current program.
  28838. Not all hosts support this, and if you don't implement it, the base class
  28839. method just calls setStateInformation() instead. If you do implement it, be
  28840. sure to also implement getCurrentProgramStateInformation.
  28841. @see setStateInformation, getCurrentProgramStateInformation
  28842. */
  28843. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  28844. /** Adds a listener that will be called when an aspect of this processor changes. */
  28845. void addListener (AudioProcessorListener* const newListener) throw();
  28846. /** Removes a previously added listener. */
  28847. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  28848. /** Not for public use - this is called before deleting an editor component. */
  28849. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  28850. /** Not for public use - this is called to initialise the processor. */
  28851. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  28852. /** Not for public use - this is called to initialise the processor before playing. */
  28853. void setPlayConfigDetails (const int numIns, const int numOuts,
  28854. const double sampleRate,
  28855. const int blockSize) throw();
  28856. juce_UseDebuggingNewOperator
  28857. protected:
  28858. /** Helper function that just converts an xml element into a binary blob.
  28859. Use this in your filter's getStateInformation() method if you want to
  28860. store its state as xml.
  28861. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  28862. from a binary blob.
  28863. */
  28864. static void copyXmlToBinary (const XmlElement& xml,
  28865. JUCE_NAMESPACE::MemoryBlock& destData);
  28866. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  28867. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  28868. an XmlElement object that the caller must delete when no longer needed.
  28869. */
  28870. static XmlElement* getXmlFromBinary (const void* data,
  28871. const int sizeInBytes);
  28872. /** @internal */
  28873. AudioPlayHead* playHead;
  28874. /** @internal */
  28875. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  28876. private:
  28877. Array <AudioProcessorListener*> listeners;
  28878. AudioProcessorEditor* activeEditor;
  28879. double sampleRate;
  28880. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  28881. bool suspended, nonRealtime;
  28882. CriticalSection callbackLock, listenerLock;
  28883. #if JUCE_DEBUG
  28884. BigInteger changingParams;
  28885. #endif
  28886. AudioProcessor (const AudioProcessor&);
  28887. AudioProcessor& operator= (const AudioProcessor&);
  28888. };
  28889. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  28890. /*** End of inlined file: juce_AudioProcessor.h ***/
  28891. /*** Start of inlined file: juce_PluginDescription.h ***/
  28892. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  28893. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  28894. /**
  28895. A small class to represent some facts about a particular type of plugin.
  28896. This class is for storing and managing the details about a plugin without
  28897. actually having to load an instance of it.
  28898. A KnownPluginList contains a list of PluginDescription objects.
  28899. @see KnownPluginList
  28900. */
  28901. class JUCE_API PluginDescription
  28902. {
  28903. public:
  28904. PluginDescription() throw();
  28905. PluginDescription (const PluginDescription& other) throw();
  28906. PluginDescription& operator= (const PluginDescription& other) throw();
  28907. ~PluginDescription() throw();
  28908. /** The name of the plugin. */
  28909. String name;
  28910. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  28911. */
  28912. String pluginFormatName;
  28913. /** A category, such as "Dynamics", "Reverbs", etc.
  28914. */
  28915. String category;
  28916. /** The manufacturer. */
  28917. String manufacturerName;
  28918. /** The version. This string doesn't have any particular format. */
  28919. String version;
  28920. /** Either the file containing the plugin module, or some other unique way
  28921. of identifying it.
  28922. E.g. for an AU, this would be an ID string that the component manager
  28923. could use to retrieve the plugin. For a VST, it's the file path.
  28924. */
  28925. String fileOrIdentifier;
  28926. /** The last time the plugin file was changed.
  28927. This is handy when scanning for new or changed plugins.
  28928. */
  28929. Time lastFileModTime;
  28930. /** A unique ID for the plugin.
  28931. Note that this might not be unique between formats, e.g. a VST and some
  28932. other format might actually have the same id.
  28933. @see createIdentifierString
  28934. */
  28935. int uid;
  28936. /** True if the plugin identifies itself as a synthesiser. */
  28937. bool isInstrument;
  28938. /** The number of inputs. */
  28939. int numInputChannels;
  28940. /** The number of outputs. */
  28941. int numOutputChannels;
  28942. /** Returns true if the two descriptions refer the the same plugin.
  28943. This isn't quite as simple as them just having the same file (because of
  28944. shell plugins).
  28945. */
  28946. bool isDuplicateOf (const PluginDescription& other) const;
  28947. /** Returns a string that can be saved and used to uniquely identify the
  28948. plugin again.
  28949. This contains less info than the XML encoding, and is independent of the
  28950. plugin's file location, so can be used to store a plugin ID for use
  28951. across different machines.
  28952. */
  28953. const String createIdentifierString() const throw();
  28954. /** Creates an XML object containing these details.
  28955. @see loadFromXml
  28956. */
  28957. XmlElement* createXml() const;
  28958. /** Reloads the info in this structure from an XML record that was previously
  28959. saved with createXML().
  28960. Returns true if the XML was a valid plugin description.
  28961. */
  28962. bool loadFromXml (const XmlElement& xml);
  28963. juce_UseDebuggingNewOperator
  28964. };
  28965. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  28966. /*** End of inlined file: juce_PluginDescription.h ***/
  28967. /**
  28968. Base class for an active instance of a plugin.
  28969. This derives from the AudioProcessor class, and adds some extra functionality
  28970. that helps when wrapping dynamically loaded plugins.
  28971. @see AudioProcessor, AudioPluginFormat
  28972. */
  28973. class JUCE_API AudioPluginInstance : public AudioProcessor
  28974. {
  28975. public:
  28976. /** Destructor.
  28977. Make sure that you delete any UI components that belong to this plugin before
  28978. deleting the plugin.
  28979. */
  28980. virtual ~AudioPluginInstance();
  28981. /** Fills-in the appropriate parts of this plugin description object.
  28982. */
  28983. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  28984. juce_UseDebuggingNewOperator
  28985. protected:
  28986. AudioPluginInstance();
  28987. AudioPluginInstance (const AudioPluginInstance&);
  28988. AudioPluginInstance& operator= (const AudioPluginInstance&);
  28989. };
  28990. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  28991. /*** End of inlined file: juce_AudioPluginInstance.h ***/
  28992. class PluginDescription;
  28993. /**
  28994. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  28995. Use the static getNumFormats() and getFormat() calls to find the types
  28996. of format that are available.
  28997. */
  28998. class JUCE_API AudioPluginFormat
  28999. {
  29000. public:
  29001. /** Destructor. */
  29002. virtual ~AudioPluginFormat();
  29003. /** Returns the format name.
  29004. E.g. "VST", "AudioUnit", etc.
  29005. */
  29006. virtual const String getName() const = 0;
  29007. /** This tries to create descriptions for all the plugin types available in
  29008. a binary module file.
  29009. The file will be some kind of DLL or bundle.
  29010. Normally there will only be one type returned, but some plugins
  29011. (e.g. VST shells) can use a single DLL to create a set of different plugin
  29012. subtypes, so in that case, each subtype is returned as a separate object.
  29013. */
  29014. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  29015. const String& fileOrIdentifier) = 0;
  29016. /** Tries to recreate a type from a previously generated PluginDescription.
  29017. @see PluginDescription::createInstance
  29018. */
  29019. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  29020. /** Should do a quick check to see if this file or directory might be a plugin of
  29021. this format.
  29022. This is for searching for potential files, so it shouldn't actually try to
  29023. load the plugin or do anything time-consuming.
  29024. */
  29025. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  29026. /** Returns a readable version of the name of the plugin that this identifier refers to.
  29027. */
  29028. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  29029. /** Checks whether this plugin could possibly be loaded.
  29030. It doesn't actually need to load it, just to check whether the file or component
  29031. still exists.
  29032. */
  29033. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  29034. /** Searches a suggested set of directories for any plugins in this format.
  29035. The path might be ignored, e.g. by AUs, which are found by the OS rather
  29036. than manually.
  29037. */
  29038. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  29039. bool recursive) = 0;
  29040. /** Returns the typical places to look for this kind of plugin.
  29041. Note that if this returns no paths, it means that the format can't be scanned-for
  29042. (i.e. it's an internal format that doesn't live in files)
  29043. */
  29044. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  29045. juce_UseDebuggingNewOperator
  29046. protected:
  29047. AudioPluginFormat() throw();
  29048. AudioPluginFormat (const AudioPluginFormat&);
  29049. AudioPluginFormat& operator= (const AudioPluginFormat&);
  29050. };
  29051. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  29052. /*** End of inlined file: juce_AudioPluginFormat.h ***/
  29053. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  29054. /**
  29055. Implements a plugin format manager for AudioUnits.
  29056. */
  29057. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  29058. {
  29059. public:
  29060. AudioUnitPluginFormat();
  29061. ~AudioUnitPluginFormat();
  29062. const String getName() const { return "AudioUnit"; }
  29063. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29064. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29065. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29066. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  29067. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  29068. bool doesPluginStillExist (const PluginDescription& desc);
  29069. const FileSearchPath getDefaultLocationsToSearch();
  29070. juce_UseDebuggingNewOperator
  29071. private:
  29072. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  29073. AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  29074. };
  29075. #endif
  29076. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  29077. /*** End of inlined file: juce_AudioUnitPluginFormat.h ***/
  29078. #endif
  29079. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29080. /*** Start of inlined file: juce_DirectXPluginFormat.h ***/
  29081. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29082. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29083. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  29084. // Sorry, this file is just a placeholder at the moment!...
  29085. /**
  29086. Implements a plugin format manager for DirectX plugins.
  29087. */
  29088. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  29089. {
  29090. public:
  29091. DirectXPluginFormat();
  29092. ~DirectXPluginFormat();
  29093. const String getName() const { return "DirectX"; }
  29094. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29095. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29096. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29097. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  29098. const FileSearchPath getDefaultLocationsToSearch();
  29099. juce_UseDebuggingNewOperator
  29100. private:
  29101. DirectXPluginFormat (const DirectXPluginFormat&);
  29102. DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  29103. };
  29104. #endif
  29105. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29106. /*** End of inlined file: juce_DirectXPluginFormat.h ***/
  29107. #endif
  29108. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29109. /*** Start of inlined file: juce_LADSPAPluginFormat.h ***/
  29110. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29111. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29112. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  29113. // Sorry, this file is just a placeholder at the moment!...
  29114. /**
  29115. Implements a plugin format manager for DirectX plugins.
  29116. */
  29117. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  29118. {
  29119. public:
  29120. LADSPAPluginFormat();
  29121. ~LADSPAPluginFormat();
  29122. const String getName() const { return "LADSPA"; }
  29123. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29124. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29125. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29126. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  29127. const FileSearchPath getDefaultLocationsToSearch();
  29128. juce_UseDebuggingNewOperator
  29129. private:
  29130. LADSPAPluginFormat (const LADSPAPluginFormat&);
  29131. LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  29132. };
  29133. #endif
  29134. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29135. /*** End of inlined file: juce_LADSPAPluginFormat.h ***/
  29136. #endif
  29137. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29138. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  29139. #ifdef __aeffect__
  29140. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29141. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29142. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  29143. events to the list.
  29144. This is used by both the VST hosting code and the plugin wrapper.
  29145. */
  29146. class VSTMidiEventList
  29147. {
  29148. public:
  29149. VSTMidiEventList()
  29150. : numEventsUsed (0), numEventsAllocated (0)
  29151. {
  29152. }
  29153. ~VSTMidiEventList()
  29154. {
  29155. freeEvents();
  29156. }
  29157. void clear()
  29158. {
  29159. numEventsUsed = 0;
  29160. if (events != 0)
  29161. events->numEvents = 0;
  29162. }
  29163. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  29164. {
  29165. ensureSize (numEventsUsed + 1);
  29166. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  29167. events->numEvents = ++numEventsUsed;
  29168. if (numBytes <= 4)
  29169. {
  29170. if (e->type == kVstSysExType)
  29171. {
  29172. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  29173. e->type = kVstMidiType;
  29174. e->byteSize = sizeof (VstMidiEvent);
  29175. e->noteLength = 0;
  29176. e->noteOffset = 0;
  29177. e->detune = 0;
  29178. e->noteOffVelocity = 0;
  29179. }
  29180. e->deltaFrames = frameOffset;
  29181. memcpy (e->midiData, midiData, numBytes);
  29182. }
  29183. else
  29184. {
  29185. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  29186. if (se->type == kVstSysExType)
  29187. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  29188. else
  29189. se->sysexDump = (char*) juce_malloc (numBytes);
  29190. memcpy (se->sysexDump, midiData, numBytes);
  29191. se->type = kVstSysExType;
  29192. se->byteSize = sizeof (VstMidiSysexEvent);
  29193. se->deltaFrames = frameOffset;
  29194. se->flags = 0;
  29195. se->dumpBytes = numBytes;
  29196. se->resvd1 = 0;
  29197. se->resvd2 = 0;
  29198. }
  29199. }
  29200. // Handy method to pull the events out of an event buffer supplied by the host
  29201. // or plugin.
  29202. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  29203. {
  29204. for (int i = 0; i < events->numEvents; ++i)
  29205. {
  29206. const VstEvent* const e = events->events[i];
  29207. if (e != 0)
  29208. {
  29209. if (e->type == kVstMidiType)
  29210. {
  29211. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  29212. 4, e->deltaFrames);
  29213. }
  29214. else if (e->type == kVstSysExType)
  29215. {
  29216. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  29217. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  29218. e->deltaFrames);
  29219. }
  29220. }
  29221. }
  29222. }
  29223. void ensureSize (int numEventsNeeded)
  29224. {
  29225. if (numEventsNeeded > numEventsAllocated)
  29226. {
  29227. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  29228. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  29229. if (events == 0)
  29230. events.calloc (size, 1);
  29231. else
  29232. events.realloc (size, 1);
  29233. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  29234. {
  29235. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  29236. (int) sizeof (VstMidiSysexEvent)));
  29237. e->type = kVstMidiType;
  29238. e->byteSize = sizeof (VstMidiEvent);
  29239. events->events[i] = (VstEvent*) e;
  29240. }
  29241. numEventsAllocated = numEventsNeeded;
  29242. }
  29243. }
  29244. void freeEvents()
  29245. {
  29246. if (events != 0)
  29247. {
  29248. for (int i = numEventsAllocated; --i >= 0;)
  29249. {
  29250. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  29251. if (e->type == kVstSysExType)
  29252. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  29253. juce_free (e);
  29254. }
  29255. events.free();
  29256. numEventsUsed = 0;
  29257. numEventsAllocated = 0;
  29258. }
  29259. }
  29260. HeapBlock <VstEvents> events;
  29261. private:
  29262. int numEventsUsed, numEventsAllocated;
  29263. };
  29264. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29265. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29266. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  29267. #endif
  29268. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29269. /*** Start of inlined file: juce_VSTPluginFormat.h ***/
  29270. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29271. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29272. #if JUCE_PLUGINHOST_VST
  29273. /**
  29274. Implements a plugin format manager for VSTs.
  29275. */
  29276. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  29277. {
  29278. public:
  29279. VSTPluginFormat();
  29280. ~VSTPluginFormat();
  29281. const String getName() const { return "VST"; }
  29282. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29283. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29284. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29285. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  29286. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  29287. bool doesPluginStillExist (const PluginDescription& desc);
  29288. const FileSearchPath getDefaultLocationsToSearch();
  29289. juce_UseDebuggingNewOperator
  29290. private:
  29291. VSTPluginFormat (const VSTPluginFormat&);
  29292. VSTPluginFormat& operator= (const VSTPluginFormat&);
  29293. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  29294. };
  29295. #endif
  29296. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29297. /*** End of inlined file: juce_VSTPluginFormat.h ***/
  29298. #endif
  29299. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  29300. #endif
  29301. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29302. /*** Start of inlined file: juce_AudioPluginFormatManager.h ***/
  29303. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29304. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29305. /**
  29306. This maintains a list of known AudioPluginFormats.
  29307. @see AudioPluginFormat
  29308. */
  29309. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  29310. {
  29311. public:
  29312. AudioPluginFormatManager() throw();
  29313. /** Destructor. */
  29314. ~AudioPluginFormatManager() throw();
  29315. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  29316. /** Adds any formats that it knows about, e.g. VST.
  29317. */
  29318. void addDefaultFormats();
  29319. /** Returns the number of types of format that are available.
  29320. Use getFormat() to get one of them.
  29321. */
  29322. int getNumFormats() throw();
  29323. /** Returns one of the available formats.
  29324. @see getNumFormats
  29325. */
  29326. AudioPluginFormat* getFormat (const int index) throw();
  29327. /** Adds a format to the list.
  29328. The object passed in will be owned and deleted by the manager.
  29329. */
  29330. void addFormat (AudioPluginFormat* const format) throw();
  29331. /** Tries to load the type for this description, by trying all the formats
  29332. that this manager knows about.
  29333. The caller is responsible for deleting the object that is returned.
  29334. If it can't load the plugin, it returns 0 and leaves a message in the
  29335. errorMessage string.
  29336. */
  29337. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  29338. String& errorMessage) const;
  29339. /** Checks that the file or component for this plugin actually still exists.
  29340. (This won't try to load the plugin)
  29341. */
  29342. bool doesPluginStillExist (const PluginDescription& description) const;
  29343. juce_UseDebuggingNewOperator
  29344. private:
  29345. OwnedArray <AudioPluginFormat> formats;
  29346. AudioPluginFormatManager (const AudioPluginFormatManager&);
  29347. AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  29348. };
  29349. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29350. /*** End of inlined file: juce_AudioPluginFormatManager.h ***/
  29351. #endif
  29352. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  29353. #endif
  29354. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29355. /*** Start of inlined file: juce_KnownPluginList.h ***/
  29356. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29357. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29358. /**
  29359. Manages a list of plugin types.
  29360. This can be easily edited, saved and loaded, and used to create instances of
  29361. the plugin types in it.
  29362. @see PluginListComponent
  29363. */
  29364. class JUCE_API KnownPluginList : public ChangeBroadcaster
  29365. {
  29366. public:
  29367. /** Creates an empty list.
  29368. */
  29369. KnownPluginList();
  29370. /** Destructor. */
  29371. ~KnownPluginList();
  29372. /** Clears the list. */
  29373. void clear();
  29374. /** Returns the number of types currently in the list.
  29375. @see getType
  29376. */
  29377. int getNumTypes() const throw() { return types.size(); }
  29378. /** Returns one of the types.
  29379. @see getNumTypes
  29380. */
  29381. PluginDescription* getType (int index) const throw() { return types [index]; }
  29382. /** Looks for a type in the list which comes from this file.
  29383. */
  29384. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const throw();
  29385. /** Looks for a type in the list which matches a plugin type ID.
  29386. The identifierString parameter must have been created by
  29387. PluginDescription::createIdentifierString().
  29388. */
  29389. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  29390. /** Adds a type manually from its description. */
  29391. bool addType (const PluginDescription& type);
  29392. /** Removes a type. */
  29393. void removeType (int index) throw();
  29394. /** Looks for all types that can be loaded from a given file, and adds them
  29395. to the list.
  29396. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  29397. re-tested if it's not already in the list, or if the file's modification
  29398. time has changed since the list was created. If dontRescanIfAlreadyInList is
  29399. false, the file will always be reloaded and tested.
  29400. Returns true if any new types were added, and all the types found in this
  29401. file (even if it was already known and hasn't been re-scanned) get returned
  29402. in the array.
  29403. */
  29404. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  29405. bool dontRescanIfAlreadyInList,
  29406. OwnedArray <PluginDescription>& typesFound,
  29407. AudioPluginFormat& formatToUse);
  29408. /** Returns true if the specified file is already known about and if it
  29409. hasn't been modified since our entry was created.
  29410. */
  29411. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const throw();
  29412. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  29413. If any types are found in the files, their descriptions are returned in the array.
  29414. */
  29415. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  29416. OwnedArray <PluginDescription>& typesFound);
  29417. /** Sort methods used to change the order of the plugins in the list.
  29418. */
  29419. enum SortMethod
  29420. {
  29421. defaultOrder = 0,
  29422. sortAlphabetically,
  29423. sortByCategory,
  29424. sortByManufacturer,
  29425. sortByFileSystemLocation
  29426. };
  29427. /** Adds all the plugin types to a popup menu so that the user can select one.
  29428. Depending on the sort method, it may add sub-menus for categories,
  29429. manufacturers, etc.
  29430. Use getIndexChosenByMenu() to find out the type that was chosen.
  29431. */
  29432. void addToMenu (PopupMenu& menu,
  29433. const SortMethod sortMethod) const;
  29434. /** Converts a menu item index that has been chosen into its index in this list.
  29435. Returns -1 if it's not an ID that was used.
  29436. @see addToMenu
  29437. */
  29438. int getIndexChosenByMenu (int menuResultCode) const;
  29439. /** Sorts the list. */
  29440. void sort (const SortMethod method);
  29441. /** Creates some XML that can be used to store the state of this list.
  29442. */
  29443. XmlElement* createXml() const;
  29444. /** Recreates the state of this list from its stored XML format.
  29445. */
  29446. void recreateFromXml (const XmlElement& xml);
  29447. juce_UseDebuggingNewOperator
  29448. private:
  29449. OwnedArray <PluginDescription> types;
  29450. KnownPluginList (const KnownPluginList&);
  29451. KnownPluginList& operator= (const KnownPluginList&);
  29452. };
  29453. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29454. /*** End of inlined file: juce_KnownPluginList.h ***/
  29455. #endif
  29456. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  29457. #endif
  29458. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29459. /*** Start of inlined file: juce_PluginDirectoryScanner.h ***/
  29460. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29461. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29462. /**
  29463. Scans a directory for plugins, and adds them to a KnownPluginList.
  29464. To use one of these, create it and call scanNextFile() repeatedly, until
  29465. it returns false.
  29466. */
  29467. class JUCE_API PluginDirectoryScanner
  29468. {
  29469. public:
  29470. /**
  29471. Creates a scanner.
  29472. @param listToAddResultsTo this will get the new types added to it.
  29473. @param formatToLookFor this is the type of format that you want to look for
  29474. @param directoriesToSearch the path to search
  29475. @param searchRecursively true to search recursively
  29476. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  29477. be used as a file to store the names of any plugins
  29478. that crash during initialisation. If there are
  29479. any plugins listed in it, then these will always
  29480. be scanned after all other possible files have
  29481. been tried - in this way, even if there's a few
  29482. dodgy plugins in your path, then a couple of rescans
  29483. will still manage to find all the proper plugins.
  29484. It's probably best to choose a file in the user's
  29485. application data directory (alongside your app's
  29486. settings file) for this. The file format it uses
  29487. is just a list of filenames of the modules that
  29488. failed.
  29489. */
  29490. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  29491. AudioPluginFormat& formatToLookFor,
  29492. FileSearchPath directoriesToSearch,
  29493. bool searchRecursively,
  29494. const File& deadMansPedalFile);
  29495. /** Destructor. */
  29496. ~PluginDirectoryScanner();
  29497. /** Tries the next likely-looking file.
  29498. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  29499. re-tested if it's not already in the list, or if the file's modification
  29500. time has changed since the list was created. If dontRescanIfAlreadyInList is
  29501. false, the file will always be reloaded and tested.
  29502. Returns false when there are no more files to try.
  29503. */
  29504. bool scanNextFile (bool dontRescanIfAlreadyInList);
  29505. /** Returns the description of the plugin that will be scanned during the next
  29506. call to scanNextFile().
  29507. This is handy if you want to show the user which file is currently getting
  29508. scanned.
  29509. */
  29510. const String getNextPluginFileThatWillBeScanned() const throw();
  29511. /** Returns the estimated progress, between 0 and 1.
  29512. */
  29513. float getProgress() const { return progress; }
  29514. /** This returns a list of all the filenames of things that looked like being
  29515. a plugin file, but which failed to open for some reason.
  29516. */
  29517. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  29518. juce_UseDebuggingNewOperator
  29519. private:
  29520. KnownPluginList& list;
  29521. AudioPluginFormat& format;
  29522. StringArray filesOrIdentifiersToScan;
  29523. File deadMansPedalFile;
  29524. StringArray failedFiles;
  29525. int nextIndex;
  29526. float progress;
  29527. const StringArray getDeadMansPedalFile() throw();
  29528. void setDeadMansPedalFile (const StringArray& newContents) throw();
  29529. PluginDirectoryScanner (const PluginDirectoryScanner&);
  29530. PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  29531. };
  29532. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29533. /*** End of inlined file: juce_PluginDirectoryScanner.h ***/
  29534. #endif
  29535. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29536. /*** Start of inlined file: juce_PluginListComponent.h ***/
  29537. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29538. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29539. /*** Start of inlined file: juce_ListBox.h ***/
  29540. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  29541. #define __JUCE_LISTBOX_JUCEHEADER__
  29542. class ListViewport;
  29543. /**
  29544. A subclass of this is used to drive a ListBox.
  29545. @see ListBox
  29546. */
  29547. class JUCE_API ListBoxModel
  29548. {
  29549. public:
  29550. /** Destructor. */
  29551. virtual ~ListBoxModel() {}
  29552. /** This has to return the number of items in the list.
  29553. @see ListBox::getNumRows()
  29554. */
  29555. virtual int getNumRows() = 0;
  29556. /** This method must be implemented to draw a row of the list.
  29557. */
  29558. virtual void paintListBoxItem (int rowNumber,
  29559. Graphics& g,
  29560. int width, int height,
  29561. bool rowIsSelected) = 0;
  29562. /** This is used to create or update a custom component to go in a row of the list.
  29563. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  29564. and handle mouse clicks with listBoxItemClicked().
  29565. This method will be called whenever a custom component might need to be updated - e.g.
  29566. when the table is changed, or TableListBox::updateContent() is called.
  29567. If you don't need a custom component for the specified row, then return 0.
  29568. If you do want a custom component, and the existingComponentToUpdate is null, then
  29569. this method must create a suitable new component and return it.
  29570. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  29571. by this method. In this case, the method must either update it to make sure it's correctly representing
  29572. the given row (which may be different from the one that the component was created for), or it can
  29573. delete this component and return a new one.
  29574. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  29575. */
  29576. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  29577. Component* existingComponentToUpdate);
  29578. /** This can be overridden to react to the user clicking on a row.
  29579. @see listBoxItemDoubleClicked
  29580. */
  29581. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  29582. /** This can be overridden to react to the user double-clicking on a row.
  29583. @see listBoxItemClicked
  29584. */
  29585. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  29586. /** This can be overridden to react to the user double-clicking on a part of the list where
  29587. there are no rows.
  29588. @see listBoxItemClicked
  29589. */
  29590. virtual void backgroundClicked();
  29591. /** Override this to be informed when rows are selected or deselected.
  29592. This will be called whenever a row is selected or deselected. If a range of
  29593. rows is selected all at once, this will just be called once for that event.
  29594. @param lastRowSelected the last row that the user selected. If no
  29595. rows are currently selected, this may be -1.
  29596. */
  29597. virtual void selectedRowsChanged (int lastRowSelected);
  29598. /** Override this to be informed when the delete key is pressed.
  29599. If no rows are selected when they press the key, this won't be called.
  29600. @param lastRowSelected the last row that had been selected when they pressed the
  29601. key - if there are multiple selections, this might not be
  29602. very useful
  29603. */
  29604. virtual void deleteKeyPressed (int lastRowSelected);
  29605. /** Override this to be informed when the return key is pressed.
  29606. If no rows are selected when they press the key, this won't be called.
  29607. @param lastRowSelected the last row that had been selected when they pressed the
  29608. key - if there are multiple selections, this might not be
  29609. very useful
  29610. */
  29611. virtual void returnKeyPressed (int lastRowSelected);
  29612. /** Override this to be informed when the list is scrolled.
  29613. This might be caused by the user moving the scrollbar, or by programmatic changes
  29614. to the list position.
  29615. */
  29616. virtual void listWasScrolled();
  29617. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  29618. If this returns a non-empty name then when the user drags a row, the listbox will
  29619. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  29620. a drag-and-drop operation, using this string as the source description, with the listbox
  29621. itself as the source component.
  29622. @see DragAndDropContainer::startDragging
  29623. */
  29624. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  29625. /** You can override this to provide tool tips for specific rows.
  29626. @see TooltipClient
  29627. */
  29628. virtual const String getTooltipForRow (int row);
  29629. };
  29630. /**
  29631. A list of items that can be scrolled vertically.
  29632. To create a list, you'll need to create a subclass of ListBoxModel. This can
  29633. either paint each row of the list and respond to events via callbacks, or for
  29634. more specialised tasks, it can supply a custom component to fill each row.
  29635. @see ComboBox, TableListBox
  29636. */
  29637. class JUCE_API ListBox : public Component,
  29638. public SettableTooltipClient
  29639. {
  29640. public:
  29641. /** Creates a ListBox.
  29642. The model pointer passed-in can be null, in which case you can set it later
  29643. with setModel().
  29644. */
  29645. ListBox (const String& componentName,
  29646. ListBoxModel* model);
  29647. /** Destructor. */
  29648. ~ListBox();
  29649. /** Changes the current data model to display. */
  29650. void setModel (ListBoxModel* newModel);
  29651. /** Returns the current list model. */
  29652. ListBoxModel* getModel() const throw() { return model; }
  29653. /** Causes the list to refresh its content.
  29654. Call this when the number of rows in the list changes, or if you want it
  29655. to call refreshComponentForRow() on all the row components.
  29656. Be careful not to call it from a different thread, though, as it's not
  29657. thread-safe.
  29658. */
  29659. void updateContent();
  29660. /** Turns on multiple-selection of rows.
  29661. By default this is disabled.
  29662. When your row component gets clicked you'll need to call the
  29663. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  29664. clicked and to get it to do the appropriate selection based on whether
  29665. the ctrl/shift keys are held down.
  29666. */
  29667. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  29668. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  29669. This function is here primarily for the ComboBox class to use, but might be
  29670. useful for some other purpose too.
  29671. */
  29672. void setMouseMoveSelectsRows (bool shouldSelect);
  29673. /** Selects a row.
  29674. If the row is already selected, this won't do anything.
  29675. @param rowNumber the row to select
  29676. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  29677. the selected row is off-screen, it'll scroll to make
  29678. sure that row is on-screen
  29679. @param deselectOthersFirst if true and there are multiple selections, these will
  29680. first be deselected before this item is selected
  29681. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  29682. deselectAllRows, selectRangeOfRows
  29683. */
  29684. void selectRow (int rowNumber,
  29685. bool dontScrollToShowThisRow = false,
  29686. bool deselectOthersFirst = true);
  29687. /** Selects a set of rows.
  29688. This will add these rows to the current selection, so you might need to
  29689. clear the current selection first with deselectAllRows()
  29690. @param firstRow the first row to select (inclusive)
  29691. @param lastRow the last row to select (inclusive)
  29692. */
  29693. void selectRangeOfRows (int firstRow,
  29694. int lastRow);
  29695. /** Deselects a row.
  29696. If it's not currently selected, this will do nothing.
  29697. @see selectRow, deselectAllRows
  29698. */
  29699. void deselectRow (int rowNumber);
  29700. /** Deselects any currently selected rows.
  29701. @see deselectRow
  29702. */
  29703. void deselectAllRows();
  29704. /** Selects or deselects a row.
  29705. If the row's currently selected, this deselects it, and vice-versa.
  29706. */
  29707. void flipRowSelection (int rowNumber);
  29708. /** Returns a sparse set indicating the rows that are currently selected.
  29709. @see setSelectedRows
  29710. */
  29711. const SparseSet<int> getSelectedRows() const;
  29712. /** Sets the rows that should be selected, based on an explicit set of ranges.
  29713. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  29714. method will be called. If it's false, no notification will be sent to the model.
  29715. @see getSelectedRows
  29716. */
  29717. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  29718. bool sendNotificationEventToModel = true);
  29719. /** Checks whether a row is selected.
  29720. */
  29721. bool isRowSelected (int rowNumber) const;
  29722. /** Returns the number of rows that are currently selected.
  29723. @see getSelectedRow, isRowSelected, getLastRowSelected
  29724. */
  29725. int getNumSelectedRows() const;
  29726. /** Returns the row number of a selected row.
  29727. This will return the row number of the Nth selected row. The row numbers returned will
  29728. be sorted in order from low to high.
  29729. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  29730. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  29731. selected
  29732. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  29733. */
  29734. int getSelectedRow (int index = 0) const;
  29735. /** Returns the last row that the user selected.
  29736. This isn't the same as the highest row number that is currently selected - if the user
  29737. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  29738. If nothing is selected, it will return -1.
  29739. */
  29740. int getLastRowSelected() const;
  29741. /** Multiply-selects rows based on the modifier keys.
  29742. If no modifier keys are down, this will select the given row and
  29743. deselect any others.
  29744. If the ctrl (or command on the Mac) key is down, it'll flip the
  29745. state of the selected row.
  29746. If the shift key is down, it'll select up to the given row from the
  29747. last row selected.
  29748. @see selectRow
  29749. */
  29750. void selectRowsBasedOnModifierKeys (int rowThatWasClickedOn,
  29751. const ModifierKeys& modifiers);
  29752. /** Scrolls the list to a particular position.
  29753. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  29754. 1.0 scrolls to the bottom.
  29755. If the total number of rows all fit onto the screen at once, then this
  29756. method won't do anything.
  29757. @see getVerticalPosition
  29758. */
  29759. void setVerticalPosition (double newProportion);
  29760. /** Returns the current vertical position as a proportion of the total.
  29761. This can be used in conjunction with setVerticalPosition() to save and restore
  29762. the list's position. It returns a value in the range 0 to 1.
  29763. @see setVerticalPosition
  29764. */
  29765. double getVerticalPosition() const;
  29766. /** Scrolls if necessary to make sure that a particular row is visible.
  29767. */
  29768. void scrollToEnsureRowIsOnscreen (int row);
  29769. /** Returns a pointer to the scrollbar.
  29770. (Unlikely to be useful for most people).
  29771. */
  29772. ScrollBar* getVerticalScrollBar() const throw();
  29773. /** Returns a pointer to the scrollbar.
  29774. (Unlikely to be useful for most people).
  29775. */
  29776. ScrollBar* getHorizontalScrollBar() const throw();
  29777. /** Finds the row index that contains a given x,y position.
  29778. The position is relative to the ListBox's top-left.
  29779. If no row exists at this position, the method will return -1.
  29780. @see getComponentForRowNumber
  29781. */
  29782. int getRowContainingPosition (int x, int y) const throw();
  29783. /** Finds a row index that would be the most suitable place to insert a new
  29784. item for a given position.
  29785. This is useful when the user is e.g. dragging and dropping onto the listbox,
  29786. because it lets you easily choose the best position to insert the item that
  29787. they drop, based on where they drop it.
  29788. If the position is out of range, this will return -1. If the position is
  29789. beyond the end of the list, it will return getNumRows() to indicate the end
  29790. of the list.
  29791. @see getComponentForRowNumber
  29792. */
  29793. int getInsertionIndexForPosition (int x, int y) const throw();
  29794. /** Returns the position of one of the rows, relative to the top-left of
  29795. the listbox.
  29796. This may be off-screen, and the range of the row number that is passed-in is
  29797. not checked to see if it's a valid row.
  29798. */
  29799. const Rectangle<int> getRowPosition (int rowNumber,
  29800. bool relativeToComponentTopLeft) const throw();
  29801. /** Finds the row component for a given row in the list.
  29802. The component returned will have been created using createRowComponent().
  29803. If the component for this row is off-screen or if the row is out-of-range,
  29804. this will return 0.
  29805. @see getRowContainingPosition
  29806. */
  29807. Component* getComponentForRowNumber (int rowNumber) const throw();
  29808. /** Returns the row number that the given component represents.
  29809. If the component isn't one of the list's rows, this will return -1.
  29810. */
  29811. int getRowNumberOfComponent (Component* rowComponent) const throw();
  29812. /** Returns the width of a row (which may be less than the width of this component
  29813. if there's a scrollbar).
  29814. */
  29815. int getVisibleRowWidth() const throw();
  29816. /** Sets the height of each row in the list.
  29817. The default height is 22 pixels.
  29818. @see getRowHeight
  29819. */
  29820. void setRowHeight (int newHeight);
  29821. /** Returns the height of a row in the list.
  29822. @see setRowHeight
  29823. */
  29824. int getRowHeight() const throw() { return rowHeight; }
  29825. /** Returns the number of rows actually visible.
  29826. This is the number of whole rows which will fit on-screen, so the value might
  29827. be more than the actual number of rows in the list.
  29828. */
  29829. int getNumRowsOnScreen() const throw();
  29830. /** A set of colour IDs to use to change the colour of various aspects of the label.
  29831. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  29832. methods.
  29833. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  29834. */
  29835. enum ColourIds
  29836. {
  29837. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  29838. Make this transparent if you don't want the background to be filled. */
  29839. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  29840. Make this transparent to not have an outline. */
  29841. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  29842. };
  29843. /** Sets the thickness of a border that will be drawn around the box.
  29844. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  29845. @see outlineColourId
  29846. */
  29847. void setOutlineThickness (int outlineThickness);
  29848. /** Returns the thickness of outline that will be drawn around the listbox.
  29849. @see setOutlineColour
  29850. */
  29851. int getOutlineThickness() const throw() { return outlineThickness; }
  29852. /** Sets a component that the list should use as a header.
  29853. This will position the given component at the top of the list, maintaining the
  29854. height of the component passed-in, but rescaling it horizontally to match the
  29855. width of the items in the listbox.
  29856. The component will be deleted when setHeaderComponent() is called with a
  29857. different component, or when the listbox is deleted.
  29858. */
  29859. void setHeaderComponent (Component* newHeaderComponent);
  29860. /** Changes the width of the rows in the list.
  29861. This can be used to make the list's row components wider than the list itself - the
  29862. width of the rows will be either the width of the list or this value, whichever is
  29863. greater, and if the rows become wider than the list, a horizontal scrollbar will
  29864. appear.
  29865. The default value for this is 0, which means that the rows will always
  29866. be the same width as the list.
  29867. */
  29868. void setMinimumContentWidth (int newMinimumWidth);
  29869. /** Returns the space currently available for the row items, taking into account
  29870. borders, scrollbars, etc.
  29871. */
  29872. int getVisibleContentWidth() const throw();
  29873. /** Repaints one of the rows.
  29874. This is a lightweight alternative to calling updateContent, and just causes a
  29875. repaint of the row's area.
  29876. */
  29877. void repaintRow (int rowNumber) throw();
  29878. /** This fairly obscure method creates an image that just shows the currently
  29879. selected row components.
  29880. It's a handy method for doing drag-and-drop, as it can be passed to the
  29881. DragAndDropContainer for use as the drag image.
  29882. Note that it will make the row components temporarily invisible, so if you're
  29883. using custom components this could affect them if they're sensitive to that
  29884. sort of thing.
  29885. @see Component::createComponentSnapshot
  29886. */
  29887. const Image createSnapshotOfSelectedRows (int& x, int& y);
  29888. /** Returns the viewport that this ListBox uses.
  29889. You may need to use this to change parameters such as whether scrollbars
  29890. are shown, etc.
  29891. */
  29892. Viewport* getViewport() const throw();
  29893. /** @internal */
  29894. bool keyPressed (const KeyPress& key);
  29895. /** @internal */
  29896. bool keyStateChanged (bool isKeyDown);
  29897. /** @internal */
  29898. void paint (Graphics& g);
  29899. /** @internal */
  29900. void paintOverChildren (Graphics& g);
  29901. /** @internal */
  29902. void resized();
  29903. /** @internal */
  29904. void visibilityChanged();
  29905. /** @internal */
  29906. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  29907. /** @internal */
  29908. void mouseMove (const MouseEvent&);
  29909. /** @internal */
  29910. void mouseExit (const MouseEvent&);
  29911. /** @internal */
  29912. void mouseUp (const MouseEvent&);
  29913. /** @internal */
  29914. void colourChanged();
  29915. /** @internal */
  29916. void startDragAndDrop (const MouseEvent& e, const String& dragDescription);
  29917. juce_UseDebuggingNewOperator
  29918. private:
  29919. friend class ListViewport;
  29920. friend class TableListBox;
  29921. ListBoxModel* model;
  29922. ListViewport* viewport;
  29923. Component* headerComponent;
  29924. int totalItems, rowHeight, minimumRowWidth;
  29925. int outlineThickness;
  29926. int lastRowSelected;
  29927. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  29928. SparseSet <int> selected;
  29929. void selectRowInternal (int rowNumber,
  29930. bool dontScrollToShowThisRow,
  29931. bool deselectOthersFirst,
  29932. bool isMouseClick);
  29933. ListBox (const ListBox&);
  29934. ListBox& operator= (const ListBox&);
  29935. };
  29936. #endif // __JUCE_LISTBOX_JUCEHEADER__
  29937. /*** End of inlined file: juce_ListBox.h ***/
  29938. /*** Start of inlined file: juce_TextButton.h ***/
  29939. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  29940. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  29941. /**
  29942. A button that uses the standard lozenge-shaped background with a line of
  29943. text on it.
  29944. @see Button, DrawableButton
  29945. */
  29946. class JUCE_API TextButton : public Button
  29947. {
  29948. public:
  29949. /** Creates a TextButton.
  29950. @param buttonName the text to put in the button (the component's name is also
  29951. initially set to this string, but these can be changed later
  29952. using the setName() and setButtonText() methods)
  29953. @param toolTip an optional string to use as a toolip
  29954. @see Button
  29955. */
  29956. TextButton (const String& buttonName = String::empty,
  29957. const String& toolTip = String::empty);
  29958. /** Destructor. */
  29959. ~TextButton();
  29960. /** A set of colour IDs to use to change the colour of various aspects of the button.
  29961. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  29962. methods.
  29963. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  29964. */
  29965. enum ColourIds
  29966. {
  29967. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  29968. 'off'). The look-and-feel class might re-interpret this to add
  29969. effects, etc. */
  29970. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  29971. 'on'). The look-and-feel class might re-interpret this to add
  29972. effects, etc. */
  29973. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  29974. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  29975. };
  29976. /** Resizes the button to fit neatly around its current text.
  29977. If newHeight is >= 0, the button's height will be changed to this
  29978. value. If it's less than zero, its height will be unaffected.
  29979. */
  29980. void changeWidthToFitText (int newHeight = -1);
  29981. /** This can be overridden to use different fonts than the default one.
  29982. Note that you'll need to set the font's size appropriately, too.
  29983. */
  29984. virtual const Font getFont();
  29985. juce_UseDebuggingNewOperator
  29986. protected:
  29987. /** @internal */
  29988. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  29989. /** @internal */
  29990. void colourChanged();
  29991. private:
  29992. TextButton (const TextButton&);
  29993. TextButton& operator= (const TextButton&);
  29994. };
  29995. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  29996. /*** End of inlined file: juce_TextButton.h ***/
  29997. /**
  29998. A component displaying a list of plugins, with options to scan for them,
  29999. add, remove and sort them.
  30000. */
  30001. class JUCE_API PluginListComponent : public Component,
  30002. public ListBoxModel,
  30003. public ChangeListener,
  30004. public ButtonListener,
  30005. public Timer
  30006. {
  30007. public:
  30008. /**
  30009. Creates the list component.
  30010. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  30011. The properties file, if supplied, is used to store the user's last search paths.
  30012. */
  30013. PluginListComponent (KnownPluginList& listToRepresent,
  30014. const File& deadMansPedalFile,
  30015. PropertiesFile* propertiesToUse);
  30016. /** Destructor. */
  30017. ~PluginListComponent();
  30018. /** @internal */
  30019. void resized();
  30020. /** @internal */
  30021. bool isInterestedInFileDrag (const StringArray& files);
  30022. /** @internal */
  30023. void filesDropped (const StringArray& files, int, int);
  30024. /** @internal */
  30025. int getNumRows();
  30026. /** @internal */
  30027. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  30028. /** @internal */
  30029. void deleteKeyPressed (int lastRowSelected);
  30030. /** @internal */
  30031. void buttonClicked (Button* b);
  30032. /** @internal */
  30033. void changeListenerCallback (void*);
  30034. /** @internal */
  30035. void timerCallback();
  30036. juce_UseDebuggingNewOperator
  30037. private:
  30038. KnownPluginList& list;
  30039. File deadMansPedalFile;
  30040. ListBox* listBox;
  30041. TextButton* optionsButton;
  30042. PropertiesFile* propertiesToUse;
  30043. int typeToScan;
  30044. void scanFor (AudioPluginFormat* format);
  30045. PluginListComponent (const PluginListComponent&);
  30046. PluginListComponent& operator= (const PluginListComponent&);
  30047. };
  30048. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  30049. /*** End of inlined file: juce_PluginListComponent.h ***/
  30050. #endif
  30051. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  30052. #endif
  30053. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  30054. #endif
  30055. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  30056. #endif
  30057. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30058. /*** Start of inlined file: juce_AudioProcessorGraph.h ***/
  30059. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30060. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30061. /**
  30062. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  30063. Use one of these objects if you want to wire-up a set of AudioProcessors
  30064. and play back the result.
  30065. Processors can be added to the graph as "nodes" using addNode(), and once
  30066. added, you can connect any of their input or output channels to other
  30067. nodes using addConnection().
  30068. To play back a graph through an audio device, you might want to use an
  30069. AudioProcessorPlayer object.
  30070. */
  30071. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  30072. public AsyncUpdater
  30073. {
  30074. public:
  30075. /** Creates an empty graph.
  30076. */
  30077. AudioProcessorGraph();
  30078. /** Destructor.
  30079. Any processor objects that have been added to the graph will also be deleted.
  30080. */
  30081. ~AudioProcessorGraph();
  30082. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  30083. To create a node, call AudioProcessorGraph::addNode().
  30084. */
  30085. class JUCE_API Node : public ReferenceCountedObject
  30086. {
  30087. public:
  30088. /** Destructor.
  30089. */
  30090. ~Node();
  30091. /** The ID number assigned to this node.
  30092. This is assigned by the graph that owns it, and can't be changed.
  30093. */
  30094. const uint32 id;
  30095. /** The actual processor object that this node represents.
  30096. */
  30097. AudioProcessor* const processor;
  30098. /** A set of user-definable properties that are associated with this node.
  30099. This can be used to attach values to the node for whatever purpose seems
  30100. useful. For example, you might store an x and y position if your application
  30101. is displaying the nodes on-screen.
  30102. */
  30103. NamedValueSet properties;
  30104. /** A convenient typedef for referring to a pointer to a node object.
  30105. */
  30106. typedef ReferenceCountedObjectPtr <Node> Ptr;
  30107. juce_UseDebuggingNewOperator
  30108. private:
  30109. friend class AudioProcessorGraph;
  30110. bool isPrepared;
  30111. Node (uint32 id, AudioProcessor* processor);
  30112. void prepare (double sampleRate, int blockSize, AudioProcessorGraph* graph);
  30113. void unprepare();
  30114. Node (const Node&);
  30115. Node& operator= (const Node&);
  30116. };
  30117. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  30118. To create a connection, use AudioProcessorGraph::addConnection().
  30119. */
  30120. struct JUCE_API Connection
  30121. {
  30122. public:
  30123. /** The ID number of the node which is the input source for this connection.
  30124. @see AudioProcessorGraph::getNodeForId
  30125. */
  30126. uint32 sourceNodeId;
  30127. /** The index of the output channel of the source node from which this
  30128. connection takes its data.
  30129. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  30130. it is referring to the source node's midi output. Otherwise, it is the zero-based
  30131. index of an audio output channel in the source node.
  30132. */
  30133. int sourceChannelIndex;
  30134. /** The ID number of the node which is the destination for this connection.
  30135. @see AudioProcessorGraph::getNodeForId
  30136. */
  30137. uint32 destNodeId;
  30138. /** The index of the input channel of the destination node to which this
  30139. connection delivers its data.
  30140. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  30141. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  30142. index of an audio input channel in the destination node.
  30143. */
  30144. int destChannelIndex;
  30145. juce_UseDebuggingNewOperator
  30146. private:
  30147. };
  30148. /** Deletes all nodes and connections from this graph.
  30149. Any processor objects in the graph will be deleted.
  30150. */
  30151. void clear();
  30152. /** Returns the number of nodes in the graph. */
  30153. int getNumNodes() const { return nodes.size(); }
  30154. /** Returns a pointer to one of the nodes in the graph.
  30155. This will return 0 if the index is out of range.
  30156. @see getNodeForId
  30157. */
  30158. Node* getNode (const int index) const { return nodes [index]; }
  30159. /** Searches the graph for a node with the given ID number and returns it.
  30160. If no such node was found, this returns 0.
  30161. @see getNode
  30162. */
  30163. Node* getNodeForId (const uint32 nodeId) const;
  30164. /** Adds a node to the graph.
  30165. This creates a new node in the graph, for the specified processor. Once you have
  30166. added a processor to the graph, the graph owns it and will delete it later when
  30167. it is no longer needed.
  30168. The optional nodeId parameter lets you specify an ID to use for the node, but
  30169. if the value is already in use, this new node will overwrite the old one.
  30170. If this succeeds, it returns a pointer to the newly-created node.
  30171. */
  30172. Node* addNode (AudioProcessor* newProcessor, uint32 nodeId = 0);
  30173. /** Deletes a node within the graph which has the specified ID.
  30174. This will also delete any connections that are attached to this node.
  30175. */
  30176. bool removeNode (uint32 nodeId);
  30177. /** Returns the number of connections in the graph. */
  30178. int getNumConnections() const { return connections.size(); }
  30179. /** Returns a pointer to one of the connections in the graph. */
  30180. const Connection* getConnection (int index) const { return connections [index]; }
  30181. /** Searches for a connection between some specified channels.
  30182. If no such connection is found, this returns 0.
  30183. */
  30184. const Connection* getConnectionBetween (uint32 sourceNodeId,
  30185. int sourceChannelIndex,
  30186. uint32 destNodeId,
  30187. int destChannelIndex) const;
  30188. /** Returns true if there is a connection between any of the channels of
  30189. two specified nodes.
  30190. */
  30191. bool isConnected (uint32 possibleSourceNodeId,
  30192. uint32 possibleDestNodeId) const;
  30193. /** Returns true if it would be legal to connect the specified points.
  30194. */
  30195. bool canConnect (uint32 sourceNodeId, int sourceChannelIndex,
  30196. uint32 destNodeId, int destChannelIndex) const;
  30197. /** Attempts to connect two specified channels of two nodes.
  30198. If this isn't allowed (e.g. because you're trying to connect a midi channel
  30199. to an audio one or other such nonsense), then it'll return false.
  30200. */
  30201. bool addConnection (uint32 sourceNodeId, int sourceChannelIndex,
  30202. uint32 destNodeId, int destChannelIndex);
  30203. /** Deletes the connection with the specified index.
  30204. Returns true if a connection was actually deleted.
  30205. */
  30206. void removeConnection (int index);
  30207. /** Deletes any connection between two specified points.
  30208. Returns true if a connection was actually deleted.
  30209. */
  30210. bool removeConnection (uint32 sourceNodeId, int sourceChannelIndex,
  30211. uint32 destNodeId, int destChannelIndex);
  30212. /** Removes all connections from the specified node.
  30213. */
  30214. bool disconnectNode (uint32 nodeId);
  30215. /** Performs a sanity checks of all the connections.
  30216. This might be useful if some of the processors are doing things like changing
  30217. their channel counts, which could render some connections obsolete.
  30218. */
  30219. bool removeIllegalConnections();
  30220. /** A special number that represents the midi channel of a node.
  30221. This is used as a channel index value if you want to refer to the midi input
  30222. or output instead of an audio channel.
  30223. */
  30224. static const int midiChannelIndex;
  30225. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  30226. in order to use the audio that comes into and out of the graph itself.
  30227. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  30228. node in the graph which delivers the audio that is coming into the parent
  30229. graph. This allows you to stream the data to other nodes and process the
  30230. incoming audio.
  30231. Likewise, one of these in "output" mode can be sent data which it will add to
  30232. the sum of data being sent to the graph's output.
  30233. @see AudioProcessorGraph
  30234. */
  30235. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  30236. {
  30237. public:
  30238. /** Specifies the mode in which this processor will operate.
  30239. */
  30240. enum IODeviceType
  30241. {
  30242. audioInputNode, /**< In this mode, the processor has output channels
  30243. representing all the audio input channels that are
  30244. coming into its parent audio graph. */
  30245. audioOutputNode, /**< In this mode, the processor has input channels
  30246. representing all the audio output channels that are
  30247. going out of its parent audio graph. */
  30248. midiInputNode, /**< In this mode, the processor has a midi output which
  30249. delivers the same midi data that is arriving at its
  30250. parent graph. */
  30251. midiOutputNode /**< In this mode, the processor has a midi input and
  30252. any data sent to it will be passed out of the parent
  30253. graph. */
  30254. };
  30255. /** Returns the mode of this processor. */
  30256. IODeviceType getType() const { return type; }
  30257. /** Returns the parent graph to which this processor belongs, or 0 if it
  30258. hasn't yet been added to one. */
  30259. AudioProcessorGraph* getParentGraph() const { return graph; }
  30260. /** True if this is an audio or midi input. */
  30261. bool isInput() const;
  30262. /** True if this is an audio or midi output. */
  30263. bool isOutput() const;
  30264. AudioGraphIOProcessor (const IODeviceType type);
  30265. ~AudioGraphIOProcessor();
  30266. const String getName() const;
  30267. void fillInPluginDescription (PluginDescription& d) const;
  30268. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  30269. void releaseResources();
  30270. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  30271. const String getInputChannelName (const int channelIndex) const;
  30272. const String getOutputChannelName (const int channelIndex) const;
  30273. bool isInputChannelStereoPair (int index) const;
  30274. bool isOutputChannelStereoPair (int index) const;
  30275. bool acceptsMidi() const;
  30276. bool producesMidi() const;
  30277. AudioProcessorEditor* createEditor();
  30278. int getNumParameters();
  30279. const String getParameterName (int);
  30280. float getParameter (int);
  30281. const String getParameterText (int);
  30282. void setParameter (int, float);
  30283. int getNumPrograms();
  30284. int getCurrentProgram();
  30285. void setCurrentProgram (int);
  30286. const String getProgramName (int);
  30287. void changeProgramName (int, const String&);
  30288. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  30289. void setStateInformation (const void* data, int sizeInBytes);
  30290. /** @internal */
  30291. void setParentGraph (AudioProcessorGraph* graph);
  30292. juce_UseDebuggingNewOperator
  30293. private:
  30294. const IODeviceType type;
  30295. AudioProcessorGraph* graph;
  30296. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  30297. AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  30298. };
  30299. // AudioProcessor methods:
  30300. const String getName() const;
  30301. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  30302. void releaseResources();
  30303. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  30304. const String getInputChannelName (const int channelIndex) const;
  30305. const String getOutputChannelName (const int channelIndex) const;
  30306. bool isInputChannelStereoPair (int index) const;
  30307. bool isOutputChannelStereoPair (int index) const;
  30308. bool acceptsMidi() const;
  30309. bool producesMidi() const;
  30310. AudioProcessorEditor* createEditor() { return 0; }
  30311. int getNumParameters() { return 0; }
  30312. const String getParameterName (int) { return String::empty; }
  30313. float getParameter (int) { return 0; }
  30314. const String getParameterText (int) { return String::empty; }
  30315. void setParameter (int, float) { }
  30316. int getNumPrograms() { return 0; }
  30317. int getCurrentProgram() { return 0; }
  30318. void setCurrentProgram (int) { }
  30319. const String getProgramName (int) { return String::empty; }
  30320. void changeProgramName (int, const String&) { }
  30321. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  30322. void setStateInformation (const void* data, int sizeInBytes);
  30323. /** @internal */
  30324. void handleAsyncUpdate();
  30325. juce_UseDebuggingNewOperator
  30326. private:
  30327. ReferenceCountedArray <Node> nodes;
  30328. OwnedArray <Connection> connections;
  30329. int lastNodeId;
  30330. AudioSampleBuffer renderingBuffers;
  30331. OwnedArray <MidiBuffer> midiBuffers;
  30332. CriticalSection renderLock;
  30333. Array<void*> renderingOps;
  30334. friend class AudioGraphIOProcessor;
  30335. AudioSampleBuffer* currentAudioInputBuffer;
  30336. AudioSampleBuffer currentAudioOutputBuffer;
  30337. MidiBuffer* currentMidiInputBuffer;
  30338. MidiBuffer currentMidiOutputBuffer;
  30339. void clearRenderingSequence();
  30340. void buildRenderingSequence();
  30341. bool isAnInputTo (uint32 possibleInputId, uint32 possibleDestinationId, int recursionCheck) const;
  30342. AudioProcessorGraph (const AudioProcessorGraph&);
  30343. AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  30344. };
  30345. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30346. /*** End of inlined file: juce_AudioProcessorGraph.h ***/
  30347. #endif
  30348. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  30349. #endif
  30350. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30351. /*** Start of inlined file: juce_AudioProcessorPlayer.h ***/
  30352. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30353. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30354. /**
  30355. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  30356. To use one of these, just make it the callback used by your AudioIODevice, and
  30357. give it a processor to use by calling setProcessor().
  30358. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  30359. input to send both streams through the processor.
  30360. @see AudioProcessor, AudioProcessorGraph
  30361. */
  30362. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  30363. public MidiInputCallback
  30364. {
  30365. public:
  30366. /**
  30367. */
  30368. AudioProcessorPlayer();
  30369. /** Destructor. */
  30370. virtual ~AudioProcessorPlayer();
  30371. /** Sets the processor that should be played.
  30372. The processor that is passed in will not be deleted or owned by this object.
  30373. To stop anything playing, pass in 0 to this method.
  30374. */
  30375. void setProcessor (AudioProcessor* const processorToPlay);
  30376. /** Returns the current audio processor that is being played.
  30377. */
  30378. AudioProcessor* getCurrentProcessor() const { return processor; }
  30379. /** Returns a midi message collector that you can pass midi messages to if you
  30380. want them to be injected into the midi stream that is being sent to the
  30381. processor.
  30382. */
  30383. MidiMessageCollector& getMidiMessageCollector() { return messageCollector; }
  30384. /** @internal */
  30385. void audioDeviceIOCallback (const float** inputChannelData,
  30386. int totalNumInputChannels,
  30387. float** outputChannelData,
  30388. int totalNumOutputChannels,
  30389. int numSamples);
  30390. /** @internal */
  30391. void audioDeviceAboutToStart (AudioIODevice* device);
  30392. /** @internal */
  30393. void audioDeviceStopped();
  30394. /** @internal */
  30395. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  30396. juce_UseDebuggingNewOperator
  30397. private:
  30398. AudioProcessor* processor;
  30399. CriticalSection lock;
  30400. double sampleRate;
  30401. int blockSize;
  30402. bool isPrepared;
  30403. int numInputChans, numOutputChans;
  30404. float* channels [128];
  30405. AudioSampleBuffer tempBuffer;
  30406. MidiBuffer incomingMidi;
  30407. MidiMessageCollector messageCollector;
  30408. AudioProcessorPlayer (const AudioProcessorPlayer&);
  30409. AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  30410. };
  30411. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30412. /*** End of inlined file: juce_AudioProcessorPlayer.h ***/
  30413. #endif
  30414. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30415. /*** Start of inlined file: juce_GenericAudioProcessorEditor.h ***/
  30416. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30417. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30418. /*** Start of inlined file: juce_PropertyPanel.h ***/
  30419. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  30420. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  30421. /*** Start of inlined file: juce_PropertyComponent.h ***/
  30422. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  30423. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  30424. class EditableProperty;
  30425. /**
  30426. A base class for a component that goes in a PropertyPanel and displays one of
  30427. an item's properties.
  30428. Subclasses of this are used to display a property in various forms, e.g. a
  30429. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  30430. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  30431. A subclass must implement the refresh() method which will be called to tell the
  30432. component to update itself, and is also responsible for calling this it when the
  30433. item that it refers to is changed.
  30434. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  30435. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  30436. */
  30437. class JUCE_API PropertyComponent : public Component,
  30438. public SettableTooltipClient
  30439. {
  30440. public:
  30441. /** Creates a PropertyComponent.
  30442. @param propertyName the name is stored as this component's name, and is
  30443. used as the name displayed next to this component in
  30444. a property panel
  30445. @param preferredHeight the height that the component should be given - some
  30446. items may need to be larger than a normal row height.
  30447. This value can also be set if a subclass changes the
  30448. preferredHeight member variable.
  30449. */
  30450. PropertyComponent (const String& propertyName,
  30451. int preferredHeight = 25);
  30452. /** Destructor. */
  30453. ~PropertyComponent();
  30454. /** Returns this item's preferred height.
  30455. This value is specified either in the constructor or by a subclass changing the
  30456. preferredHeight member variable.
  30457. */
  30458. int getPreferredHeight() const throw() { return preferredHeight; }
  30459. void setPreferredHeight (int newHeight) throw() { preferredHeight = newHeight; }
  30460. /** Updates the property component if the item it refers to has changed.
  30461. A subclass must implement this method, and other objects may call it to
  30462. force it to refresh itself.
  30463. The subclass should be economical in the amount of work is done, so for
  30464. example it should check whether it really needs to do a repaint rather than
  30465. just doing one every time this method is called, as it may be called when
  30466. the value being displayed hasn't actually changed.
  30467. */
  30468. virtual void refresh() = 0;
  30469. /** The default paint method fills the background and draws a label for the
  30470. item's name.
  30471. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  30472. */
  30473. void paint (Graphics& g);
  30474. /** The default resize method positions any child component to the right of this
  30475. one, based on the look and feel's default label size.
  30476. */
  30477. void resized();
  30478. /** By default, this just repaints the component. */
  30479. void enablementChanged();
  30480. juce_UseDebuggingNewOperator
  30481. protected:
  30482. /** Used by the PropertyPanel to determine how high this component needs to be.
  30483. A subclass can update this value in its constructor but shouldn't alter it later
  30484. as changes won't necessarily be picked up.
  30485. */
  30486. int preferredHeight;
  30487. };
  30488. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  30489. /*** End of inlined file: juce_PropertyComponent.h ***/
  30490. /**
  30491. A panel that holds a list of PropertyComponent objects.
  30492. This panel displays a list of PropertyComponents, and allows them to be organised
  30493. into collapsible sections.
  30494. To use, simply create one of these and add your properties to it with addProperties()
  30495. or addSection().
  30496. @see PropertyComponent
  30497. */
  30498. class JUCE_API PropertyPanel : public Component
  30499. {
  30500. public:
  30501. /** Creates an empty property panel. */
  30502. PropertyPanel();
  30503. /** Destructor. */
  30504. ~PropertyPanel();
  30505. /** Deletes all property components from the panel.
  30506. */
  30507. void clear();
  30508. /** Adds a set of properties to the panel.
  30509. The components in the list will be owned by this object and will be automatically
  30510. deleted later on when no longer needed.
  30511. These properties are added without them being inside a named section. If you
  30512. want them to be kept together in a collapsible section, use addSection() instead.
  30513. */
  30514. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  30515. /** Adds a set of properties to the panel.
  30516. These properties are added at the bottom of the list, under a section heading with
  30517. a plus/minus button that allows it to be opened and closed.
  30518. The components in the list will be owned by this object and will be automatically
  30519. deleted later on when no longer needed.
  30520. To add properies without them being in a section, use addProperties().
  30521. */
  30522. void addSection (const String& sectionTitle,
  30523. const Array <PropertyComponent*>& newPropertyComponents,
  30524. bool shouldSectionInitiallyBeOpen = true);
  30525. /** Calls the refresh() method of all PropertyComponents in the panel */
  30526. void refreshAll() const;
  30527. /** Returns a list of all the names of sections in the panel.
  30528. These are the sections that have been added with addSection().
  30529. */
  30530. const StringArray getSectionNames() const;
  30531. /** Returns true if the section at this index is currently open.
  30532. The index is from 0 up to the number of items returned by getSectionNames().
  30533. */
  30534. bool isSectionOpen (int sectionIndex) const;
  30535. /** Opens or closes one of the sections.
  30536. The index is from 0 up to the number of items returned by getSectionNames().
  30537. */
  30538. void setSectionOpen (int sectionIndex, bool shouldBeOpen);
  30539. /** Enables or disables one of the sections.
  30540. The index is from 0 up to the number of items returned by getSectionNames().
  30541. */
  30542. void setSectionEnabled (int sectionIndex, bool shouldBeEnabled);
  30543. /** Saves the current state of open/closed sections so it can be restored later.
  30544. The caller is responsible for deleting the object that is returned.
  30545. To restore this state, use restoreOpennessState().
  30546. @see restoreOpennessState
  30547. */
  30548. XmlElement* getOpennessState() const;
  30549. /** Restores a previously saved arrangement of open/closed sections.
  30550. This will try to restore a snapshot of the panel's state that was created by
  30551. the getOpennessState() method. If any of the sections named in the original
  30552. XML aren't present, they will be ignored.
  30553. @see getOpennessState
  30554. */
  30555. void restoreOpennessState (const XmlElement& newState);
  30556. /** Sets a message to be displayed when there are no properties in the panel.
  30557. The default message is "nothing selected".
  30558. */
  30559. void setMessageWhenEmpty (const String& newMessage);
  30560. /** Returns the message that is displayed when there are no properties.
  30561. @see setMessageWhenEmpty
  30562. */
  30563. const String& getMessageWhenEmpty() const;
  30564. /** @internal */
  30565. void paint (Graphics& g);
  30566. /** @internal */
  30567. void resized();
  30568. juce_UseDebuggingNewOperator
  30569. private:
  30570. Viewport* viewport;
  30571. class PropertyHolderComponent;
  30572. PropertyHolderComponent* propertyHolderComponent;
  30573. String messageWhenEmpty;
  30574. void updatePropHolderLayout() const;
  30575. void updatePropHolderLayout (int width) const;
  30576. };
  30577. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  30578. /*** End of inlined file: juce_PropertyPanel.h ***/
  30579. /**
  30580. A type of UI component that displays the parameters of an AudioProcessor as
  30581. a simple list of sliders.
  30582. This can be used for showing an editor for a processor that doesn't supply
  30583. its own custom editor.
  30584. @see AudioProcessor
  30585. */
  30586. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  30587. {
  30588. public:
  30589. GenericAudioProcessorEditor (AudioProcessor* const owner);
  30590. ~GenericAudioProcessorEditor();
  30591. void paint (Graphics& g);
  30592. void resized();
  30593. juce_UseDebuggingNewOperator
  30594. private:
  30595. PropertyPanel* panel;
  30596. GenericAudioProcessorEditor (const GenericAudioProcessorEditor&);
  30597. GenericAudioProcessorEditor& operator= (const GenericAudioProcessorEditor&);
  30598. };
  30599. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30600. /*** End of inlined file: juce_GenericAudioProcessorEditor.h ***/
  30601. #endif
  30602. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  30603. /*** Start of inlined file: juce_Sampler.h ***/
  30604. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  30605. #define __JUCE_SAMPLER_JUCEHEADER__
  30606. /*** Start of inlined file: juce_Synthesiser.h ***/
  30607. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  30608. #define __JUCE_SYNTHESISER_JUCEHEADER__
  30609. /**
  30610. Describes one of the sounds that a Synthesiser can play.
  30611. A synthesiser can contain one or more sounds, and a sound can choose which
  30612. midi notes and channels can trigger it.
  30613. The SynthesiserSound is a passive class that just describes what the sound is -
  30614. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  30615. more than one SynthesiserVoice to play the same sound at the same time.
  30616. @see Synthesiser, SynthesiserVoice
  30617. */
  30618. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  30619. {
  30620. protected:
  30621. SynthesiserSound();
  30622. public:
  30623. /** Destructor. */
  30624. virtual ~SynthesiserSound();
  30625. /** Returns true if this sound should be played when a given midi note is pressed.
  30626. The Synthesiser will use this information when deciding which sounds to trigger
  30627. for a given note.
  30628. */
  30629. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  30630. /** Returns true if the sound should be triggered by midi events on a given channel.
  30631. The Synthesiser will use this information when deciding which sounds to trigger
  30632. for a given note.
  30633. */
  30634. virtual bool appliesToChannel (const int midiChannel) = 0;
  30635. /**
  30636. */
  30637. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  30638. juce_UseDebuggingNewOperator
  30639. };
  30640. /**
  30641. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  30642. A voice plays a single sound at a time, and a synthesiser holds an array of
  30643. voices so that it can play polyphonically.
  30644. @see Synthesiser, SynthesiserSound
  30645. */
  30646. class JUCE_API SynthesiserVoice
  30647. {
  30648. public:
  30649. /** Creates a voice. */
  30650. SynthesiserVoice();
  30651. /** Destructor. */
  30652. virtual ~SynthesiserVoice();
  30653. /** Returns the midi note that this voice is currently playing.
  30654. Returns a value less than 0 if no note is playing.
  30655. */
  30656. int getCurrentlyPlayingNote() const { return currentlyPlayingNote; }
  30657. /** Returns the sound that this voice is currently playing.
  30658. Returns 0 if it's not playing.
  30659. */
  30660. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const { return currentlyPlayingSound; }
  30661. /** Must return true if this voice object is capable of playing the given sound.
  30662. If there are different classes of sound, and different classes of voice, a voice can
  30663. choose which ones it wants to take on.
  30664. A typical implementation of this method may just return true if there's only one type
  30665. of voice and sound, or it might check the type of the sound object passed-in and
  30666. see if it's one that it understands.
  30667. */
  30668. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  30669. /** Called to start a new note.
  30670. This will be called during the rendering callback, so must be fast and thread-safe.
  30671. */
  30672. virtual void startNote (const int midiNoteNumber,
  30673. const float velocity,
  30674. SynthesiserSound* sound,
  30675. const int currentPitchWheelPosition) = 0;
  30676. /** Called to stop a note.
  30677. This will be called during the rendering callback, so must be fast and thread-safe.
  30678. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  30679. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  30680. and allow the synth to reassign it another sound.
  30681. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  30682. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  30683. finishes playing (during the rendering callback), it must make sure that it calls
  30684. clearCurrentNote().
  30685. */
  30686. virtual void stopNote (const bool allowTailOff) = 0;
  30687. /** Called to let the voice know that the pitch wheel has been moved.
  30688. This will be called during the rendering callback, so must be fast and thread-safe.
  30689. */
  30690. virtual void pitchWheelMoved (const int newValue) = 0;
  30691. /** Called to let the voice know that a midi controller has been moved.
  30692. This will be called during the rendering callback, so must be fast and thread-safe.
  30693. */
  30694. virtual void controllerMoved (const int controllerNumber,
  30695. const int newValue) = 0;
  30696. /** Renders the next block of data for this voice.
  30697. The output audio data must be added to the current contents of the buffer provided.
  30698. Only the region of the buffer between startSample and (startSample + numSamples)
  30699. should be altered by this method.
  30700. If the voice is currently silent, it should just return without doing anything.
  30701. If the sound that the voice is playing finishes during the course of this rendered
  30702. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  30703. The size of the blocks that are rendered can change each time it is called, and may
  30704. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  30705. the voice's methods will be called to tell it about note and controller events.
  30706. */
  30707. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  30708. int startSample,
  30709. int numSamples) = 0;
  30710. /** Returns true if the voice is currently playing a sound which is mapped to the given
  30711. midi channel.
  30712. If it's not currently playing, this will return false.
  30713. */
  30714. bool isPlayingChannel (int midiChannel) const;
  30715. /** Changes the voice's reference sample rate.
  30716. The rate is set so that subclasses know the output rate and can set their pitch
  30717. accordingly.
  30718. This method is called by the synth, and subclasses can access the current rate with
  30719. the currentSampleRate member.
  30720. */
  30721. void setCurrentPlaybackSampleRate (double newRate);
  30722. juce_UseDebuggingNewOperator
  30723. protected:
  30724. /** Returns the current target sample rate at which rendering is being done.
  30725. This is available for subclasses so they can pitch things correctly.
  30726. */
  30727. double getSampleRate() const { return currentSampleRate; }
  30728. /** Resets the state of this voice after a sound has finished playing.
  30729. The subclass must call this when it finishes playing a note and becomes available
  30730. to play new ones.
  30731. It must either call it in the stopNote() method, or if the voice is tailing off,
  30732. then it should call it later during the renderNextBlock method, as soon as it
  30733. finishes its tail-off.
  30734. It can also be called at any time during the render callback if the sound happens
  30735. to have finished, e.g. if it's playing a sample and the sample finishes.
  30736. */
  30737. void clearCurrentNote();
  30738. private:
  30739. friend class Synthesiser;
  30740. double currentSampleRate;
  30741. int currentlyPlayingNote;
  30742. uint32 noteOnTime;
  30743. SynthesiserSound::Ptr currentlyPlayingSound;
  30744. };
  30745. /**
  30746. Base class for a musical device that can play sounds.
  30747. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  30748. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  30749. which can play back one of these sounds.
  30750. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  30751. set of sounds, and a set of voices it can use to play them. If you only give it
  30752. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  30753. have available.
  30754. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  30755. events that go in will be scanned for note on/off messages, and these are used to
  30756. start and stop the voices playing the appropriate sounds.
  30757. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  30758. noteOff() and other controller methods.
  30759. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  30760. what the target playback rate is. This value is passed on to the voices so that
  30761. they can pitch their output correctly.
  30762. */
  30763. class JUCE_API Synthesiser
  30764. {
  30765. public:
  30766. /** Creates a new synthesiser.
  30767. You'll need to add some sounds and voices before it'll make any sound..
  30768. */
  30769. Synthesiser();
  30770. /** Destructor. */
  30771. virtual ~Synthesiser();
  30772. /** Deletes all voices. */
  30773. void clearVoices();
  30774. /** Returns the number of voices that have been added. */
  30775. int getNumVoices() const { return voices.size(); }
  30776. /** Returns one of the voices that have been added. */
  30777. SynthesiserVoice* getVoice (int index) const;
  30778. /** Adds a new voice to the synth.
  30779. All the voices should be the same class of object and are treated equally.
  30780. The object passed in will be managed by the synthesiser, which will delete
  30781. it later on when no longer needed. The caller should not retain a pointer to the
  30782. voice.
  30783. */
  30784. void addVoice (SynthesiserVoice* newVoice);
  30785. /** Deletes one of the voices. */
  30786. void removeVoice (int index);
  30787. /** Deletes all sounds. */
  30788. void clearSounds();
  30789. /** Returns the number of sounds that have been added to the synth. */
  30790. int getNumSounds() const { return sounds.size(); }
  30791. /** Returns one of the sounds. */
  30792. SynthesiserSound* getSound (int index) const { return sounds [index]; }
  30793. /** Adds a new sound to the synthesiser.
  30794. The object passed in is reference counted, so will be deleted when it is removed
  30795. from the synthesiser, and when no voices are still using it.
  30796. */
  30797. void addSound (const SynthesiserSound::Ptr& newSound);
  30798. /** Removes and deletes one of the sounds. */
  30799. void removeSound (int index);
  30800. /** If set to true, then the synth will try to take over an existing voice if
  30801. it runs out and needs to play another note.
  30802. The value of this boolean is passed into findFreeVoice(), so the result will
  30803. depend on the implementation of this method.
  30804. */
  30805. void setNoteStealingEnabled (bool shouldStealNotes);
  30806. /** Returns true if note-stealing is enabled.
  30807. @see setNoteStealingEnabled
  30808. */
  30809. bool isNoteStealingEnabled() const { return shouldStealNotes; }
  30810. /** Triggers a note-on event.
  30811. The default method here will find all the sounds that want to be triggered by
  30812. this note/channel. For each sound, it'll try to find a free voice, and use the
  30813. voice to start playing the sound.
  30814. Subclasses might want to override this if they need a more complex algorithm.
  30815. This method will be called automatically according to the midi data passed into
  30816. renderNextBlock(), but may be called explicitly too.
  30817. */
  30818. virtual void noteOn (const int midiChannel,
  30819. const int midiNoteNumber,
  30820. const float velocity);
  30821. /** Triggers a note-off event.
  30822. This will turn off any voices that are playing a sound for the given note/channel.
  30823. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  30824. (if they can do). If this is false, the notes will all be cut off immediately.
  30825. This method will be called automatically according to the midi data passed into
  30826. renderNextBlock(), but may be called explicitly too.
  30827. */
  30828. virtual void noteOff (const int midiChannel,
  30829. const int midiNoteNumber,
  30830. const bool allowTailOff);
  30831. /** Turns off all notes.
  30832. This will turn off any voices that are playing a sound on the given midi channel.
  30833. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  30834. which channel they're playing.
  30835. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  30836. (if they can do). If this is false, the notes will all be cut off immediately.
  30837. This method will be called automatically according to the midi data passed into
  30838. renderNextBlock(), but may be called explicitly too.
  30839. */
  30840. virtual void allNotesOff (const int midiChannel,
  30841. const bool allowTailOff);
  30842. /** Sends a pitch-wheel message.
  30843. This will send a pitch-wheel message to any voices that are playing sounds on
  30844. the given midi channel.
  30845. This method will be called automatically according to the midi data passed into
  30846. renderNextBlock(), but may be called explicitly too.
  30847. @param midiChannel the midi channel for the event
  30848. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  30849. */
  30850. virtual void handlePitchWheel (const int midiChannel,
  30851. const int wheelValue);
  30852. /** Sends a midi controller message.
  30853. This will send a midi controller message to any voices that are playing sounds on
  30854. the given midi channel.
  30855. This method will be called automatically according to the midi data passed into
  30856. renderNextBlock(), but may be called explicitly too.
  30857. @param midiChannel the midi channel for the event
  30858. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  30859. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  30860. */
  30861. virtual void handleController (const int midiChannel,
  30862. const int controllerNumber,
  30863. const int controllerValue);
  30864. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  30865. render.
  30866. This value is propagated to the voices so that they can use it to render the correct
  30867. pitches.
  30868. */
  30869. void setCurrentPlaybackSampleRate (const double sampleRate);
  30870. /** Creates the next block of audio output.
  30871. This will process the next numSamples of data from all the voices, and add that output
  30872. to the audio block supplied, starting from the offset specified. Note that the
  30873. data will be added to the current contents of the buffer, so you should clear it
  30874. before calling this method if necessary.
  30875. The midi events in the inputMidi buffer are parsed for note and controller events,
  30876. and these are used to trigger the voices. Note that the startSample offset applies
  30877. both to the audio output buffer and the midi input buffer, so any midi events
  30878. with timestamps outside the specified region will be ignored.
  30879. */
  30880. void renderNextBlock (AudioSampleBuffer& outputAudio,
  30881. const MidiBuffer& inputMidi,
  30882. int startSample,
  30883. int numSamples);
  30884. juce_UseDebuggingNewOperator
  30885. protected:
  30886. /** This is used to control access to the rendering callback and the note trigger methods. */
  30887. CriticalSection lock;
  30888. OwnedArray <SynthesiserVoice> voices;
  30889. ReferenceCountedArray <SynthesiserSound> sounds;
  30890. /** The last pitch-wheel values for each midi channel. */
  30891. int lastPitchWheelValues [16];
  30892. /** Searches through the voices to find one that's not currently playing, and which
  30893. can play the given sound.
  30894. Returns 0 if all voices are busy and stealing isn't enabled.
  30895. This can be overridden to implement custom voice-stealing algorithms.
  30896. */
  30897. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  30898. const bool stealIfNoneAvailable) const;
  30899. /** Starts a specified voice playing a particular sound.
  30900. You'll probably never need to call this, it's used internally by noteOn(), but
  30901. may be needed by subclasses for custom behaviours.
  30902. */
  30903. void startVoice (SynthesiserVoice* voice,
  30904. SynthesiserSound* sound,
  30905. int midiChannel,
  30906. int midiNoteNumber,
  30907. float velocity);
  30908. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  30909. int findFreeVoice (const bool) const { return 0; }
  30910. private:
  30911. double sampleRate;
  30912. uint32 lastNoteOnCounter;
  30913. bool shouldStealNotes;
  30914. Synthesiser (const Synthesiser&);
  30915. Synthesiser& operator= (const Synthesiser&);
  30916. };
  30917. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  30918. /*** End of inlined file: juce_Synthesiser.h ***/
  30919. /**
  30920. A subclass of SynthesiserSound that represents a sampled audio clip.
  30921. This is a pretty basic sampler, and just attempts to load the whole audio stream
  30922. into memory.
  30923. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  30924. give it some SampledSound objects to play.
  30925. @see SamplerVoice, Synthesiser, SynthesiserSound
  30926. */
  30927. class JUCE_API SamplerSound : public SynthesiserSound
  30928. {
  30929. public:
  30930. /** Creates a sampled sound from an audio reader.
  30931. This will attempt to load the audio from the source into memory and store
  30932. it in this object.
  30933. @param name a name for the sample
  30934. @param source the audio to load. This object can be safely deleted by the
  30935. caller after this constructor returns
  30936. @param midiNotes the set of midi keys that this sound should be played on. This
  30937. is used by the SynthesiserSound::appliesToNote() method
  30938. @param midiNoteForNormalPitch the midi note at which the sample should be played
  30939. with its natural rate. All other notes will be pitched
  30940. up or down relative to this one
  30941. @param attackTimeSecs the attack (fade-in) time, in seconds
  30942. @param releaseTimeSecs the decay (fade-out) time, in seconds
  30943. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  30944. source, in seconds
  30945. */
  30946. SamplerSound (const String& name,
  30947. AudioFormatReader& source,
  30948. const BigInteger& midiNotes,
  30949. int midiNoteForNormalPitch,
  30950. double attackTimeSecs,
  30951. double releaseTimeSecs,
  30952. double maxSampleLengthSeconds);
  30953. /** Destructor. */
  30954. ~SamplerSound();
  30955. /** Returns the sample's name */
  30956. const String& getName() const { return name; }
  30957. /** Returns the audio sample data.
  30958. This could be 0 if there was a problem loading it.
  30959. */
  30960. AudioSampleBuffer* getAudioData() const { return data; }
  30961. bool appliesToNote (const int midiNoteNumber);
  30962. bool appliesToChannel (const int midiChannel);
  30963. juce_UseDebuggingNewOperator
  30964. private:
  30965. friend class SamplerVoice;
  30966. String name;
  30967. ScopedPointer <AudioSampleBuffer> data;
  30968. double sourceSampleRate;
  30969. BigInteger midiNotes;
  30970. int length, attackSamples, releaseSamples;
  30971. int midiRootNote;
  30972. };
  30973. /**
  30974. A subclass of SynthesiserVoice that can play a SamplerSound.
  30975. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  30976. give it some SampledSound objects to play.
  30977. @see SamplerSound, Synthesiser, SynthesiserVoice
  30978. */
  30979. class JUCE_API SamplerVoice : public SynthesiserVoice
  30980. {
  30981. public:
  30982. /** Creates a SamplerVoice.
  30983. */
  30984. SamplerVoice();
  30985. /** Destructor. */
  30986. ~SamplerVoice();
  30987. bool canPlaySound (SynthesiserSound* sound);
  30988. void startNote (const int midiNoteNumber,
  30989. const float velocity,
  30990. SynthesiserSound* sound,
  30991. const int currentPitchWheelPosition);
  30992. void stopNote (const bool allowTailOff);
  30993. void pitchWheelMoved (const int newValue);
  30994. void controllerMoved (const int controllerNumber,
  30995. const int newValue);
  30996. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  30997. juce_UseDebuggingNewOperator
  30998. private:
  30999. double pitchRatio;
  31000. double sourceSamplePosition;
  31001. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  31002. bool isInAttack, isInRelease;
  31003. };
  31004. #endif // __JUCE_SAMPLER_JUCEHEADER__
  31005. /*** End of inlined file: juce_Sampler.h ***/
  31006. #endif
  31007. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  31008. #endif
  31009. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31010. /*** Start of inlined file: juce_ActionBroadcaster.h ***/
  31011. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31012. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31013. /*** Start of inlined file: juce_ActionListenerList.h ***/
  31014. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31015. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31016. /**
  31017. A set of ActionListeners.
  31018. Listeners can be added and removed from the list, and messages can be
  31019. broadcast to all the listeners.
  31020. @see ActionListener, ActionBroadcaster
  31021. */
  31022. class JUCE_API ActionListenerList : public MessageListener
  31023. {
  31024. public:
  31025. /** Creates an empty list. */
  31026. ActionListenerList() throw();
  31027. /** Destructor. */
  31028. ~ActionListenerList() throw();
  31029. /** Adds a listener to the list.
  31030. (Trying to add a listener that's already on the list will have no effect).
  31031. */
  31032. void addActionListener (ActionListener* listener) throw();
  31033. /** Removes a listener from the list.
  31034. If the listener isn't on the list, this won't have any effect.
  31035. */
  31036. void removeActionListener (ActionListener* listener) throw();
  31037. /** Removes all listeners from the list. */
  31038. void removeAllActionListeners() throw();
  31039. /** Broadcasts a message to all the registered listeners.
  31040. This sends the message asynchronously.
  31041. If a listener is on the list when this method is called but is removed from
  31042. the list before the message arrives, it won't receive the message. Similarly
  31043. listeners that are added to the list after the message is sent but before it
  31044. arrives won't get the message either.
  31045. */
  31046. void sendActionMessage (const String& message) const;
  31047. /** @internal */
  31048. void handleMessage (const Message&);
  31049. juce_UseDebuggingNewOperator
  31050. private:
  31051. SortedSet <void*> actionListeners_;
  31052. CriticalSection actionListenerLock_;
  31053. ActionListenerList (const ActionListenerList&);
  31054. ActionListenerList& operator= (const ActionListenerList&);
  31055. };
  31056. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31057. /*** End of inlined file: juce_ActionListenerList.h ***/
  31058. /** Manages a list of ActionListeners, and can send them messages.
  31059. To quickly add methods to your class that can add/remove action
  31060. listeners and broadcast to them, you can derive from this.
  31061. @see ActionListenerList, ActionListener
  31062. */
  31063. class JUCE_API ActionBroadcaster
  31064. {
  31065. public:
  31066. /** Creates an ActionBroadcaster. */
  31067. ActionBroadcaster() throw();
  31068. /** Destructor. */
  31069. virtual ~ActionBroadcaster();
  31070. /** Adds a listener to the list.
  31071. (Trying to add a listener that's already on the list will have no effect).
  31072. */
  31073. void addActionListener (ActionListener* listener);
  31074. /** Removes a listener from the list.
  31075. If the listener isn't on the list, this won't have any effect.
  31076. */
  31077. void removeActionListener (ActionListener* listener);
  31078. /** Removes all listeners from the list. */
  31079. void removeAllActionListeners();
  31080. /** Broadcasts a message to all the registered listeners.
  31081. @see ActionListenerList::sendActionMessage
  31082. */
  31083. void sendActionMessage (const String& message) const;
  31084. private:
  31085. ActionListenerList actionListenerList;
  31086. ActionBroadcaster (const ActionBroadcaster&);
  31087. ActionBroadcaster& operator= (const ActionBroadcaster&);
  31088. };
  31089. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31090. /*** End of inlined file: juce_ActionBroadcaster.h ***/
  31091. #endif
  31092. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  31093. #endif
  31094. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31095. #endif
  31096. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  31097. #endif
  31098. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31099. /*** Start of inlined file: juce_CallbackMessage.h ***/
  31100. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31101. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31102. /**
  31103. A message that calls a custom function when it gets delivered.
  31104. You can use this class to fire off actions that you want to be performed later
  31105. on the message thread.
  31106. Unlike other Message objects, these don't get sent to a MessageListener, you
  31107. just call the post() method to send them, and when they arrive, your
  31108. messageCallback() method will automatically be invoked.
  31109. @see MessageListener, MessageManager, ActionListener, ChangeListener
  31110. */
  31111. class JUCE_API CallbackMessage : public Message
  31112. {
  31113. public:
  31114. CallbackMessage() throw();
  31115. /** Destructor. */
  31116. ~CallbackMessage() throw();
  31117. /** Called when the message is delivered.
  31118. You should implement this method and make it do whatever action you want
  31119. to perform.
  31120. Note that like all other messages, this object will be deleted immediately
  31121. after this method has been invoked.
  31122. */
  31123. virtual void messageCallback() = 0;
  31124. /** Instead of sending this message to a MessageListener, just call this method
  31125. to post it to the event queue.
  31126. After you've called this, this object will belong to the MessageManager,
  31127. which will delete it later. So make sure you don't delete the object yourself,
  31128. call post() more than once, or call post() on a stack-based obect!
  31129. */
  31130. void post();
  31131. juce_UseDebuggingNewOperator
  31132. private:
  31133. CallbackMessage (const CallbackMessage&);
  31134. CallbackMessage& operator= (const CallbackMessage&);
  31135. };
  31136. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31137. /*** End of inlined file: juce_CallbackMessage.h ***/
  31138. #endif
  31139. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  31140. #endif
  31141. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  31142. #endif
  31143. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  31144. #endif
  31145. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31146. /*** Start of inlined file: juce_InterprocessConnection.h ***/
  31147. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31148. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31149. class InterprocessConnectionServer;
  31150. /**
  31151. Manages a simple two-way messaging connection to another process, using either
  31152. a socket or a named pipe as the transport medium.
  31153. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  31154. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  31155. and incoming messages will result in a callback via the messageReceived()
  31156. method.
  31157. To open a pipe and wait for another client to connect to it, use the createPipe()
  31158. method.
  31159. To act as a socket server and create connections for one or more client, see the
  31160. InterprocessConnectionServer class.
  31161. @see InterprocessConnectionServer, Socket, NamedPipe
  31162. */
  31163. class JUCE_API InterprocessConnection : public Thread,
  31164. private MessageListener
  31165. {
  31166. public:
  31167. /** Creates a connection.
  31168. Connections are created manually, connecting them with the connectToSocket()
  31169. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  31170. when a client wants to connect.
  31171. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  31172. connectionLost() and messageReceived() methods will
  31173. always be made using the message thread; if false,
  31174. these will be called immediately on the connection's
  31175. own thread.
  31176. @param magicMessageHeaderNumber a magic number to use in the header to check the
  31177. validity of the data blocks being sent and received. This
  31178. can be any number, but the sender and receiver must obviously
  31179. use matching values or they won't recognise each other.
  31180. */
  31181. InterprocessConnection (bool callbacksOnMessageThread = true,
  31182. uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  31183. /** Destructor. */
  31184. ~InterprocessConnection();
  31185. /** Tries to connect this object to a socket.
  31186. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  31187. object waiting to receive client connections on this port number.
  31188. @param hostName the host computer, either a network address or name
  31189. @param portNumber the socket port number to try to connect to
  31190. @param timeOutMillisecs how long to keep trying before giving up
  31191. @returns true if the connection is established successfully
  31192. @see Socket
  31193. */
  31194. bool connectToSocket (const String& hostName,
  31195. int portNumber,
  31196. int timeOutMillisecs);
  31197. /** Tries to connect the object to an existing named pipe.
  31198. For this to work, another process on the same computer must already have opened
  31199. an InterprocessConnection object and used createPipe() to create a pipe for this
  31200. to connect to.
  31201. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  31202. @returns true if it connects successfully.
  31203. @see createPipe, NamedPipe
  31204. */
  31205. bool connectToPipe (const String& pipeName,
  31206. int pipeReceiveMessageTimeoutMs = -1);
  31207. /** Tries to create a new pipe for other processes to connect to.
  31208. This creates a pipe with the given name, so that other processes can use
  31209. connectToPipe() to connect to the other end.
  31210. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  31211. If another process is already using this pipe, this will fail and return false.
  31212. */
  31213. bool createPipe (const String& pipeName,
  31214. int pipeReceiveMessageTimeoutMs = -1);
  31215. /** Disconnects and closes any currently-open sockets or pipes. */
  31216. void disconnect();
  31217. /** True if a socket or pipe is currently active. */
  31218. bool isConnected() const;
  31219. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  31220. StreamingSocket* getSocket() const throw() { return socket; }
  31221. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  31222. NamedPipe* getPipe() const throw() { return pipe; }
  31223. /** Returns the name of the machine at the other end of this connection.
  31224. This will return an empty string if the other machine isn't known for
  31225. some reason.
  31226. */
  31227. const String getConnectedHostName() const;
  31228. /** Tries to send a message to the other end of this connection.
  31229. This will fail if it's not connected, or if there's some kind of write error. If
  31230. it succeeds, the connection object at the other end will receive the message by
  31231. a callback to its messageReceived() method.
  31232. @see messageReceived
  31233. */
  31234. bool sendMessage (const MemoryBlock& message);
  31235. /** Called when the connection is first connected.
  31236. If the connection was created with the callbacksOnMessageThread flag set, then
  31237. this will be called on the message thread; otherwise it will be called on a server
  31238. thread.
  31239. */
  31240. virtual void connectionMade() = 0;
  31241. /** Called when the connection is broken.
  31242. If the connection was created with the callbacksOnMessageThread flag set, then
  31243. this will be called on the message thread; otherwise it will be called on a server
  31244. thread.
  31245. */
  31246. virtual void connectionLost() = 0;
  31247. /** Called when a message arrives.
  31248. When the object at the other end of this connection sends us a message with sendMessage(),
  31249. this callback is used to deliver it to us.
  31250. If the connection was created with the callbacksOnMessageThread flag set, then
  31251. this will be called on the message thread; otherwise it will be called on a server
  31252. thread.
  31253. @see sendMessage
  31254. */
  31255. virtual void messageReceived (const MemoryBlock& message) = 0;
  31256. juce_UseDebuggingNewOperator
  31257. private:
  31258. CriticalSection pipeAndSocketLock;
  31259. ScopedPointer <StreamingSocket> socket;
  31260. ScopedPointer <NamedPipe> pipe;
  31261. bool callbackConnectionState;
  31262. const bool useMessageThread;
  31263. const uint32 magicMessageHeader;
  31264. int pipeReceiveMessageTimeout;
  31265. friend class InterprocessConnectionServer;
  31266. void initialiseWithSocket (StreamingSocket* socket_);
  31267. void initialiseWithPipe (NamedPipe* pipe_);
  31268. void handleMessage (const Message& message);
  31269. void connectionMadeInt();
  31270. void connectionLostInt();
  31271. void deliverDataInt (const MemoryBlock& data);
  31272. bool readNextMessageInt();
  31273. void run();
  31274. InterprocessConnection (const InterprocessConnection&);
  31275. InterprocessConnection& operator= (const InterprocessConnection&);
  31276. };
  31277. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31278. /*** End of inlined file: juce_InterprocessConnection.h ***/
  31279. #endif
  31280. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31281. /*** Start of inlined file: juce_InterprocessConnectionServer.h ***/
  31282. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31283. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31284. /**
  31285. An object that waits for client sockets to connect to a port on this host, and
  31286. creates InterprocessConnection objects for each one.
  31287. To use this, create a class derived from it which implements the createConnectionObject()
  31288. method, so that it creates suitable connection objects for each client that tries
  31289. to connect.
  31290. @see InterprocessConnection
  31291. */
  31292. class JUCE_API InterprocessConnectionServer : private Thread
  31293. {
  31294. public:
  31295. /** Creates an uninitialised server object.
  31296. */
  31297. InterprocessConnectionServer();
  31298. /** Destructor. */
  31299. ~InterprocessConnectionServer();
  31300. /** Starts an internal thread which listens on the given port number.
  31301. While this is running, in another process tries to connect with the
  31302. InterprocessConnection::connectToSocket() method, this object will call
  31303. createConnectionObject() to create a connection to that client.
  31304. Use stop() to stop the thread running.
  31305. @see createConnectionObject, stop
  31306. */
  31307. bool beginWaitingForSocket (int portNumber);
  31308. /** Terminates the listener thread, if it's active.
  31309. @see beginWaitingForSocket
  31310. */
  31311. void stop();
  31312. protected:
  31313. /** Creates a suitable connection object for a client process that wants to
  31314. connect to this one.
  31315. This will be called by the listener thread when a client process tries
  31316. to connect, and must return a new InterprocessConnection object that will
  31317. then run as this end of the connection.
  31318. @see InterprocessConnection
  31319. */
  31320. virtual InterprocessConnection* createConnectionObject() = 0;
  31321. public:
  31322. juce_UseDebuggingNewOperator
  31323. private:
  31324. ScopedPointer <StreamingSocket> socket;
  31325. void run();
  31326. InterprocessConnectionServer (const InterprocessConnectionServer&);
  31327. InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  31328. };
  31329. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31330. /*** End of inlined file: juce_InterprocessConnectionServer.h ***/
  31331. #endif
  31332. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  31333. #endif
  31334. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  31335. #endif
  31336. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  31337. #endif
  31338. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31339. /*** Start of inlined file: juce_MessageManager.h ***/
  31340. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31341. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31342. class Component;
  31343. class MessageManagerLock;
  31344. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  31345. */
  31346. typedef void* (MessageCallbackFunction) (void* userData);
  31347. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  31348. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  31349. */
  31350. class JUCE_API MessageManager
  31351. {
  31352. public:
  31353. /** Returns the global instance of the MessageManager. */
  31354. static MessageManager* getInstance() throw();
  31355. /** Runs the event dispatch loop until a stop message is posted.
  31356. This method is only intended to be run by the application's startup routine,
  31357. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  31358. @see stopDispatchLoop
  31359. */
  31360. void runDispatchLoop();
  31361. /** Sends a signal that the dispatch loop should terminate.
  31362. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  31363. will be interrupted and will return.
  31364. @see runDispatchLoop
  31365. */
  31366. void stopDispatchLoop();
  31367. /** Returns true if the stopDispatchLoop() method has been called.
  31368. */
  31369. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  31370. /** Synchronously dispatches messages until a given time has elapsed.
  31371. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  31372. otherwise returns true.
  31373. */
  31374. bool runDispatchLoopUntil (int millisecondsToRunFor);
  31375. /** Calls a function using the message-thread.
  31376. This can be used by any thread to cause this function to be called-back
  31377. by the message thread. If it's the message-thread that's calling this method,
  31378. then the function will just be called; if another thread is calling, a message
  31379. will be posted to the queue, and this method will block until that message
  31380. is delivered, the function is called, and the result is returned.
  31381. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  31382. thread has a critical section locked, which an unrelated message callback then tries to lock
  31383. before the message thread gets round to processing this callback.
  31384. @param callback the function to call - its signature must be @code
  31385. void* myCallbackFunction (void*) @endcode
  31386. @param userData a user-defined pointer that will be passed to the function that gets called
  31387. @returns the value that the callback function returns.
  31388. @see MessageManagerLock
  31389. */
  31390. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  31391. void* userData);
  31392. /** Returns true if the caller-thread is the message thread. */
  31393. bool isThisTheMessageThread() const throw();
  31394. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  31395. (Best to ignore this method unless you really know what you're doing..)
  31396. @see getCurrentMessageThread
  31397. */
  31398. void setCurrentThreadAsMessageThread();
  31399. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  31400. (Best to ignore this method unless you really know what you're doing..)
  31401. @see setCurrentMessageThread
  31402. */
  31403. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  31404. /** Returns true if the caller thread has currenltly got the message manager locked.
  31405. see the MessageManagerLock class for more info about this.
  31406. This will be true if the caller is the message thread, because that automatically
  31407. gains a lock while a message is being dispatched.
  31408. */
  31409. bool currentThreadHasLockedMessageManager() const throw();
  31410. /** Sends a message to all other JUCE applications that are running.
  31411. @param messageText the string that will be passed to the actionListenerCallback()
  31412. method of the broadcast listeners in the other app.
  31413. @see registerBroadcastListener, ActionListener
  31414. */
  31415. static void broadcastMessage (const String& messageText) throw();
  31416. /** Registers a listener to get told about broadcast messages.
  31417. The actionListenerCallback() callback's string parameter
  31418. is the message passed into broadcastMessage().
  31419. @see broadcastMessage
  31420. */
  31421. void registerBroadcastListener (ActionListener* listener) throw();
  31422. /** Deregisters a broadcast listener. */
  31423. void deregisterBroadcastListener (ActionListener* listener) throw();
  31424. /** @internal */
  31425. void deliverMessage (void*);
  31426. /** @internal */
  31427. void deliverBroadcastMessage (const String&);
  31428. /** @internal */
  31429. ~MessageManager() throw();
  31430. juce_UseDebuggingNewOperator
  31431. private:
  31432. MessageManager() throw();
  31433. friend class MessageListener;
  31434. friend class ChangeBroadcaster;
  31435. friend class ActionBroadcaster;
  31436. friend class CallbackMessage;
  31437. static MessageManager* instance;
  31438. SortedSet <const MessageListener*> messageListeners;
  31439. ScopedPointer <ActionListenerList> broadcastListeners;
  31440. friend class JUCEApplication;
  31441. bool quitMessagePosted, quitMessageReceived;
  31442. Thread::ThreadID messageThreadId;
  31443. static void* exitModalLoopCallback (void*);
  31444. void postMessageToQueue (Message* message);
  31445. void postCallbackMessage (Message* message);
  31446. static void doPlatformSpecificInitialisation();
  31447. static void doPlatformSpecificShutdown();
  31448. friend class MessageManagerLock;
  31449. Thread::ThreadID volatile threadWithLock;
  31450. CriticalSection lockingLock;
  31451. MessageManager (const MessageManager&);
  31452. MessageManager& operator= (const MessageManager&);
  31453. };
  31454. /** Used to make sure that the calling thread has exclusive access to the message loop.
  31455. Because it's not thread-safe to call any of the Component or other UI classes
  31456. from threads other than the message thread, one of these objects can be used to
  31457. lock the message loop and allow this to be done. The message thread will be
  31458. suspended for the lifetime of the MessageManagerLock object, so create one on
  31459. the stack like this: @code
  31460. void MyThread::run()
  31461. {
  31462. someData = 1234;
  31463. const MessageManagerLock mmLock;
  31464. // the event loop will now be locked so it's safe to make a few calls..
  31465. myComponent->setBounds (newBounds);
  31466. myComponent->repaint();
  31467. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  31468. }
  31469. @endcode
  31470. Obviously be careful not to create one of these and leave it lying around, or
  31471. your app will grind to a halt!
  31472. Another caveat is that using this in conjunction with other CriticalSections
  31473. can create lots of interesting ways of producing a deadlock! In particular, if
  31474. your message thread calls stopThread() for a thread that uses these locks,
  31475. you'll get an (occasional) deadlock..
  31476. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  31477. */
  31478. class JUCE_API MessageManagerLock
  31479. {
  31480. public:
  31481. /** Tries to acquire a lock on the message manager.
  31482. The constructor attempts to gain a lock on the message loop, and the lock will be
  31483. kept for the lifetime of this object.
  31484. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  31485. this method will keep checking whether the thread has been given the
  31486. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  31487. without gaining the lock. If you pass a thread, you must check whether the lock was
  31488. successful by calling lockWasGained(). If this is false, your thread is being told to
  31489. die, so you should take evasive action.
  31490. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  31491. careful when doing this, because it's very easy to deadlock if your message thread
  31492. attempts to call stopThread() on a thread just as that thread attempts to get the
  31493. message lock.
  31494. If the calling thread already has the lock, nothing will be done, so it's safe and
  31495. quick to use these locks recursively.
  31496. E.g.
  31497. @code
  31498. void run()
  31499. {
  31500. ...
  31501. while (! threadShouldExit())
  31502. {
  31503. MessageManagerLock mml (Thread::getCurrentThread());
  31504. if (! mml.lockWasGained())
  31505. return; // another thread is trying to kill us!
  31506. ..do some locked stuff here..
  31507. }
  31508. ..and now the MM is now unlocked..
  31509. }
  31510. @endcode
  31511. */
  31512. MessageManagerLock (Thread* threadToCheckForExitSignal = 0) throw();
  31513. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  31514. instead of a thread.
  31515. See the MessageManagerLock (Thread*) constructor for details on how this works.
  31516. */
  31517. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal) throw();
  31518. /** Releases the current thread's lock on the message manager.
  31519. Make sure this object is created and deleted by the same thread,
  31520. otherwise there are no guarantees what will happen!
  31521. */
  31522. ~MessageManagerLock() throw();
  31523. /** Returns true if the lock was successfully acquired.
  31524. (See the constructor that takes a Thread for more info).
  31525. */
  31526. bool lockWasGained() const throw() { return locked; }
  31527. private:
  31528. class SharedEvents;
  31529. class BlockingMessage;
  31530. friend class SharedEvents;
  31531. friend class BlockingMessage;
  31532. SharedEvents* sharedEvents;
  31533. bool locked;
  31534. void init (Thread* thread, ThreadPoolJob* job) throw();
  31535. MessageManagerLock (const MessageManagerLock&);
  31536. MessageManagerLock& operator= (const MessageManagerLock&);
  31537. };
  31538. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31539. /*** End of inlined file: juce_MessageManager.h ***/
  31540. #endif
  31541. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  31542. /*** Start of inlined file: juce_MultiTimer.h ***/
  31543. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  31544. #define __JUCE_MULTITIMER_JUCEHEADER__
  31545. /**
  31546. A type of timer class that can run multiple timers with different frequencies,
  31547. all of which share a single callback.
  31548. This class is very similar to the Timer class, but allows you run multiple
  31549. separate timers, where each one has a unique ID number. The methods in this
  31550. class are exactly equivalent to those in Timer, but with the addition of
  31551. this ID number.
  31552. To use it, you need to create a subclass of MultiTimer, implementing the
  31553. timerCallback() method. Then you can start timers with startTimer(), and
  31554. each time the callback is triggered, it passes in the ID of the timer that
  31555. caused it.
  31556. @see Timer
  31557. */
  31558. class JUCE_API MultiTimer
  31559. {
  31560. protected:
  31561. /** Creates a MultiTimer.
  31562. When created, no timers are running, so use startTimer() to start things off.
  31563. */
  31564. MultiTimer() throw();
  31565. /** Creates a copy of another timer.
  31566. Note that this timer will not contain any running timers, even if the one you're
  31567. copying from was running.
  31568. */
  31569. MultiTimer (const MultiTimer& other) throw();
  31570. public:
  31571. /** Destructor. */
  31572. virtual ~MultiTimer();
  31573. /** The user-defined callback routine that actually gets called by each of the
  31574. timers that are running.
  31575. It's perfectly ok to call startTimer() or stopTimer() from within this
  31576. callback to change the subsequent intervals.
  31577. */
  31578. virtual void timerCallback (int timerId) = 0;
  31579. /** Starts a timer and sets the length of interval required.
  31580. If the timer is already started, this will reset it, so the
  31581. time between calling this method and the next timer callback
  31582. will not be less than the interval length passed in.
  31583. @param timerId a unique Id number that identifies the timer to
  31584. start. This is the id that will be passed back
  31585. to the timerCallback() method when this timer is
  31586. triggered
  31587. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  31588. rounded up to 1)
  31589. */
  31590. void startTimer (int timerId, int intervalInMilliseconds) throw();
  31591. /** Stops a timer.
  31592. If a timer has been started with the given ID number, it will be cancelled.
  31593. No more callbacks will be made for the specified timer after this method returns.
  31594. If this is called from a different thread, any callbacks that may
  31595. be currently executing may be allowed to finish before the method
  31596. returns.
  31597. */
  31598. void stopTimer (int timerId) throw();
  31599. /** Checks whether a timer has been started for a specified ID.
  31600. @returns true if a timer with the given ID is running.
  31601. */
  31602. bool isTimerRunning (int timerId) const throw();
  31603. /** Returns the interval for a specified timer ID.
  31604. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  31605. is running for the ID number specified.
  31606. */
  31607. int getTimerInterval (int timerId) const throw();
  31608. private:
  31609. class MultiTimerCallback;
  31610. CriticalSection timerListLock;
  31611. OwnedArray <MultiTimerCallback> timers;
  31612. MultiTimer& operator= (const MultiTimer&);
  31613. };
  31614. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  31615. /*** End of inlined file: juce_MultiTimer.h ***/
  31616. #endif
  31617. #ifndef __JUCE_TIMER_JUCEHEADER__
  31618. #endif
  31619. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31620. /*** Start of inlined file: juce_ArrowButton.h ***/
  31621. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31622. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  31623. /*** Start of inlined file: juce_DropShadowEffect.h ***/
  31624. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31625. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31626. /**
  31627. An effect filter that adds a drop-shadow behind the image's content.
  31628. (This will only work on images/components that aren't opaque, of course).
  31629. When added to a component, this effect will draw a soft-edged
  31630. shadow based on what gets drawn inside it. The shadow will also
  31631. be applied to the component's children.
  31632. For speed, this doesn't use a proper gaussian blur, but cheats by
  31633. using a simple bilinear filter. If you need a really high-quality
  31634. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  31635. @see Component::setComponentEffect
  31636. */
  31637. class JUCE_API DropShadowEffect : public ImageEffectFilter
  31638. {
  31639. public:
  31640. /** Creates a default drop-shadow effect.
  31641. To customise the shadow's appearance, use the setShadowProperties()
  31642. method.
  31643. */
  31644. DropShadowEffect();
  31645. /** Destructor. */
  31646. ~DropShadowEffect();
  31647. /** Sets up parameters affecting the shadow's appearance.
  31648. @param newRadius the (approximate) radius of the blur used
  31649. @param newOpacity the opacity with which the shadow is rendered
  31650. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  31651. component's contents
  31652. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  31653. component's contents
  31654. */
  31655. void setShadowProperties (float newRadius,
  31656. float newOpacity,
  31657. int newShadowOffsetX,
  31658. int newShadowOffsetY);
  31659. /** @internal */
  31660. void applyEffect (Image& sourceImage, Graphics& destContext);
  31661. juce_UseDebuggingNewOperator
  31662. private:
  31663. int offsetX, offsetY;
  31664. float radius, opacity;
  31665. };
  31666. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31667. /*** End of inlined file: juce_DropShadowEffect.h ***/
  31668. /**
  31669. A button with an arrow in it.
  31670. @see Button
  31671. */
  31672. class JUCE_API ArrowButton : public Button
  31673. {
  31674. public:
  31675. /** Creates an ArrowButton.
  31676. @param buttonName the name to give the button
  31677. @param arrowDirection the direction the arrow should point in, where 0.0 is
  31678. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  31679. @param arrowColour the colour to use for the arrow
  31680. */
  31681. ArrowButton (const String& buttonName,
  31682. float arrowDirection,
  31683. const Colour& arrowColour);
  31684. /** Destructor. */
  31685. ~ArrowButton();
  31686. juce_UseDebuggingNewOperator
  31687. protected:
  31688. /** @internal */
  31689. void paintButton (Graphics& g,
  31690. bool isMouseOverButton,
  31691. bool isButtonDown);
  31692. /** @internal */
  31693. void buttonStateChanged();
  31694. private:
  31695. Colour colour;
  31696. DropShadowEffect shadow;
  31697. Path path;
  31698. int offset;
  31699. ArrowButton (const ArrowButton&);
  31700. ArrowButton& operator= (const ArrowButton&);
  31701. };
  31702. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  31703. /*** End of inlined file: juce_ArrowButton.h ***/
  31704. #endif
  31705. #ifndef __JUCE_BUTTON_JUCEHEADER__
  31706. #endif
  31707. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31708. /*** Start of inlined file: juce_DrawableButton.h ***/
  31709. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31710. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31711. /*** Start of inlined file: juce_Drawable.h ***/
  31712. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  31713. #define __JUCE_DRAWABLE_JUCEHEADER__
  31714. /*** Start of inlined file: juce_RelativeCoordinate.h ***/
  31715. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  31716. #define __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  31717. /**
  31718. Expresses a coordinate as an absolute or proportional distance from other
  31719. named coordinates.
  31720. A RelativeCoordinate represents a position as either:
  31721. - an absolute distance from the origin
  31722. - an absolute distance from another named RelativeCoordinate
  31723. - a proportion of the distance between two other named RelativeCoordinates
  31724. Of course, the coordinates that this one is relative to may themselves be relative
  31725. to other coordinates, so complex arrangements can be built up (as long as you're careful
  31726. not to create recursive loops!)
  31727. Rather than keeping pointers to the coordinates that this one is dependent on, it
  31728. stores their names, and when resolving this coordinate to an absolute value, a
  31729. NamedCoordinateFinder class is required to retrieve these coordinates by name.
  31730. @see RelativePoint, RelativeRectangle
  31731. */
  31732. class JUCE_API RelativeCoordinate
  31733. {
  31734. public:
  31735. /** Creates a zero coordinate. */
  31736. RelativeCoordinate();
  31737. /** Creates an absolute position from the parent origin on either the X or Y axis.
  31738. @param absoluteDistanceFromOrigin the distance from the origin
  31739. @param isHorizontal this must be true if this is an X coordinate, or false if it's on the Y axis.
  31740. */
  31741. RelativeCoordinate (double absoluteDistanceFromOrigin, bool isHorizontal);
  31742. /** Creates an absolute position relative to a named coordinate.
  31743. @param absoluteDistanceFromAnchor the distance to add to the named anchor point
  31744. @param anchorPoint the name of the coordinate from which this one will be relative. See the constructor
  31745. notes for a description of the syntax for coordinate names.
  31746. */
  31747. RelativeCoordinate (double absoluteDistanceFromAnchor, const String& anchorPoint);
  31748. /** Creates a relative position between two named points.
  31749. @param relativeProportionBetweenAnchors a value between 0 and 1 indicating this coordinate's relative position
  31750. between anchorPoint1 and anchorPoint2.
  31751. @param anchorPoint1 the name of the first coordinate from which this one will be relative. See the constructor
  31752. notes for a description of the syntax for coordinate names.
  31753. @param anchorPoint2 the name of the first coordinate from which this one will be relative. See the constructor
  31754. notes for a description of the syntax for coordinate names.
  31755. */
  31756. RelativeCoordinate (double relativeProportionBetweenAnchors, const String& anchorPoint1, const String& anchorPoint2);
  31757. /** Recreates a coordinate from a string description.
  31758. The string can be in one of the following formats:
  31759. - "123" = 123 pixels from parent origin (this is equivalent to "parent.left + 123"
  31760. or "parent.top + 123", depending on which axis the coordinate is using)
  31761. - "anchor" = the same position as the coordinate named "anchor"
  31762. - "anchor + 123" = the coordinate named "anchor" + 123 pixels
  31763. - "anchor - 123" = the coordinate named "anchor" - 123 pixels
  31764. - "50%" = 50% of the distance between the coordinate space's top-left origin and its extent
  31765. (this is equivalent to "50% * parent.left -> parent.right" or "50% * parent.top -> parent.bottom")
  31766. - "50% * anchor" = 50% of the distance between the coordinate space's origin and the coordinate named "anchor"
  31767. (this is equivalent to "50% * parent.left -> anchor" or "50% * parent.top -> anchor")
  31768. - "50% * anchor1 -> anchor2" = 50% of the distance between the coordinate "anchor1" and the coordinate "anchor2"
  31769. An anchor name can either be just a single identifier (letters, digits and underscores only - no spaces),
  31770. e.g. "marker1", or it can be a two-part name in the form "objectName.edge". For example "parent.left" is
  31771. the origin, or "myComponent.top" is the top edge of a component called "myComponent". The exact names that
  31772. will be recognised are dependent on the NamedCoordinateFinder that you provide for looking them up, but
  31773. "parent.left" and "parent.top" are always available, meaning the origin. "parent.right" and "parent.bottom"
  31774. may also be available if the coordinate space has a fixed size.
  31775. @param stringVersion the string to parse
  31776. @param isHorizontal this must be true if this is an X coordinate, or false if it's on the Y axis.
  31777. @see toString
  31778. */
  31779. RelativeCoordinate (const String& stringVersion, bool isHorizontal);
  31780. /** Destructor. */
  31781. ~RelativeCoordinate();
  31782. bool operator== (const RelativeCoordinate& other) const throw();
  31783. bool operator!= (const RelativeCoordinate& other) const throw();
  31784. /**
  31785. Provides an interface for looking up the position of a named anchor when resolving a RelativeCoordinate.
  31786. When using RelativeCoordinates, to resolve their names you need to provide a subclass of this which
  31787. can retrieve a coordinate by name.
  31788. */
  31789. class JUCE_API NamedCoordinateFinder
  31790. {
  31791. public:
  31792. /** Destructor. */
  31793. virtual ~NamedCoordinateFinder() {}
  31794. /** Returns the coordinate for a given name.
  31795. The objectName parameter will be the first section of the name, and the edge the name of the second part.
  31796. E.g. for "parent.right", objectName would be "parent" and edge would be "right". If the name
  31797. has no dot, the edge parameter will be an empty string.
  31798. This method must be able to resolve "parent.left", "parent.top", "parent.right" and "parent.bottom", as
  31799. well as any other objects that your application uses.
  31800. */
  31801. virtual const RelativeCoordinate findNamedCoordinate (const String& objectName, const String& edge) const = 0;
  31802. };
  31803. /** Calculates the absolute position of this coordinate.
  31804. You'll need to provide a suitable NamedCoordinateFinder for looking up any coordinates that may
  31805. be needed to calculate the result.
  31806. */
  31807. double resolve (const NamedCoordinateFinder* nameFinder) const;
  31808. /** Returns true if this coordinate uses the specified coord name at any level in its evaluation.
  31809. This will recursively check any coordinates upon which this one depends.
  31810. */
  31811. bool references (const String& coordName, const NamedCoordinateFinder* nameFinder) const;
  31812. /** Returns true if there's a recursive loop when trying to resolve this coordinate's position. */
  31813. bool isRecursive (const NamedCoordinateFinder* nameFinder) const;
  31814. /** Returns true if this coordinate depends on any other coordinates for its position. */
  31815. bool isDynamic() const;
  31816. /** Changes the value of this coord to make it resolve to the specified position.
  31817. Calling this will leave the anchor points unchanged, but will set this coordinate's absolute
  31818. or relative position to whatever value is necessary to make its resultant position
  31819. match the position that is provided.
  31820. */
  31821. void moveToAbsolute (double absoluteTargetPosition, const NamedCoordinateFinder* nameFinder);
  31822. /** Returns true if the coordinate is calculated as a proportion of the distance between two other points.
  31823. @see toggleProportionality
  31824. */
  31825. bool isProportional() const throw() { return anchor2.isNotEmpty(); }
  31826. /** Toggles the coordinate between using a proportional or absolute position.
  31827. Note that calling this will reset the names of any anchor points, and just make the
  31828. coordinate relative to the parent origin and parent size.
  31829. */
  31830. void toggleProportionality (const NamedCoordinateFinder* nameFinder, bool isHorizontal);
  31831. /** Returns a value that can be edited to set this coordinate's position.
  31832. The meaning of this number depends on the coordinate's mode. If the coordinate is
  31833. proportional, the number will be a percentage between 0 and 100. If the
  31834. coordinate is absolute, then it will be the number of pixels from its anchor point.
  31835. @see setEditableNumber
  31836. */
  31837. const double getEditableNumber() const;
  31838. /** Sets the value that controls this coordinate's position.
  31839. The meaning of this number depends on the coordinate's mode. If the coordinate is
  31840. proportional, the number must be a percentage between 0 and 100. If the
  31841. coordinate is absolute, then it indicates the number of pixels from its anchor point.
  31842. @see setEditableNumber
  31843. */
  31844. void setEditableNumber (const double newValue);
  31845. /** Returns the name of the first anchor point from which this coordinate is relative.
  31846. */
  31847. const String getAnchorName1() const { return anchor1; }
  31848. /** Returns the name of the second anchor point from which this coordinate is relative.
  31849. The second anchor is only valid if the coordinate is in proportional mode.
  31850. */
  31851. const String getAnchorName2() const { return anchor2; }
  31852. /** Returns the first anchor point as a coordinate. */
  31853. const RelativeCoordinate getAnchorCoordinate1() const;
  31854. /** Returns the first anchor point as a coordinate.
  31855. The second anchor is only valid if the coordinate is in proportional mode.
  31856. */
  31857. const RelativeCoordinate getAnchorCoordinate2() const;
  31858. /** Changes the first anchor point, keeping the resultant position of this coordinate in
  31859. the same place it was previously.
  31860. */
  31861. void changeAnchor1 (const String& newAnchor, const NamedCoordinateFinder* nameFinder);
  31862. /** Changes the second anchor point, keeping the resultant position of this coordinate in
  31863. the same place it was previously.
  31864. */
  31865. void changeAnchor2 (const String& newAnchor, const NamedCoordinateFinder* nameFinder);
  31866. /** Tells the coordinate that an object is changing its name or being deleted.
  31867. If either of this coordinates anchor points match this name, they will be replaced.
  31868. If the newName string is empty, it indicates that the object is being removed, so if
  31869. this coordinate was using it, the coordinate is changed to be relative to the origin
  31870. instead.
  31871. */
  31872. void renameAnchorIfUsed (const String& oldName, const String& newName,
  31873. const NamedCoordinateFinder* nameFinder);
  31874. /** Returns a string which represents this coordinate.
  31875. For details of the string syntax, see the constructor notes.
  31876. */
  31877. const String toString() const;
  31878. /** A set of static strings that are commonly used by the RelativeCoordinate class.
  31879. As well as avoiding using string literals in your code, using these preset values
  31880. has the advantage that all instances of the same string will share the same, reference-counted
  31881. String object, so if you have thousands of points which all refer to the same
  31882. anchor points, this can save a significant amount of memory allocation.
  31883. */
  31884. struct Strings
  31885. {
  31886. static const String parent; /**< "parent" */
  31887. static const String left; /**< "left" */
  31888. static const String right; /**< "right" */
  31889. static const String top; /**< "top" */
  31890. static const String bottom; /**< "bottom" */
  31891. static const String parentLeft; /**< "parent.left" */
  31892. static const String parentTop; /**< "parent.top" */
  31893. static const String parentRight; /**< "parent.right" */
  31894. static const String parentBottom; /**< "parent.bottom" */
  31895. };
  31896. private:
  31897. String anchor1, anchor2;
  31898. double value;
  31899. double resolve (const NamedCoordinateFinder* nameFinder, int recursionCounter) const;
  31900. static double resolveAnchor (const String& anchorName, const NamedCoordinateFinder* nameFinder, int recursionCounter);
  31901. };
  31902. /**
  31903. An X-Y position stored as a pair of RelativeCoordinate values.
  31904. @see RelativeCoordinate, RelativeRectangle
  31905. */
  31906. class JUCE_API RelativePoint
  31907. {
  31908. public:
  31909. /** Creates a point at the origin. */
  31910. RelativePoint();
  31911. /** Creates an absolute point, relative to the origin. */
  31912. RelativePoint (const Point<float>& absolutePoint);
  31913. /** Creates an absolute point, relative to the origin. */
  31914. RelativePoint (float absoluteX, float absoluteY);
  31915. /** Creates an absolute point from two coordinates. */
  31916. RelativePoint (const RelativeCoordinate& x, const RelativeCoordinate& y);
  31917. /** Creates a point from a stringified representation.
  31918. The string must contain a pair of coordinates, separated by space or a comma. The syntax for the coordinate
  31919. strings is explained in the RelativeCoordinate class.
  31920. @see toString
  31921. */
  31922. RelativePoint (const String& stringVersion);
  31923. bool operator== (const RelativePoint& other) const throw();
  31924. bool operator!= (const RelativePoint& other) const throw();
  31925. /** Calculates the absolute position of this point.
  31926. You'll need to provide a suitable NamedCoordinateFinder for looking up any coordinates that may
  31927. be needed to calculate the result.
  31928. */
  31929. const Point<float> resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const;
  31930. /** Changes the values of this point's coordinates to make it resolve to the specified position.
  31931. Calling this will leave any anchor points unchanged, but will set any absolute
  31932. or relative positions to whatever values are necessary to make the resultant position
  31933. match the position that is provided.
  31934. */
  31935. void moveToAbsolute (const Point<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  31936. /** Returns a string which represents this point.
  31937. This returns a comma-separated pair of coordinates. For details of the string syntax used by the
  31938. coordinates, see the RelativeCoordinate constructor notes.
  31939. The string that is returned can be passed to the RelativePoint constructor to recreate the point.
  31940. */
  31941. const String toString() const;
  31942. /** Tells the point that an object is changing its name or being deleted.
  31943. This calls RelativeCoordinate::renameAnchorIfUsed() on its X and Y coordinates.
  31944. */
  31945. void renameAnchorIfUsed (const String& oldName, const String& newName,
  31946. const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  31947. /** Returns true if this point depends on any other coordinates for its position. */
  31948. bool isDynamic() const;
  31949. // The actual X and Y coords...
  31950. RelativeCoordinate x, y;
  31951. };
  31952. /**
  31953. An rectangle stored as a set of RelativeCoordinate values.
  31954. The rectangle's top, left, bottom and right edge positions are each stored as a RelativeCoordinate.
  31955. @see RelativeCoordinate, RelativePoint
  31956. */
  31957. class JUCE_API RelativeRectangle
  31958. {
  31959. public:
  31960. /** Creates a zero-size rectangle at the origin. */
  31961. RelativeRectangle();
  31962. /** Creates an absolute rectangle, relative to the origin. */
  31963. explicit RelativeRectangle (const Rectangle<float>& rect, const String& componentName);
  31964. /** Creates a rectangle from four coordinates. */
  31965. RelativeRectangle (const RelativeCoordinate& left, const RelativeCoordinate& right,
  31966. const RelativeCoordinate& top, const RelativeCoordinate& bottom);
  31967. /** Creates a rectangle from a stringified representation.
  31968. The string must contain a sequence of 4 coordinates, separated by commas, in the order
  31969. left, top, right, bottom. The syntax for the coordinate strings is explained in the
  31970. RelativeCoordinate class.
  31971. @see toString
  31972. */
  31973. explicit RelativeRectangle (const String& stringVersion);
  31974. bool operator== (const RelativeRectangle& other) const throw();
  31975. bool operator!= (const RelativeRectangle& other) const throw();
  31976. /** Calculates the absolute position of this rectangle.
  31977. You'll need to provide a suitable NamedCoordinateFinder for looking up any coordinates that may
  31978. be needed to calculate the result.
  31979. */
  31980. const Rectangle<float> resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const;
  31981. /** Changes the values of this rectangle's coordinates to make it resolve to the specified position.
  31982. Calling this will leave any anchor points unchanged, but will set any absolute
  31983. or relative positions to whatever values are necessary to make the resultant position
  31984. match the position that is provided.
  31985. */
  31986. void moveToAbsolute (const Rectangle<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  31987. /** Returns a string which represents this point.
  31988. This returns a comma-separated list of coordinates, in the order left, top, right, bottom. For details of
  31989. the string syntax used by the coordinates, see the RelativeCoordinate constructor notes.
  31990. The string that is returned can be passed to the RelativeRectangle constructor to recreate the rectangle.
  31991. */
  31992. const String toString() const;
  31993. /** Tells the rectangle that an object is changing its name or being deleted.
  31994. This calls RelativeCoordinate::renameAnchorIfUsed() on the rectangle's coordinates.
  31995. */
  31996. void renameAnchorIfUsed (const String& oldName, const String& newName,
  31997. const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  31998. // The actual rectangle coords...
  31999. RelativeCoordinate left, right, top, bottom;
  32000. };
  32001. /**
  32002. A path object that consists of RelativePoint coordinates rather than the normal fixed ones.
  32003. One of these paths can be converted into a Path object for drawing and manipulation, but
  32004. unlike a Path, its points can be dynamic instead of just fixed.
  32005. @see RelativePoint, RelativeCoordinate
  32006. */
  32007. class JUCE_API RelativePointPath
  32008. {
  32009. public:
  32010. RelativePointPath();
  32011. RelativePointPath (const RelativePointPath& other);
  32012. RelativePointPath (const ValueTree& drawable);
  32013. RelativePointPath (const Path& path);
  32014. ~RelativePointPath();
  32015. /** Resolves this points in this path and adds them to a normal Path object. */
  32016. void createPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder);
  32017. /** Returns true if the path contains any non-fixed points. */
  32018. bool containsAnyDynamicPoints() const;
  32019. /** Writes the path to this drawable encoding. */
  32020. void writeTo (ValueTree state, UndoManager* undoManager) const;
  32021. /** Quickly swaps the contents of this path with another. */
  32022. void swapWith (RelativePointPath& other) throw();
  32023. /** The types of element that may be contained in this path.
  32024. @see RelativePointPath::ElementBase
  32025. */
  32026. enum ElementType
  32027. {
  32028. nullElement,
  32029. startSubPathElement,
  32030. closeSubPathElement,
  32031. lineToElement,
  32032. quadraticToElement,
  32033. cubicToElement
  32034. };
  32035. /** Base class for the elements that make up a RelativePointPath.
  32036. */
  32037. class JUCE_API ElementBase
  32038. {
  32039. public:
  32040. ElementBase (ElementType type);
  32041. virtual ~ElementBase() {}
  32042. virtual const ValueTree createTree() const = 0;
  32043. virtual void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const = 0;
  32044. virtual RelativePoint* getControlPoints (int& numPoints) = 0;
  32045. const ElementType type;
  32046. private:
  32047. ElementBase (const ElementBase&);
  32048. ElementBase& operator= (const ElementBase&);
  32049. };
  32050. class JUCE_API StartSubPath : public ElementBase
  32051. {
  32052. public:
  32053. StartSubPath (const RelativePoint& pos);
  32054. ~StartSubPath() {}
  32055. const ValueTree createTree() const;
  32056. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32057. RelativePoint* getControlPoints (int& numPoints);
  32058. RelativePoint startPos;
  32059. private:
  32060. StartSubPath (const StartSubPath&);
  32061. StartSubPath& operator= (const StartSubPath&);
  32062. };
  32063. class JUCE_API CloseSubPath : public ElementBase
  32064. {
  32065. public:
  32066. CloseSubPath();
  32067. ~CloseSubPath() {}
  32068. const ValueTree createTree() const;
  32069. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32070. RelativePoint* getControlPoints (int& numPoints);
  32071. private:
  32072. CloseSubPath (const CloseSubPath&);
  32073. CloseSubPath& operator= (const CloseSubPath&);
  32074. };
  32075. class JUCE_API LineTo : public ElementBase
  32076. {
  32077. public:
  32078. LineTo (const RelativePoint& endPoint);
  32079. ~LineTo() {}
  32080. const ValueTree createTree() const;
  32081. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32082. RelativePoint* getControlPoints (int& numPoints);
  32083. RelativePoint endPoint;
  32084. private:
  32085. LineTo (const LineTo&);
  32086. LineTo& operator= (const LineTo&);
  32087. };
  32088. class JUCE_API QuadraticTo : public ElementBase
  32089. {
  32090. public:
  32091. QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint);
  32092. ~QuadraticTo() {}
  32093. const ValueTree createTree() const;
  32094. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32095. RelativePoint* getControlPoints (int& numPoints);
  32096. RelativePoint controlPoints[2];
  32097. private:
  32098. QuadraticTo (const QuadraticTo&);
  32099. QuadraticTo& operator= (const QuadraticTo&);
  32100. };
  32101. class JUCE_API CubicTo : public ElementBase
  32102. {
  32103. public:
  32104. CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint);
  32105. ~CubicTo() {}
  32106. const ValueTree createTree() const;
  32107. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32108. RelativePoint* getControlPoints (int& numPoints);
  32109. RelativePoint controlPoints[3];
  32110. private:
  32111. CubicTo (const CubicTo&);
  32112. CubicTo& operator= (const CubicTo&);
  32113. };
  32114. OwnedArray <ElementBase> elements;
  32115. bool usesNonZeroWinding;
  32116. private:
  32117. bool containsDynamicPoints;
  32118. void parse (const ValueTree& state);
  32119. RelativePointPath& operator= (const RelativePointPath&);
  32120. };
  32121. /**
  32122. A parallelogram defined by three RelativePoint positions.
  32123. @see RelativePoint, RelativeCoordinate
  32124. */
  32125. class JUCE_API RelativeParallelogram
  32126. {
  32127. public:
  32128. RelativeParallelogram();
  32129. RelativeParallelogram (const RelativePoint& topLeft, const RelativePoint& topRight, const RelativePoint& bottomLeft);
  32130. RelativeParallelogram (const String& topLeft, const String& topRight, const String& bottomLeft);
  32131. ~RelativeParallelogram();
  32132. void resolveThreePoints (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32133. void resolveFourCorners (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32134. const Rectangle<float> getBounds (RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32135. void getPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32136. const AffineTransform resetToPerpendicular (RelativeCoordinate::NamedCoordinateFinder* coordFinder);
  32137. bool operator== (const RelativeParallelogram& other) const throw();
  32138. bool operator!= (const RelativeParallelogram& other) const throw();
  32139. static const Point<float> getInternalCoordForPoint (const Point<float>* parallelogramCorners, Point<float> point) throw();
  32140. static const Point<float> getPointForInternalCoord (const Point<float>* parallelogramCorners, const Point<float>& internalPoint) throw();
  32141. RelativePoint topLeft, topRight, bottomLeft;
  32142. };
  32143. #endif // __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  32144. /*** End of inlined file: juce_RelativeCoordinate.h ***/
  32145. class DrawableComposite;
  32146. /**
  32147. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  32148. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  32149. */
  32150. class JUCE_API Drawable
  32151. {
  32152. protected:
  32153. /** The base class can't be instantiated directly.
  32154. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  32155. */
  32156. Drawable();
  32157. public:
  32158. /** Destructor. */
  32159. virtual ~Drawable();
  32160. /** Creates a deep copy of this Drawable object.
  32161. Use this to create a new copy of this and any sub-objects in the tree.
  32162. */
  32163. virtual Drawable* createCopy() const = 0;
  32164. /** Renders this Drawable object.
  32165. @see drawWithin
  32166. */
  32167. void draw (Graphics& g, float opacity,
  32168. const AffineTransform& transform = AffineTransform::identity) const;
  32169. /** Renders the Drawable at a given offset within the Graphics context.
  32170. The co-ordinates passed-in are used to translate the object relative to its own
  32171. origin before drawing it - this is basically a quick way of saying:
  32172. @code
  32173. draw (g, AffineTransform::translation (x, y)).
  32174. @endcode
  32175. */
  32176. void drawAt (Graphics& g,
  32177. float x, float y,
  32178. float opacity) const;
  32179. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  32180. changing its aspect-ratio.
  32181. The object can placed arbitrarily within the rectangle based on a Justification type,
  32182. and can either be made as big as possible, or just reduced to fit.
  32183. @param g the graphics context to render onto
  32184. @param destX top-left of the target rectangle to fit it into
  32185. @param destY top-left of the target rectangle to fit it into
  32186. @param destWidth size of the target rectangle to fit the image into
  32187. @param destHeight size of the target rectangle to fit the image into
  32188. @param placement defines the alignment and rescaling to use to fit
  32189. this object within the target rectangle.
  32190. @param opacity the opacity to use, in the range 0 to 1.0
  32191. */
  32192. void drawWithin (Graphics& g,
  32193. int destX,
  32194. int destY,
  32195. int destWidth,
  32196. int destHeight,
  32197. const RectanglePlacement& placement,
  32198. float opacity) const;
  32199. /** Holds the information needed when telling a drawable to render itself.
  32200. @see Drawable::draw
  32201. */
  32202. class RenderingContext
  32203. {
  32204. public:
  32205. RenderingContext (Graphics& g, const AffineTransform& transform, float opacity) throw();
  32206. Graphics& g;
  32207. AffineTransform transform;
  32208. float opacity;
  32209. private:
  32210. RenderingContext& operator= (const RenderingContext&);
  32211. };
  32212. /** Renders this Drawable object.
  32213. @see draw
  32214. */
  32215. virtual void render (const RenderingContext& context) const = 0;
  32216. /** Returns the smallest rectangle that can contain this Drawable object.
  32217. Co-ordinates are relative to the object's own origin.
  32218. */
  32219. virtual const Rectangle<float> getBounds() const = 0;
  32220. /** Returns true if the given point is somewhere inside this Drawable.
  32221. Co-ordinates are relative to the object's own origin.
  32222. */
  32223. virtual bool hitTest (float x, float y) const = 0;
  32224. /** Returns the name given to this drawable.
  32225. @see setName
  32226. */
  32227. const String& getName() const throw() { return name; }
  32228. /** Assigns a name to this drawable. */
  32229. void setName (const String& newName) throw() { name = newName; }
  32230. /** Returns the DrawableComposite that contains this object, if there is one. */
  32231. DrawableComposite* getParent() const throw() { return parent; }
  32232. /** Tries to turn some kind of image file into a drawable.
  32233. The data could be an image that the ImageFileFormat class understands, or it
  32234. could be SVG.
  32235. */
  32236. static Drawable* createFromImageData (const void* data, size_t numBytes);
  32237. /** Tries to turn a stream containing some kind of image data into a drawable.
  32238. The data could be an image that the ImageFileFormat class understands, or it
  32239. could be SVG.
  32240. */
  32241. static Drawable* createFromImageDataStream (InputStream& dataSource);
  32242. /** Tries to turn a file containing some kind of image data into a drawable.
  32243. The data could be an image that the ImageFileFormat class understands, or it
  32244. could be SVG.
  32245. */
  32246. static Drawable* createFromImageFile (const File& file);
  32247. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  32248. into a Drawable tree.
  32249. The object returned must be deleted by the caller. If something goes wrong
  32250. while parsing, it may return 0.
  32251. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  32252. implementation, but it can return the basic vector objects.
  32253. */
  32254. static Drawable* createFromSVG (const XmlElement& svgDocument);
  32255. /** This class is used when loading Drawables that contain images, and retrieves
  32256. the image for a stored identifier.
  32257. @see Drawable::createFromValueTree
  32258. */
  32259. class JUCE_API ImageProvider
  32260. {
  32261. public:
  32262. ImageProvider() {}
  32263. virtual ~ImageProvider() {}
  32264. /** Retrieves the image associated with this identifier, which could be any
  32265. kind of string, number, filename, etc.
  32266. The image that is returned will be owned by the caller, but it may come
  32267. from the ImageCache.
  32268. */
  32269. virtual const Image getImageForIdentifier (const var& imageIdentifier) = 0;
  32270. /** Returns an identifier to be used to refer to a given image.
  32271. This is used when converting a drawable into a ValueTree, so if you're
  32272. only loading drawables, you can just return a var::null here.
  32273. */
  32274. virtual const var getIdentifierForImage (const Image& image) = 0;
  32275. };
  32276. /** Tries to create a Drawable from a previously-saved ValueTree.
  32277. The ValueTree must have been created by the createValueTree() method.
  32278. If there are any images used within the drawable, you'll need to provide a valid
  32279. ImageProvider object that can be used to retrieve these images from whatever type
  32280. of identifier is used to represent them.
  32281. */
  32282. static Drawable* createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  32283. /** Tries to refresh a Drawable from the same ValueTree that was used to create it.
  32284. @returns the damage rectangle that will need repainting due to any changes that were made.
  32285. */
  32286. virtual const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider) = 0;
  32287. /** Creates a ValueTree to represent this Drawable.
  32288. The VarTree that is returned can be turned back into a Drawable with
  32289. createFromValueTree().
  32290. If there are any images used in this drawable, you'll need to provide a valid
  32291. ImageProvider object that can be used to create storable representations of them.
  32292. */
  32293. virtual const ValueTree createValueTree (ImageProvider* imageProvider) const = 0;
  32294. /** Returns the tag ID that is used for a ValueTree that stores this type of drawable. */
  32295. virtual const Identifier getValueTreeType() const = 0;
  32296. /** Internal class used to manage ValueTrees that represent Drawables. */
  32297. class ValueTreeWrapperBase
  32298. {
  32299. public:
  32300. ValueTreeWrapperBase (const ValueTree& state);
  32301. ~ValueTreeWrapperBase();
  32302. ValueTree& getState() throw() { return state; }
  32303. const String getID() const;
  32304. void setID (const String& newID, UndoManager* undoManager);
  32305. static const Identifier idProperty;
  32306. static const FillType readFillType (const ValueTree& v, RelativePoint* gradientPoint1, RelativePoint* gradientPoint2,
  32307. RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  32308. ImageProvider* imageProvider);
  32309. static void writeFillType (ValueTree& v, const FillType& fillType,
  32310. const RelativePoint* gradientPoint1, const RelativePoint* gradientPoint2,
  32311. ImageProvider* imageProvider,
  32312. UndoManager* undoManager);
  32313. ValueTree state;
  32314. static const Identifier type, gradientPoint1, gradientPoint2, colour, radial, colours, imageId, imageOpacity;
  32315. };
  32316. juce_UseDebuggingNewOperator
  32317. protected:
  32318. friend class DrawableComposite;
  32319. DrawableComposite* parent;
  32320. virtual void invalidatePoints() = 0;
  32321. static Drawable* createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider);
  32322. private:
  32323. String name;
  32324. Drawable (const Drawable&);
  32325. Drawable& operator= (const Drawable&);
  32326. };
  32327. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  32328. /*** End of inlined file: juce_Drawable.h ***/
  32329. /**
  32330. A button that displays a Drawable.
  32331. Up to three Drawable objects can be given to this button, to represent the
  32332. 'normal', 'over' and 'down' states.
  32333. @see Button
  32334. */
  32335. class JUCE_API DrawableButton : public Button
  32336. {
  32337. public:
  32338. enum ButtonStyle
  32339. {
  32340. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  32341. ImageRaw, /**< The button will just display the images in their normal size and position.
  32342. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  32343. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  32344. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  32345. };
  32346. /** Creates a DrawableButton.
  32347. After creating one of these, use setImages() to specify the drawables to use.
  32348. @param buttonName the name to give the component
  32349. @param buttonStyle the layout to use
  32350. @see ButtonStyle, setButtonStyle, setImages
  32351. */
  32352. DrawableButton (const String& buttonName,
  32353. ButtonStyle buttonStyle);
  32354. /** Destructor. */
  32355. ~DrawableButton();
  32356. /** Sets up the images to draw for the various button states.
  32357. The button will keep its own internal copies of these drawables.
  32358. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  32359. will be made of the object passed-in if it is non-zero.
  32360. @param overImage the thing to draw for the button's 'over' state - if this is
  32361. zero, the button's normal image will be used when the mouse is
  32362. over it. An internal copy will be made of the object passed-in
  32363. if it is non-zero.
  32364. @param downImage the thing to draw for the button's 'down' state - if this is
  32365. zero, the 'over' image will be used instead (or the normal image
  32366. as a last resort). An internal copy will be made of the object
  32367. passed-in if it is non-zero.
  32368. @param disabledImage an image to draw when the button is disabled. If this is zero,
  32369. the normal image will be drawn with a reduced opacity instead.
  32370. An internal copy will be made of the object passed-in if it is
  32371. non-zero.
  32372. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  32373. state is 'on'. If this is 0, the normal image is used instead
  32374. @param overImageOn same as the overImage, but this is used when the button's toggle
  32375. state is 'on'. If this is 0, the normalImageOn is drawn instead
  32376. @param downImageOn same as the downImage, but this is used when the button's toggle
  32377. state is 'on'. If this is 0, the overImageOn is drawn instead
  32378. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  32379. state is 'on'. If this is 0, the normal image will be drawn instead
  32380. with a reduced opacity
  32381. */
  32382. void setImages (const Drawable* normalImage,
  32383. const Drawable* overImage = 0,
  32384. const Drawable* downImage = 0,
  32385. const Drawable* disabledImage = 0,
  32386. const Drawable* normalImageOn = 0,
  32387. const Drawable* overImageOn = 0,
  32388. const Drawable* downImageOn = 0,
  32389. const Drawable* disabledImageOn = 0);
  32390. /** Changes the button's style.
  32391. @see ButtonStyle
  32392. */
  32393. void setButtonStyle (ButtonStyle newStyle);
  32394. /** Changes the button's background colours.
  32395. The toggledOffColour is the colour to use when the button's toggle state
  32396. is off, and toggledOnColour when it's on.
  32397. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  32398. used to fill the background of the component.
  32399. For an ImageOnButtonBackground style, the colour is used to draw the
  32400. button's lozenge shape and exactly how the colour's used will depend
  32401. on the LookAndFeel.
  32402. */
  32403. void setBackgroundColours (const Colour& toggledOffColour,
  32404. const Colour& toggledOnColour);
  32405. /** Returns the current background colour being used.
  32406. @see setBackgroundColour
  32407. */
  32408. const Colour& getBackgroundColour() const throw();
  32409. /** Gives the button an optional amount of space around the edge of the drawable.
  32410. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  32411. ones on a button background. If the button is too small for the given gap, a
  32412. smaller gap will be used.
  32413. By default there's a gap of about 3 pixels.
  32414. */
  32415. void setEdgeIndent (int numPixelsIndent);
  32416. /** Returns the image that the button is currently displaying. */
  32417. const Drawable* getCurrentImage() const throw();
  32418. const Drawable* getNormalImage() const throw();
  32419. const Drawable* getOverImage() const throw();
  32420. const Drawable* getDownImage() const throw();
  32421. juce_UseDebuggingNewOperator
  32422. protected:
  32423. /** @internal */
  32424. void paintButton (Graphics& g,
  32425. bool isMouseOverButton,
  32426. bool isButtonDown);
  32427. private:
  32428. ButtonStyle style;
  32429. ScopedPointer <Drawable> normalImage, overImage, downImage, disabledImage;
  32430. ScopedPointer <Drawable> normalImageOn, overImageOn, downImageOn, disabledImageOn;
  32431. Colour backgroundOff, backgroundOn;
  32432. int edgeIndent;
  32433. void deleteImages();
  32434. DrawableButton (const DrawableButton&);
  32435. DrawableButton& operator= (const DrawableButton&);
  32436. };
  32437. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  32438. /*** End of inlined file: juce_DrawableButton.h ***/
  32439. #endif
  32440. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32441. /*** Start of inlined file: juce_HyperlinkButton.h ***/
  32442. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32443. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32444. /**
  32445. A button showing an underlined weblink, that will launch the link
  32446. when it's clicked.
  32447. @see Button
  32448. */
  32449. class JUCE_API HyperlinkButton : public Button
  32450. {
  32451. public:
  32452. /** Creates a HyperlinkButton.
  32453. @param linkText the text that will be displayed in the button - this is
  32454. also set as the Component's name, but the text can be
  32455. changed later with the Button::getButtonText() method
  32456. @param linkURL the URL to launch when the user clicks the button
  32457. */
  32458. HyperlinkButton (const String& linkText,
  32459. const URL& linkURL);
  32460. /** Destructor. */
  32461. ~HyperlinkButton();
  32462. /** Changes the font to use for the text.
  32463. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  32464. to match the size of the component.
  32465. */
  32466. void setFont (const Font& newFont,
  32467. bool resizeToMatchComponentHeight,
  32468. const Justification& justificationType = Justification::horizontallyCentred);
  32469. /** A set of colour IDs to use to change the colour of various aspects of the link.
  32470. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32471. methods.
  32472. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32473. */
  32474. enum ColourIds
  32475. {
  32476. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  32477. };
  32478. /** Changes the URL that the button will trigger. */
  32479. void setURL (const URL& newURL) throw();
  32480. /** Returns the URL that the button will trigger. */
  32481. const URL& getURL() const throw() { return url; }
  32482. /** Resizes the button horizontally to fit snugly around the text.
  32483. This won't affect the button's height.
  32484. */
  32485. void changeWidthToFitText();
  32486. juce_UseDebuggingNewOperator
  32487. protected:
  32488. /** @internal */
  32489. void clicked();
  32490. /** @internal */
  32491. void colourChanged();
  32492. /** @internal */
  32493. void paintButton (Graphics& g,
  32494. bool isMouseOverButton,
  32495. bool isButtonDown);
  32496. private:
  32497. URL url;
  32498. Font font;
  32499. bool resizeFont;
  32500. Justification justification;
  32501. const Font getFontToUse() const;
  32502. HyperlinkButton (const HyperlinkButton&);
  32503. HyperlinkButton& operator= (const HyperlinkButton&);
  32504. };
  32505. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32506. /*** End of inlined file: juce_HyperlinkButton.h ***/
  32507. #endif
  32508. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  32509. /*** Start of inlined file: juce_ImageButton.h ***/
  32510. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  32511. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  32512. /**
  32513. As the title suggests, this is a button containing an image.
  32514. The colour and transparency of the image can be set to vary when the
  32515. button state changes.
  32516. @see Button, ShapeButton, TextButton
  32517. */
  32518. class JUCE_API ImageButton : public Button
  32519. {
  32520. public:
  32521. /** Creates an ImageButton.
  32522. Use setImage() to specify the image to use. The colours and opacities that
  32523. are specified here can be changed later using setDrawingOptions().
  32524. @param name the name to give the component
  32525. */
  32526. explicit ImageButton (const String& name);
  32527. /** Destructor. */
  32528. ~ImageButton();
  32529. /** Sets up the images to draw in various states.
  32530. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  32531. resized to the same dimensions as the normal image
  32532. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  32533. button when the button's size changes
  32534. @param preserveImageProportions if true then any rescaling of the image to fit
  32535. the button will keep the image's x and y proportions
  32536. correct - i.e. it won't distort its shape, although
  32537. this might create gaps around the edges
  32538. @param normalImage the image to use when the button is in its normal state.
  32539. button no longer needs it.
  32540. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  32541. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  32542. normal image - if this colour is transparent, no overlay
  32543. will be drawn. The overlay will be drawn over the top of the
  32544. image, so you can basically add a solid or semi-transparent
  32545. colour to the image to brighten or darken it
  32546. @param overImage the image to use when the mouse is over the button. If
  32547. you want to use the same image as was set in the normalImage
  32548. parameter, this value can be a null image.
  32549. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  32550. is over the button
  32551. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  32552. image when the mouse is over - if this colour is transparent,
  32553. no overlay will be drawn
  32554. @param downImage an image to use when the button is pressed down. If set
  32555. to a null image, the 'over' image will be drawn instead (or the
  32556. normal image if there isn't an 'over' image either).
  32557. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  32558. is pressed
  32559. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  32560. image when the button is pressed down - if this colour is
  32561. transparent, no overlay will be drawn
  32562. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  32563. whenever it's inside the button's bounding rectangle. If
  32564. set to values higher than 0, the mouse will only be
  32565. considered to be over the image when the value of the
  32566. image's alpha channel at that position is greater than
  32567. this level.
  32568. */
  32569. void setImages (bool resizeButtonNowToFitThisImage,
  32570. bool rescaleImagesWhenButtonSizeChanges,
  32571. bool preserveImageProportions,
  32572. const Image& normalImage,
  32573. float imageOpacityWhenNormal,
  32574. const Colour& overlayColourWhenNormal,
  32575. const Image& overImage,
  32576. float imageOpacityWhenOver,
  32577. const Colour& overlayColourWhenOver,
  32578. const Image& downImage,
  32579. float imageOpacityWhenDown,
  32580. const Colour& overlayColourWhenDown,
  32581. float hitTestAlphaThreshold = 0.0f);
  32582. /** Returns the currently set 'normal' image. */
  32583. const Image getNormalImage() const;
  32584. /** Returns the image that's drawn when the mouse is over the button.
  32585. If a valid 'over' image has been set, this will return it; otherwise it'll
  32586. just return the normal image.
  32587. */
  32588. const Image getOverImage() const;
  32589. /** Returns the image that's drawn when the button is held down.
  32590. If a valid 'down' image has been set, this will return it; otherwise it'll
  32591. return the 'over' image or normal image, depending on what's available.
  32592. */
  32593. const Image getDownImage() const;
  32594. juce_UseDebuggingNewOperator
  32595. protected:
  32596. /** @internal */
  32597. bool hitTest (int x, int y);
  32598. /** @internal */
  32599. void paintButton (Graphics& g,
  32600. bool isMouseOverButton,
  32601. bool isButtonDown);
  32602. private:
  32603. bool scaleImageToFit, preserveProportions;
  32604. unsigned char alphaThreshold;
  32605. int imageX, imageY, imageW, imageH;
  32606. Image normalImage, overImage, downImage;
  32607. float normalOpacity, overOpacity, downOpacity;
  32608. Colour normalOverlay, overOverlay, downOverlay;
  32609. const Image getCurrentImage() const;
  32610. ImageButton (const ImageButton&);
  32611. ImageButton& operator= (const ImageButton&);
  32612. };
  32613. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  32614. /*** End of inlined file: juce_ImageButton.h ***/
  32615. #endif
  32616. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  32617. /*** Start of inlined file: juce_ShapeButton.h ***/
  32618. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  32619. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  32620. /**
  32621. A button that contains a filled shape.
  32622. @see Button, ImageButton, TextButton, ArrowButton
  32623. */
  32624. class JUCE_API ShapeButton : public Button
  32625. {
  32626. public:
  32627. /** Creates a ShapeButton.
  32628. @param name a name to give the component - see Component::setName()
  32629. @param normalColour the colour to fill the shape with when the mouse isn't over
  32630. @param overColour the colour to use when the mouse is over the shape
  32631. @param downColour the colour to use when the button is in the pressed-down state
  32632. */
  32633. ShapeButton (const String& name,
  32634. const Colour& normalColour,
  32635. const Colour& overColour,
  32636. const Colour& downColour);
  32637. /** Destructor. */
  32638. ~ShapeButton();
  32639. /** Sets the shape to use.
  32640. @param newShape the shape to use
  32641. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  32642. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  32643. the button is resized
  32644. @param hasDropShadow if true, the button will be given a drop-shadow effect
  32645. */
  32646. void setShape (const Path& newShape,
  32647. bool resizeNowToFitThisShape,
  32648. bool maintainShapeProportions,
  32649. bool hasDropShadow);
  32650. /** Set the colours to use for drawing the shape.
  32651. @param normalColour the colour to fill the shape with when the mouse isn't over
  32652. @param overColour the colour to use when the mouse is over the shape
  32653. @param downColour the colour to use when the button is in the pressed-down state
  32654. */
  32655. void setColours (const Colour& normalColour,
  32656. const Colour& overColour,
  32657. const Colour& downColour);
  32658. /** Sets up an outline to draw around the shape.
  32659. @param outlineColour the colour to use
  32660. @param outlineStrokeWidth the thickness of line to draw
  32661. */
  32662. void setOutline (const Colour& outlineColour,
  32663. float outlineStrokeWidth);
  32664. juce_UseDebuggingNewOperator
  32665. protected:
  32666. /** @internal */
  32667. void paintButton (Graphics& g,
  32668. bool isMouseOverButton,
  32669. bool isButtonDown);
  32670. private:
  32671. Colour normalColour, overColour, downColour, outlineColour;
  32672. DropShadowEffect shadow;
  32673. Path shape;
  32674. bool maintainShapeProportions;
  32675. float outlineWidth;
  32676. ShapeButton (const ShapeButton&);
  32677. ShapeButton& operator= (const ShapeButton&);
  32678. };
  32679. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  32680. /*** End of inlined file: juce_ShapeButton.h ***/
  32681. #endif
  32682. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  32683. #endif
  32684. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  32685. /*** Start of inlined file: juce_ToggleButton.h ***/
  32686. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  32687. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  32688. /**
  32689. A button that can be toggled on/off.
  32690. All buttons can be toggle buttons, but this lets you create one of the
  32691. standard ones which has a tick-box and a text label next to it.
  32692. @see Button, DrawableButton, TextButton
  32693. */
  32694. class JUCE_API ToggleButton : public Button
  32695. {
  32696. public:
  32697. /** Creates a ToggleButton.
  32698. @param buttonText the text to put in the button (the component's name is also
  32699. initially set to this string, but these can be changed later
  32700. using the setName() and setButtonText() methods)
  32701. */
  32702. explicit ToggleButton (const String& buttonText = String::empty);
  32703. /** Destructor. */
  32704. ~ToggleButton();
  32705. /** Resizes the button to fit neatly around its current text.
  32706. The button's height won't be affected, only its width.
  32707. */
  32708. void changeWidthToFitText();
  32709. /** A set of colour IDs to use to change the colour of various aspects of the button.
  32710. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32711. methods.
  32712. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32713. */
  32714. enum ColourIds
  32715. {
  32716. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  32717. };
  32718. juce_UseDebuggingNewOperator
  32719. protected:
  32720. /** @internal */
  32721. void paintButton (Graphics& g,
  32722. bool isMouseOverButton,
  32723. bool isButtonDown);
  32724. /** @internal */
  32725. void colourChanged();
  32726. private:
  32727. ToggleButton (const ToggleButton&);
  32728. ToggleButton& operator= (const ToggleButton&);
  32729. };
  32730. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  32731. /*** End of inlined file: juce_ToggleButton.h ***/
  32732. #endif
  32733. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  32734. /*** Start of inlined file: juce_ToolbarButton.h ***/
  32735. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  32736. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  32737. /*** Start of inlined file: juce_ToolbarItemComponent.h ***/
  32738. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  32739. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  32740. /*** Start of inlined file: juce_Toolbar.h ***/
  32741. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  32742. #define __JUCE_TOOLBAR_JUCEHEADER__
  32743. /*** Start of inlined file: juce_DragAndDropContainer.h ***/
  32744. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  32745. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  32746. /*** Start of inlined file: juce_DragAndDropTarget.h ***/
  32747. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  32748. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  32749. /**
  32750. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  32751. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  32752. derive your component from this class, and make sure that it is somewhere inside a
  32753. DragAndDropContainer component.
  32754. Note: If all that you need to do is to respond to files being drag-and-dropped from
  32755. the operating system onto your component, you don't need any of these classes: instead
  32756. see the FileDragAndDropTarget class.
  32757. @see DragAndDropContainer, FileDragAndDropTarget
  32758. */
  32759. class JUCE_API DragAndDropTarget
  32760. {
  32761. public:
  32762. /** Destructor. */
  32763. virtual ~DragAndDropTarget() {}
  32764. /** Callback to check whether this target is interested in the type of object being
  32765. dragged.
  32766. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32767. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32768. @returns true if this component wants to receive the other callbacks regarging this
  32769. type of object; if it returns false, no other callbacks will be made.
  32770. */
  32771. virtual bool isInterestedInDragSource (const String& sourceDescription,
  32772. Component* sourceComponent) = 0;
  32773. /** Callback to indicate that something is being dragged over this component.
  32774. This gets called when the user moves the mouse into this component while dragging
  32775. something.
  32776. Use this callback as a trigger to make your component repaint itself to give the
  32777. user feedback about whether the item can be dropped here or not.
  32778. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32779. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32780. @param x the mouse x position, relative to this component
  32781. @param y the mouse y position, relative to this component
  32782. @see itemDragExit
  32783. */
  32784. virtual void itemDragEnter (const String& sourceDescription,
  32785. Component* sourceComponent,
  32786. int x, int y);
  32787. /** Callback to indicate that the user is dragging something over this component.
  32788. This gets called when the user moves the mouse over this component while dragging
  32789. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  32790. this lets you know what happens in-between.
  32791. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32792. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32793. @param x the mouse x position, relative to this component
  32794. @param y the mouse y position, relative to this component
  32795. */
  32796. virtual void itemDragMove (const String& sourceDescription,
  32797. Component* sourceComponent,
  32798. int x, int y);
  32799. /** Callback to indicate that something has been dragged off the edge of this component.
  32800. This gets called when the user moves the mouse out of this component while dragging
  32801. something.
  32802. If you've used itemDragEnter() to repaint your component and give feedback, use this
  32803. as a signal to repaint it in its normal state.
  32804. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32805. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32806. @see itemDragEnter
  32807. */
  32808. virtual void itemDragExit (const String& sourceDescription,
  32809. Component* sourceComponent);
  32810. /** Callback to indicate that the user has dropped something onto this component.
  32811. When the user drops an item this get called, and you can use the description to
  32812. work out whether your object wants to deal with it or not.
  32813. Note that after this is called, the itemDragExit method may not be called, so you should
  32814. clean up in here if there's anything you need to do when the drag finishes.
  32815. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32816. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32817. @param x the mouse x position, relative to this component
  32818. @param y the mouse y position, relative to this component
  32819. */
  32820. virtual void itemDropped (const String& sourceDescription,
  32821. Component* sourceComponent,
  32822. int x, int y) = 0;
  32823. /** Overriding this allows the target to tell the drag container whether to
  32824. draw the drag image while the cursor is over it.
  32825. By default it returns true, but if you return false, then the normal drag
  32826. image will not be shown when the cursor is over this target.
  32827. */
  32828. virtual bool shouldDrawDragImageWhenOver();
  32829. };
  32830. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  32831. /*** End of inlined file: juce_DragAndDropTarget.h ***/
  32832. /**
  32833. Enables drag-and-drop behaviour for a component and all its sub-components.
  32834. For a component to be able to make or receive drag-and-drop events, one of its parent
  32835. components must derive from this class. It's probably best for the top-level
  32836. component to implement it.
  32837. Then to start a drag operation, any sub-component can just call the startDragging()
  32838. method, and this object will take over, tracking the mouse and sending appropriate
  32839. callbacks to any child components derived from DragAndDropTarget which the mouse
  32840. moves over.
  32841. Note: If all that you need to do is to respond to files being drag-and-dropped from
  32842. the operating system onto your component, you don't need any of these classes: you can do this
  32843. simply by overriding Component::filesDropped().
  32844. @see DragAndDropTarget
  32845. */
  32846. class JUCE_API DragAndDropContainer
  32847. {
  32848. public:
  32849. /** Creates a DragAndDropContainer.
  32850. The object that derives from this class must also be a Component.
  32851. */
  32852. DragAndDropContainer();
  32853. /** Destructor. */
  32854. virtual ~DragAndDropContainer();
  32855. /** Begins a drag-and-drop operation.
  32856. This starts a drag-and-drop operation - call it when the user drags the
  32857. mouse in your drag-source component, and this object will track mouse
  32858. movements until the user lets go of the mouse button, and will send
  32859. appropriate messages to DragAndDropTarget objects that the mouse moves
  32860. over.
  32861. findParentDragContainerFor() is a handy method to call to find the
  32862. drag container to use for a component.
  32863. @param sourceDescription a string to use as the description of the thing being
  32864. dragged - this will be passed to the objects that might be
  32865. dropped-onto so they can decide if they want to handle it or
  32866. not
  32867. @param sourceComponent the component that is being dragged
  32868. @param dragImage the image to drag around underneath the mouse. If this is a null image,
  32869. a snapshot of the sourceComponent will be used instead.
  32870. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  32871. window, and can be dragged to DragAndDropTargets that are the
  32872. children of components other than this one.
  32873. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  32874. at which the image should be drawn from the mouse. If it isn't
  32875. specified, then the image will be centred around the mouse. If
  32876. an image hasn't been passed-in, this will be ignored.
  32877. */
  32878. void startDragging (const String& sourceDescription,
  32879. Component* sourceComponent,
  32880. const Image& dragImage = Image(),
  32881. bool allowDraggingToOtherJuceWindows = false,
  32882. const Point<int>* imageOffsetFromMouse = 0);
  32883. /** Returns true if something is currently being dragged. */
  32884. bool isDragAndDropActive() const;
  32885. /** Returns the description of the thing that's currently being dragged.
  32886. If nothing's being dragged, this will return an empty string, otherwise it's the
  32887. string that was passed into startDragging().
  32888. @see startDragging
  32889. */
  32890. const String getCurrentDragDescription() const;
  32891. /** Utility to find the DragAndDropContainer for a given Component.
  32892. This will search up this component's parent hierarchy looking for the first
  32893. parent component which is a DragAndDropContainer.
  32894. It's useful when a component wants to call startDragging but doesn't know
  32895. the DragAndDropContainer it should to use.
  32896. Obviously this may return 0 if it doesn't find a suitable component.
  32897. */
  32898. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  32899. /** This performs a synchronous drag-and-drop of a set of files to some external
  32900. application.
  32901. You can call this function in response to a mouseDrag callback, and it will
  32902. block, running its own internal message loop and tracking the mouse, while it
  32903. uses a native operating system drag-and-drop operation to move or copy some
  32904. files to another application.
  32905. @param files a list of filenames to drag
  32906. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  32907. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  32908. @returns true if the files were successfully dropped somewhere, or false if it
  32909. was interrupted
  32910. @see performExternalDragDropOfText
  32911. */
  32912. static bool performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles);
  32913. /** This performs a synchronous drag-and-drop of a block of text to some external
  32914. application.
  32915. You can call this function in response to a mouseDrag callback, and it will
  32916. block, running its own internal message loop and tracking the mouse, while it
  32917. uses a native operating system drag-and-drop operation to move or copy some
  32918. text to another application.
  32919. @param text the text to copy
  32920. @returns true if the text was successfully dropped somewhere, or false if it
  32921. was interrupted
  32922. @see performExternalDragDropOfFiles
  32923. */
  32924. static bool performExternalDragDropOfText (const String& text);
  32925. juce_UseDebuggingNewOperator
  32926. protected:
  32927. /** Override this if you want to be able to perform an external drag a set of files
  32928. when the user drags outside of this container component.
  32929. This method will be called when a drag operation moves outside the Juce-based window,
  32930. and if you want it to then perform a file drag-and-drop, add the filenames you want
  32931. to the array passed in, and return true.
  32932. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  32933. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  32934. @param files on return, the filenames you want to drag
  32935. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  32936. it must make a copy of them (see the performExternalDragDropOfFiles()
  32937. method)
  32938. @see performExternalDragDropOfFiles
  32939. */
  32940. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  32941. Component* dragSourceComponent,
  32942. StringArray& files,
  32943. bool& canMoveFiles);
  32944. private:
  32945. friend class DragImageComponent;
  32946. ScopedPointer <Component> dragImageComponent;
  32947. String currentDragDesc;
  32948. };
  32949. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  32950. /*** End of inlined file: juce_DragAndDropContainer.h ***/
  32951. /*** Start of inlined file: juce_ComponentAnimator.h ***/
  32952. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  32953. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  32954. /**
  32955. Animates a set of components, moving it to a new position.
  32956. To use this, create a ComponentAnimator, and use its animateComponent() method
  32957. to tell it to move components to destination positions. Any number of
  32958. components can be animated by one ComponentAnimator object (if you've got a
  32959. lot of components to move, it's much more efficient to share a single animator
  32960. than to have many animators running at once).
  32961. You'll need to make sure the animator object isn't deleted before it finishes
  32962. moving the components.
  32963. The class is a ChangeBroadcaster and sends a notification when any components
  32964. start or finish being animated.
  32965. */
  32966. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  32967. private Timer
  32968. {
  32969. public:
  32970. /** Creates a ComponentAnimator. */
  32971. ComponentAnimator();
  32972. /** Destructor. */
  32973. ~ComponentAnimator();
  32974. /** Starts a component moving from its current position to a specified position.
  32975. If the component is already in the middle of an animation, that will be abandoned,
  32976. and a new animation will begin, moving the component from its current location.
  32977. The start and end speed parameters let you apply some acceleration to the component's
  32978. movement.
  32979. @param component the component to move
  32980. @param finalPosition the destination position and size to move it to
  32981. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  32982. to arrive at its destination
  32983. @param startSpeed a value to indicate the relative start speed of the
  32984. animation. If this is 0, the component will start
  32985. by accelerating from rest; higher values mean that it
  32986. will have an initial speed greater than zero. If the
  32987. value if greater than 1, it will decelerate towards the
  32988. middle of its journey. To move the component at a constant
  32989. rate for its entire animation, set both the start and
  32990. end speeds to 1.0
  32991. @param endSpeed a relative speed at which the component should be moving
  32992. when the animation finishes. If this is 0, the component
  32993. will decelerate to a standstill at its final position; higher
  32994. values mean the component will still be moving when it stops.
  32995. To move the component at a constant rate for its entire
  32996. animation, set both the start and end speeds to 1.0
  32997. */
  32998. void animateComponent (Component* component,
  32999. const Rectangle<int>& finalPosition,
  33000. int millisecondsToSpendMoving,
  33001. double startSpeed = 1.0,
  33002. double endSpeed = 1.0);
  33003. /** Stops a component if it's currently being animated.
  33004. If moveComponentToItsFinalPosition is true, then the component will
  33005. be immediately moved to its destination position and size. If false, it will be
  33006. left in whatever location it currently occupies.
  33007. */
  33008. void cancelAnimation (Component* component,
  33009. bool moveComponentToItsFinalPosition);
  33010. /** Clears all of the active animations.
  33011. If moveComponentsToTheirFinalPositions is true, all the components will
  33012. be immediately set to their final positions. If false, they will be
  33013. left in whatever locations they currently occupy.
  33014. */
  33015. void cancelAllAnimations (bool moveComponentsToTheirFinalPositions);
  33016. /** Returns the destination position for a component.
  33017. If the component is being animated, this will return the target position that
  33018. was specified when animateComponent() was called.
  33019. If the specified component isn't currently being animated, this method will just
  33020. return its current position.
  33021. */
  33022. const Rectangle<int> getComponentDestination (Component* component);
  33023. /** Returns true if the specified component is currently being animated.
  33024. */
  33025. bool isAnimating (Component* component) const;
  33026. juce_UseDebuggingNewOperator
  33027. private:
  33028. class AnimationTask;
  33029. Array <AnimationTask*> tasks;
  33030. uint32 lastTime;
  33031. AnimationTask* findTaskFor (Component* component) const;
  33032. void timerCallback();
  33033. };
  33034. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  33035. /*** End of inlined file: juce_ComponentAnimator.h ***/
  33036. class ToolbarItemComponent;
  33037. class ToolbarItemFactory;
  33038. class MissingItemsComponent;
  33039. /**
  33040. A toolbar component.
  33041. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  33042. and looks after their order and layout.
  33043. Items (icon buttons or other custom components) are added to a toolbar using a
  33044. ToolbarItemFactory - each type of item is given a unique ID number, and a
  33045. toolbar might contain more than one instance of a particular item type.
  33046. Toolbars can be interactively customised, allowing the user to drag the items
  33047. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  33048. component as a source of new items.
  33049. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  33050. */
  33051. class JUCE_API Toolbar : public Component,
  33052. public DragAndDropContainer,
  33053. public DragAndDropTarget,
  33054. private ButtonListener
  33055. {
  33056. public:
  33057. /** Creates an empty toolbar component.
  33058. To add some icons or other components to your toolbar, you'll need to
  33059. create a ToolbarItemFactory class that can create a suitable set of
  33060. ToolbarItemComponents.
  33061. @see ToolbarItemFactory, ToolbarItemComponents
  33062. */
  33063. Toolbar();
  33064. /** Destructor.
  33065. Any items on the bar will be deleted when the toolbar is deleted.
  33066. */
  33067. ~Toolbar();
  33068. /** Changes the bar's orientation.
  33069. @see isVertical
  33070. */
  33071. void setVertical (bool shouldBeVertical);
  33072. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  33073. You can change the bar's orientation with setVertical().
  33074. */
  33075. bool isVertical() const throw() { return vertical; }
  33076. /** Returns the depth of the bar.
  33077. If the bar is horizontal, this will return its height; if it's vertical, it
  33078. will return its width.
  33079. @see getLength
  33080. */
  33081. int getThickness() const throw();
  33082. /** Returns the length of the bar.
  33083. If the bar is horizontal, this will return its width; if it's vertical, it
  33084. will return its height.
  33085. @see getThickness
  33086. */
  33087. int getLength() const throw();
  33088. /** Deletes all items from the bar.
  33089. */
  33090. void clear();
  33091. /** Adds an item to the toolbar.
  33092. The factory's ToolbarItemFactory::createItem() will be called by this method
  33093. to create the component that will actually be added to the bar.
  33094. The new item will be inserted at the specified index (if the index is -1, it
  33095. will be added to the right-hand or bottom end of the bar).
  33096. Once added, the component will be automatically deleted by this object when it
  33097. is no longer needed.
  33098. @see ToolbarItemFactory
  33099. */
  33100. void addItem (ToolbarItemFactory& factory,
  33101. int itemId,
  33102. int insertIndex = -1);
  33103. /** Deletes one of the items from the bar.
  33104. */
  33105. void removeToolbarItem (int itemIndex);
  33106. /** Returns the number of items currently on the toolbar.
  33107. @see getItemId, getItemComponent
  33108. */
  33109. int getNumItems() const throw();
  33110. /** Returns the ID of the item with the given index.
  33111. If the index is less than zero or greater than the number of items,
  33112. this will return 0.
  33113. @see getNumItems
  33114. */
  33115. int getItemId (int itemIndex) const throw();
  33116. /** Returns the component being used for the item with the given index.
  33117. If the index is less than zero or greater than the number of items,
  33118. this will return 0.
  33119. @see getNumItems
  33120. */
  33121. ToolbarItemComponent* getItemComponent (int itemIndex) const throw();
  33122. /** Clears this toolbar and adds to it the default set of items that the specified
  33123. factory creates.
  33124. @see ToolbarItemFactory::getDefaultItemSet
  33125. */
  33126. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  33127. /** Options for the way items should be displayed.
  33128. @see setStyle, getStyle
  33129. */
  33130. enum ToolbarItemStyle
  33131. {
  33132. iconsOnly, /**< Means that the toolbar should just contain icons. */
  33133. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  33134. textOnly /**< Means that the toolbar only display text labels for each item. */
  33135. };
  33136. /** Returns the toolbar's current style.
  33137. @see ToolbarItemStyle, setStyle
  33138. */
  33139. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  33140. /** Changes the toolbar's current style.
  33141. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  33142. */
  33143. void setStyle (const ToolbarItemStyle& newStyle);
  33144. /** Flags used by the showCustomisationDialog() method. */
  33145. enum CustomisationFlags
  33146. {
  33147. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  33148. show the "icons only" option on its choice of toolbar styles. */
  33149. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  33150. show the "icons with text" option on its choice of toolbar styles. */
  33151. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  33152. show the "text only" option on its choice of toolbar styles. */
  33153. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  33154. show a button to reset the toolbar to its default set of items. */
  33155. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  33156. };
  33157. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  33158. The dialog contains a ToolbarItemPalette and various controls for editing other
  33159. aspects of the toolbar. This method will block and run the dialog box modally,
  33160. returning when the user closes it.
  33161. The factory is used to determine the set of items that will be shown on the
  33162. palette.
  33163. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  33164. enum.
  33165. @see ToolbarItemPalette
  33166. */
  33167. void showCustomisationDialog (ToolbarItemFactory& factory,
  33168. int optionFlags = allCustomisationOptionsEnabled);
  33169. /** Turns on or off the toolbar's editing mode, in which its items can be
  33170. rearranged by the user.
  33171. (In most cases it's easier just to use showCustomisationDialog() instead of
  33172. trying to enable editing directly).
  33173. @see ToolbarItemPalette
  33174. */
  33175. void setEditingActive (bool editingEnabled);
  33176. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  33177. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33178. methods.
  33179. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33180. */
  33181. enum ColourIds
  33182. {
  33183. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  33184. more control over this, override LookAndFeel::paintToolbarBackground(). */
  33185. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  33186. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  33187. over them. */
  33188. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  33189. held down on them. */
  33190. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  33191. when the style is set to iconsWithText or textOnly. */
  33192. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  33193. the customisation dialog is active and the mouse moves over them. */
  33194. };
  33195. /** Returns a string that represents the toolbar's current set of items.
  33196. This lets you later restore the same item layout using restoreFromString().
  33197. @see restoreFromString
  33198. */
  33199. const String toString() const;
  33200. /** Restores a set of items that was previously stored in a string by the toString()
  33201. method.
  33202. The factory object is used to create any item components that are needed.
  33203. @see toString
  33204. */
  33205. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  33206. const String& savedVersion);
  33207. /** @internal */
  33208. void paint (Graphics& g);
  33209. /** @internal */
  33210. void resized();
  33211. /** @internal */
  33212. void buttonClicked (Button*);
  33213. /** @internal */
  33214. void mouseDown (const MouseEvent&);
  33215. /** @internal */
  33216. bool isInterestedInDragSource (const String&, Component*);
  33217. /** @internal */
  33218. void itemDragMove (const String&, Component*, int, int);
  33219. /** @internal */
  33220. void itemDragExit (const String&, Component*);
  33221. /** @internal */
  33222. void itemDropped (const String&, Component*, int, int);
  33223. /** @internal */
  33224. void updateAllItemPositions (const bool animate);
  33225. /** @internal */
  33226. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  33227. juce_UseDebuggingNewOperator
  33228. private:
  33229. Button* missingItemsButton;
  33230. bool vertical, isEditingActive;
  33231. ToolbarItemStyle toolbarStyle;
  33232. ComponentAnimator animator;
  33233. friend class MissingItemsComponent;
  33234. Array <ToolbarItemComponent*> items;
  33235. friend class ItemDragAndDropOverlayComponent;
  33236. static const char* const toolbarDragDescriptor;
  33237. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  33238. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  33239. Toolbar (const Toolbar&);
  33240. Toolbar& operator= (const Toolbar&);
  33241. };
  33242. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  33243. /*** End of inlined file: juce_Toolbar.h ***/
  33244. class ItemDragAndDropOverlayComponent;
  33245. /**
  33246. A component that can be used as one of the items in a Toolbar.
  33247. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  33248. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  33249. class for further info about creating them.
  33250. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  33251. components too. To do this, set the value of isBeingUsedAsAButton to false when
  33252. calling the constructor, and override contentAreaChanged(), in which you can position
  33253. any sub-components you need to add.
  33254. To add basic buttons without writing a special subclass, have a look at the
  33255. ToolbarButton class.
  33256. @see ToolbarButton, Toolbar, ToolbarItemFactory
  33257. */
  33258. class JUCE_API ToolbarItemComponent : public Button
  33259. {
  33260. public:
  33261. /** Constructor.
  33262. @param itemId the ID of the type of toolbar item which this represents
  33263. @param labelText the text to display if the toolbar's style is set to
  33264. Toolbar::iconsWithText or Toolbar::textOnly
  33265. @param isBeingUsedAsAButton set this to false if you don't want the button
  33266. to draw itself with button over/down states when the mouse
  33267. moves over it or clicks
  33268. */
  33269. ToolbarItemComponent (int itemId,
  33270. const String& labelText,
  33271. bool isBeingUsedAsAButton);
  33272. /** Destructor. */
  33273. ~ToolbarItemComponent();
  33274. /** Returns the item type ID that this component represents.
  33275. This value is in the constructor.
  33276. */
  33277. int getItemId() const throw() { return itemId; }
  33278. /** Returns the toolbar that contains this component, or 0 if it's not currently
  33279. inside one.
  33280. */
  33281. Toolbar* getToolbar() const;
  33282. /** Returns true if this component is currently inside a toolbar which is vertical.
  33283. @see Toolbar::isVertical
  33284. */
  33285. bool isToolbarVertical() const;
  33286. /** Returns the current style setting of this item.
  33287. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  33288. @see setStyle, Toolbar::getStyle
  33289. */
  33290. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  33291. /** Changes the current style setting of this item.
  33292. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  33293. by the toolbar that holds this item.
  33294. @see setStyle, Toolbar::setStyle
  33295. */
  33296. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  33297. /** Returns the area of the component that should be used to display the button image or
  33298. other contents of the item.
  33299. This content area may change when the item's style changes, and may leave a space around the
  33300. edge of the component where the text label can be shown.
  33301. @see contentAreaChanged
  33302. */
  33303. const Rectangle<int> getContentArea() const throw() { return contentArea; }
  33304. /** This method must return the size criteria for this item, based on a given toolbar
  33305. size and orientation.
  33306. The preferredSize, minSize and maxSize values must all be set by your implementation
  33307. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  33308. toolbar, they refer to the item's height.
  33309. The preferredSize is the size that the component would like to be, and this must be
  33310. between the min and max sizes. For a fixed-size item, simply set all three variables to
  33311. the same value.
  33312. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  33313. Toolbar::getThickness().
  33314. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  33315. vertically.
  33316. */
  33317. virtual bool getToolbarItemSizes (int toolbarThickness,
  33318. bool isToolbarVertical,
  33319. int& preferredSize,
  33320. int& minSize,
  33321. int& maxSize) = 0;
  33322. /** Your subclass should use this method to draw its content area.
  33323. The graphics object that is passed-in will have been clipped and had its origin
  33324. moved to fit the content area as specified get getContentArea(). The width and height
  33325. parameters are the width and height of the content area.
  33326. If the component you're writing isn't a button, you can just do nothing in this method.
  33327. */
  33328. virtual void paintButtonArea (Graphics& g,
  33329. int width, int height,
  33330. bool isMouseOver, bool isMouseDown) = 0;
  33331. /** Callback to indicate that the content area of this item has changed.
  33332. This might be because the component was resized, or because the style changed and
  33333. the space needed for the text label is different.
  33334. See getContentArea() for a description of what the area is.
  33335. */
  33336. virtual void contentAreaChanged (const Rectangle<int>& newBounds) = 0;
  33337. /** Editing modes.
  33338. These are used by setEditingMode(), but will be rarely needed in user code.
  33339. */
  33340. enum ToolbarEditingMode
  33341. {
  33342. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  33343. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  33344. customisation mode, and the items can be dragged around. */
  33345. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  33346. dragged onto a toolbar to add it to that bar.*/
  33347. };
  33348. /** Changes the editing mode of this component.
  33349. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  33350. and is unlikely to be of much use in end-user-code.
  33351. */
  33352. void setEditingMode (const ToolbarEditingMode newMode);
  33353. /** Returns the current editing mode of this component.
  33354. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  33355. and is unlikely to be of much use in end-user-code.
  33356. */
  33357. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  33358. /** @internal */
  33359. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  33360. /** @internal */
  33361. void resized();
  33362. juce_UseDebuggingNewOperator
  33363. private:
  33364. friend class Toolbar;
  33365. friend class ItemDragAndDropOverlayComponent;
  33366. const int itemId;
  33367. ToolbarEditingMode mode;
  33368. Toolbar::ToolbarItemStyle toolbarStyle;
  33369. ScopedPointer <Component> overlayComp;
  33370. int dragOffsetX, dragOffsetY;
  33371. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  33372. Rectangle<int> contentArea;
  33373. ToolbarItemComponent (const ToolbarItemComponent&);
  33374. ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  33375. };
  33376. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  33377. /*** End of inlined file: juce_ToolbarItemComponent.h ***/
  33378. /**
  33379. A type of button designed to go on a toolbar.
  33380. This simple button can have two Drawable objects specified - one for normal
  33381. use and another one (optionally) for the button's "on" state if it's a
  33382. toggle button.
  33383. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  33384. */
  33385. class JUCE_API ToolbarButton : public ToolbarItemComponent
  33386. {
  33387. public:
  33388. /** Creates a ToolbarButton.
  33389. @param itemId the ID for this toolbar item type. This is passed through to the
  33390. ToolbarItemComponent constructor
  33391. @param labelText the text to display on the button (if the toolbar is using a style
  33392. that shows text labels). This is passed through to the
  33393. ToolbarItemComponent constructor
  33394. @param normalImage a drawable object that the button should use as its icon. The object
  33395. that is passed-in here will be kept by this object and will be
  33396. deleted when no longer needed or when this button is deleted.
  33397. @param toggledOnImage a drawable object that the button can use as its icon if the button
  33398. is in a toggled-on state (see the Button::getToggleState() method). If
  33399. 0 is passed-in here, then the normal image will be used instead, regardless
  33400. of the toggle state. The object that is passed-in here will be kept by
  33401. this object and will be deleted when no longer needed or when this button
  33402. is deleted.
  33403. */
  33404. ToolbarButton (int itemId,
  33405. const String& labelText,
  33406. Drawable* normalImage,
  33407. Drawable* toggledOnImage);
  33408. /** Destructor. */
  33409. ~ToolbarButton();
  33410. /** @internal */
  33411. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  33412. int& minSize, int& maxSize);
  33413. /** @internal */
  33414. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  33415. /** @internal */
  33416. void contentAreaChanged (const Rectangle<int>& newBounds);
  33417. juce_UseDebuggingNewOperator
  33418. private:
  33419. ScopedPointer <Drawable> normalImage, toggledOnImage;
  33420. ToolbarButton (const ToolbarButton&);
  33421. ToolbarButton& operator= (const ToolbarButton&);
  33422. };
  33423. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  33424. /*** End of inlined file: juce_ToolbarButton.h ***/
  33425. #endif
  33426. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  33427. /*** Start of inlined file: juce_CodeDocument.h ***/
  33428. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  33429. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  33430. class CodeDocumentLine;
  33431. /**
  33432. A class for storing and manipulating a source code file.
  33433. When using a CodeEditorComponent, it takes one of these as its source object.
  33434. The CodeDocument stores its content as an array of lines, which makes it
  33435. quick to insert and delete.
  33436. @see CodeEditorComponent
  33437. */
  33438. class JUCE_API CodeDocument
  33439. {
  33440. public:
  33441. /** Creates a new, empty document.
  33442. */
  33443. CodeDocument();
  33444. /** Destructor. */
  33445. ~CodeDocument();
  33446. /** A position in a code document.
  33447. Using this class you can find a position in a code document and quickly get its
  33448. character position, line, and index. By calling setPositionMaintained (true), the
  33449. position is automatically updated when text is inserted or deleted in the document,
  33450. so that it maintains its original place in the text.
  33451. */
  33452. class JUCE_API Position
  33453. {
  33454. public:
  33455. /** Creates an uninitialised postion.
  33456. Don't attempt to call any methods on this until you've given it an owner document
  33457. to refer to!
  33458. */
  33459. Position() throw();
  33460. /** Creates a position based on a line and index in a document.
  33461. Note that this index is NOT the column number, it's the number of characters from the
  33462. start of the line. The "column" number isn't quite the same, because if the line
  33463. contains any tab characters, the relationship of the index to its visual column depends on
  33464. the number of spaces per tab being used!
  33465. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  33466. they will be adjusted to keep them within its limits.
  33467. */
  33468. Position (const CodeDocument* ownerDocument,
  33469. int line, int indexInLine) throw();
  33470. /** Creates a position based on a character index in a document.
  33471. This position is placed at the specified number of characters from the start of the
  33472. document. The line and column are auto-calculated.
  33473. If the position is beyond the range of the document, it'll be adjusted to keep it
  33474. inside.
  33475. */
  33476. Position (const CodeDocument* ownerDocument,
  33477. int charactersFromStartOfDocument) throw();
  33478. /** Creates a copy of another position.
  33479. This will copy the position, but the new object will not be set to maintain its position,
  33480. even if the source object was set to do so.
  33481. */
  33482. Position (const Position& other) throw();
  33483. /** Destructor. */
  33484. ~Position() throw();
  33485. Position& operator= (const Position& other) throw();
  33486. bool operator== (const Position& other) const throw();
  33487. bool operator!= (const Position& other) const throw();
  33488. /** Points this object at a new position within the document.
  33489. If the position is beyond the range of the document, it'll be adjusted to keep it
  33490. inside.
  33491. @see getPosition, setLineAndIndex
  33492. */
  33493. void setPosition (int charactersFromStartOfDocument) throw();
  33494. /** Returns the position as the number of characters from the start of the document.
  33495. @see setPosition, getLineNumber, getIndexInLine
  33496. */
  33497. int getPosition() const throw() { return characterPos; }
  33498. /** Moves the position to a new line and index within the line.
  33499. Note that the index is NOT the column at which the position appears in an editor.
  33500. If the line contains any tab characters, the relationship of the index to its
  33501. visual position depends on the number of spaces per tab being used!
  33502. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  33503. they will be adjusted to keep them within its limits.
  33504. */
  33505. void setLineAndIndex (int newLine, int newIndexInLine) throw();
  33506. /** Returns the line number of this position.
  33507. The first line in the document is numbered zero, not one!
  33508. */
  33509. int getLineNumber() const throw() { return line; }
  33510. /** Returns the number of characters from the start of the line.
  33511. Note that this value is NOT the column at which the position appears in an editor.
  33512. If the line contains any tab characters, the relationship of the index to its
  33513. visual position depends on the number of spaces per tab being used!
  33514. */
  33515. int getIndexInLine() const throw() { return indexInLine; }
  33516. /** Allows the position to be automatically updated when the document changes.
  33517. If this is set to true, the positon will register with its document so that
  33518. when the document has text inserted or deleted, this position will be automatically
  33519. moved to keep it at the same position in the text.
  33520. */
  33521. void setPositionMaintained (bool isMaintained) throw();
  33522. /** Moves the position forwards or backwards by the specified number of characters.
  33523. @see movedBy
  33524. */
  33525. void moveBy (int characterDelta) throw();
  33526. /** Returns a position which is the same as this one, moved by the specified number of
  33527. characters.
  33528. @see moveBy
  33529. */
  33530. const Position movedBy (int characterDelta) const throw();
  33531. /** Returns a position which is the same as this one, moved up or down by the specified
  33532. number of lines.
  33533. @see movedBy
  33534. */
  33535. const Position movedByLines (int deltaLines) const throw();
  33536. /** Returns the character in the document at this position.
  33537. @see getLineText
  33538. */
  33539. const juce_wchar getCharacter() const throw();
  33540. /** Returns the line from the document that this position is within.
  33541. @see getCharacter, getLineNumber
  33542. */
  33543. const String getLineText() const throw();
  33544. private:
  33545. CodeDocument* owner;
  33546. int characterPos, line, indexInLine;
  33547. bool positionMaintained;
  33548. };
  33549. /** Returns the full text of the document. */
  33550. const String getAllContent() const throw();
  33551. /** Returns a section of the document's text. */
  33552. const String getTextBetween (const Position& start, const Position& end) const throw();
  33553. /** Returns a line from the document. */
  33554. const String getLine (int lineIndex) const throw();
  33555. /** Returns the number of characters in the document. */
  33556. int getNumCharacters() const throw();
  33557. /** Returns the number of lines in the document. */
  33558. int getNumLines() const throw() { return lines.size(); }
  33559. /** Returns the number of characters in the longest line of the document. */
  33560. int getMaximumLineLength() throw();
  33561. /** Deletes a section of the text.
  33562. This operation is undoable.
  33563. */
  33564. void deleteSection (const Position& startPosition, const Position& endPosition);
  33565. /** Inserts some text into the document at a given position.
  33566. This operation is undoable.
  33567. */
  33568. void insertText (const Position& position, const String& text);
  33569. /** Clears the document and replaces it with some new text.
  33570. This operation is undoable - if you're trying to completely reset the document, you
  33571. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  33572. */
  33573. void replaceAllContent (const String& newContent);
  33574. /** Replaces the editor's contents with the contents of a stream.
  33575. This will also reset the undo history and save point marker.
  33576. */
  33577. bool loadFromStream (InputStream& stream);
  33578. /** Writes the editor's current contents to a stream. */
  33579. bool writeToStream (OutputStream& stream);
  33580. /** Returns the preferred new-line characters for the document.
  33581. This will be either "\n", "\r\n", or (rarely) "\r".
  33582. @see setNewLineCharacters
  33583. */
  33584. const String getNewLineCharacters() const throw() { return newLineChars; }
  33585. /** Sets the new-line characters that the document should use.
  33586. The string must be either "\n", "\r\n", or (rarely) "\r".
  33587. @see getNewLineCharacters
  33588. */
  33589. void setNewLineCharacters (const String& newLine) throw();
  33590. /** Begins a new undo transaction.
  33591. The document itself will not call this internally, so relies on whatever is using the
  33592. document to periodically call this to break up the undo sequence into sensible chunks.
  33593. @see UndoManager::beginNewTransaction
  33594. */
  33595. void newTransaction();
  33596. /** Undo the last operation.
  33597. @see UndoManager::undo
  33598. */
  33599. void undo();
  33600. /** Redo the last operation.
  33601. @see UndoManager::redo
  33602. */
  33603. void redo();
  33604. /** Clears the undo history.
  33605. @see UndoManager::clearUndoHistory
  33606. */
  33607. void clearUndoHistory();
  33608. /** Returns the document's UndoManager */
  33609. UndoManager& getUndoManager() throw() { return undoManager; }
  33610. /** Makes a note that the document's current state matches the one that is saved.
  33611. After this has been called, hasChangedSinceSavePoint() will return false until
  33612. the document has been altered, and then it'll start returning true. If the document is
  33613. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  33614. will again return false.
  33615. @see hasChangedSinceSavePoint
  33616. */
  33617. void setSavePoint() throw();
  33618. /** Returns true if the state of the document differs from the state it was in when
  33619. setSavePoint() was last called.
  33620. @see setSavePoint
  33621. */
  33622. bool hasChangedSinceSavePoint() const throw();
  33623. /** Searches for a word-break. */
  33624. const Position findWordBreakAfter (const Position& position) const throw();
  33625. /** Searches for a word-break. */
  33626. const Position findWordBreakBefore (const Position& position) const throw();
  33627. /** An object that receives callbacks from the CodeDocument when its text changes.
  33628. @see CodeDocument::addListener, CodeDocument::removeListener
  33629. */
  33630. class JUCE_API Listener
  33631. {
  33632. public:
  33633. Listener() {}
  33634. virtual ~Listener() {}
  33635. /** Called by a CodeDocument when it is altered.
  33636. */
  33637. virtual void codeDocumentChanged (const Position& affectedTextStart,
  33638. const Position& affectedTextEnd) = 0;
  33639. };
  33640. /** Registers a listener object to receive callbacks when the document changes.
  33641. If the listener is already registered, this method has no effect.
  33642. @see removeListener
  33643. */
  33644. void addListener (Listener* listener) throw();
  33645. /** Deregisters a listener.
  33646. @see addListener
  33647. */
  33648. void removeListener (Listener* listener) throw();
  33649. /** Iterates the text in a CodeDocument.
  33650. This class lets you read characters from a CodeDocument. It's designed to be used
  33651. by a SyntaxAnalyser object.
  33652. @see CodeDocument, SyntaxAnalyser
  33653. */
  33654. class Iterator
  33655. {
  33656. public:
  33657. Iterator (CodeDocument* document);
  33658. Iterator (const Iterator& other);
  33659. Iterator& operator= (const Iterator& other) throw();
  33660. ~Iterator() throw();
  33661. /** Reads the next character and returns it.
  33662. @see peekNextChar
  33663. */
  33664. juce_wchar nextChar();
  33665. /** Reads the next character without advancing the current position. */
  33666. juce_wchar peekNextChar() const;
  33667. /** Advances the position by one character. */
  33668. void skip();
  33669. /** Returns the position of the next character as its position within the
  33670. whole document.
  33671. */
  33672. int getPosition() const throw() { return position; }
  33673. /** Skips over any whitespace characters until the next character is non-whitespace. */
  33674. void skipWhitespace();
  33675. /** Skips forward until the next character will be the first character on the next line */
  33676. void skipToEndOfLine();
  33677. /** Returns the line number of the next character. */
  33678. int getLine() const throw() { return line; }
  33679. /** Returns true if the iterator has reached the end of the document. */
  33680. bool isEOF() const throw();
  33681. private:
  33682. CodeDocument* document;
  33683. CodeDocumentLine* currentLine;
  33684. int line, position;
  33685. };
  33686. juce_UseDebuggingNewOperator
  33687. private:
  33688. friend class CodeDocumentInsertAction;
  33689. friend class CodeDocumentDeleteAction;
  33690. friend class Iterator;
  33691. friend class Position;
  33692. OwnedArray <CodeDocumentLine> lines;
  33693. Array <Position*> positionsToMaintain;
  33694. UndoManager undoManager;
  33695. int currentActionIndex, indexOfSavedState;
  33696. int maximumLineLength;
  33697. ListenerList <Listener> listeners;
  33698. String newLineChars;
  33699. void sendListenerChangeMessage (int startLine, int endLine);
  33700. void insert (const String& text, int insertPos, bool undoable);
  33701. void remove (int startPos, int endPos, bool undoable);
  33702. void checkLastLineStatus();
  33703. CodeDocument (const CodeDocument&);
  33704. CodeDocument& operator= (const CodeDocument&);
  33705. };
  33706. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  33707. /*** End of inlined file: juce_CodeDocument.h ***/
  33708. #endif
  33709. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33710. /*** Start of inlined file: juce_CodeEditorComponent.h ***/
  33711. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33712. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33713. /*** Start of inlined file: juce_CodeTokeniser.h ***/
  33714. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  33715. #define __JUCE_CODETOKENISER_JUCEHEADER__
  33716. /**
  33717. A base class for tokenising code so that the syntax can be displayed in a
  33718. code editor.
  33719. @see CodeDocument, CodeEditorComponent
  33720. */
  33721. class JUCE_API CodeTokeniser
  33722. {
  33723. public:
  33724. CodeTokeniser() {}
  33725. virtual ~CodeTokeniser() {}
  33726. /** Reads the next token from the source and returns its token type.
  33727. This must leave the source pointing to the first character in the
  33728. next token.
  33729. */
  33730. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  33731. /** Returns a list of the names of the token types this analyser uses.
  33732. The index in this list must match the token type numbers that are
  33733. returned by readNextToken().
  33734. */
  33735. virtual const StringArray getTokenTypes() = 0;
  33736. /** Returns a suggested syntax highlighting colour for a specified
  33737. token type.
  33738. */
  33739. virtual const Colour getDefaultColour (int tokenType) = 0;
  33740. juce_UseDebuggingNewOperator
  33741. };
  33742. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  33743. /*** End of inlined file: juce_CodeTokeniser.h ***/
  33744. /**
  33745. A text editor component designed specifically for source code.
  33746. This is designed to handle syntax highlighting and fast editing of very large
  33747. files.
  33748. */
  33749. class JUCE_API CodeEditorComponent : public Component,
  33750. public TextInputTarget,
  33751. public Timer,
  33752. public ScrollBarListener,
  33753. public CodeDocument::Listener,
  33754. public AsyncUpdater
  33755. {
  33756. public:
  33757. /** Creates an editor for a document.
  33758. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  33759. The object that you pass in is not owned or deleted by the editor - you must
  33760. make sure that it doesn't get deleted while this component is still using it.
  33761. @see CodeDocument
  33762. */
  33763. CodeEditorComponent (CodeDocument& document,
  33764. CodeTokeniser* codeTokeniser);
  33765. /** Destructor. */
  33766. ~CodeEditorComponent();
  33767. /** Returns the code document that this component is editing. */
  33768. CodeDocument& getDocument() const throw() { return document; }
  33769. /** Loads the given content into the document.
  33770. This will completely reset the CodeDocument object, clear its undo history,
  33771. and fill it with this text.
  33772. */
  33773. void loadContent (const String& newContent);
  33774. /** Returns the standard character width. */
  33775. float getCharWidth() const throw() { return charWidth; }
  33776. /** Returns the height of a line of text, in pixels. */
  33777. int getLineHeight() const throw() { return lineHeight; }
  33778. /** Returns the number of whole lines visible on the screen,
  33779. This doesn't include a cut-off line that might be visible at the bottom if the
  33780. component's height isn't an exact multiple of the line-height.
  33781. */
  33782. int getNumLinesOnScreen() const throw() { return linesOnScreen; }
  33783. /** Returns the number of whole columns visible on the screen.
  33784. This doesn't include any cut-off columns at the right-hand edge.
  33785. */
  33786. int getNumColumnsOnScreen() const throw() { return columnsOnScreen; }
  33787. /** Returns the current caret position. */
  33788. const CodeDocument::Position getCaretPos() const { return caretPos; }
  33789. /** Moves the caret.
  33790. If selecting is true, the section of the document between the current
  33791. caret position and the new one will become selected. If false, any currently
  33792. selected region will be deselected.
  33793. */
  33794. void moveCaretTo (const CodeDocument::Position& newPos, bool selecting);
  33795. /** Returns the on-screen position of a character in the document.
  33796. The rectangle returned is relative to this component's top-left origin.
  33797. */
  33798. const Rectangle<int> getCharacterBounds (const CodeDocument::Position& pos) const throw();
  33799. /** Finds the character at a given on-screen position.
  33800. The co-ordinates are relative to this component's top-left origin.
  33801. */
  33802. const CodeDocument::Position getPositionAt (int x, int y);
  33803. void cursorLeft (bool moveInWholeWordSteps, bool selecting);
  33804. void cursorRight (bool moveInWholeWordSteps, bool selecting);
  33805. void cursorDown (bool selecting);
  33806. void cursorUp (bool selecting);
  33807. void pageDown (bool selecting);
  33808. void pageUp (bool selecting);
  33809. void scrollDown();
  33810. void scrollUp();
  33811. void scrollToLine (int newFirstLineOnScreen);
  33812. void scrollBy (int deltaLines);
  33813. void scrollToColumn (int newFirstColumnOnScreen);
  33814. void scrollToKeepCaretOnScreen();
  33815. void goToStartOfDocument (bool selecting);
  33816. void goToStartOfLine (bool selecting);
  33817. void goToEndOfDocument (bool selecting);
  33818. void goToEndOfLine (bool selecting);
  33819. void deselectAll();
  33820. void selectAll();
  33821. void insertTextAtCaret (const String& textToInsert);
  33822. void insertTabAtCaret();
  33823. void cut();
  33824. void copy();
  33825. void copyThenCut();
  33826. void paste();
  33827. void backspace (bool moveInWholeWordSteps);
  33828. void deleteForward (bool moveInWholeWordSteps);
  33829. void undo();
  33830. void redo();
  33831. const Range<int> getHighlightedRegion() const;
  33832. void setHighlightedRegion (const Range<int>& newRange);
  33833. const String getTextInRange (const Range<int>& range) const;
  33834. /** Changes the current tab settings.
  33835. This lets you change the tab size and whether pressing the tab key inserts a
  33836. tab character, or its equivalent number of spaces.
  33837. */
  33838. void setTabSize (int numSpacesPerTab,
  33839. bool insertSpacesInsteadOfTabCharacters) throw();
  33840. /** Returns the current number of spaces per tab.
  33841. @see setTabSize
  33842. */
  33843. int getTabSize() const throw() { return spacesPerTab; }
  33844. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  33845. @see setTabSize
  33846. */
  33847. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  33848. /** Changes the font.
  33849. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  33850. */
  33851. void setFont (const Font& newFont);
  33852. /** Returns the font that the editor is using. */
  33853. const Font& getFont() const throw() { return font; }
  33854. /** Resets the syntax highlighting colours to the default ones provided by the
  33855. code tokeniser.
  33856. @see CodeTokeniser::getDefaultColour
  33857. */
  33858. void resetToDefaultColours();
  33859. /** Changes one of the syntax highlighting colours.
  33860. The token type values are dependent on the tokeniser being used - use
  33861. CodeTokeniser::getTokenTypes() to get a list of the token types.
  33862. @see getColourForTokenType
  33863. */
  33864. void setColourForTokenType (int tokenType, const Colour& colour);
  33865. /** Returns one of the syntax highlighting colours.
  33866. The token type values are dependent on the tokeniser being used - use
  33867. CodeTokeniser::getTokenTypes() to get a list of the token types.
  33868. @see setColourForTokenType
  33869. */
  33870. const Colour getColourForTokenType (int tokenType) const throw();
  33871. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  33872. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33873. methods.
  33874. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33875. */
  33876. enum ColourIds
  33877. {
  33878. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  33879. caretColourId = 0x1004501, /**< The colour to draw the caret. */
  33880. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  33881. selected text. */
  33882. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  33883. enabled. */
  33884. };
  33885. /** Changes the size of the scrollbars. */
  33886. void setScrollbarThickness (int thickness) throw();
  33887. /** Returns the thickness of the scrollbars. */
  33888. int getScrollbarThickness() const throw() { return scrollbarThickness; }
  33889. /** @internal */
  33890. void resized();
  33891. /** @internal */
  33892. void paint (Graphics& g);
  33893. /** @internal */
  33894. bool keyPressed (const KeyPress& key);
  33895. /** @internal */
  33896. void mouseDown (const MouseEvent& e);
  33897. /** @internal */
  33898. void mouseDrag (const MouseEvent& e);
  33899. /** @internal */
  33900. void mouseUp (const MouseEvent& e);
  33901. /** @internal */
  33902. void mouseDoubleClick (const MouseEvent& e);
  33903. /** @internal */
  33904. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  33905. /** @internal */
  33906. void focusGained (FocusChangeType cause);
  33907. /** @internal */
  33908. void focusLost (FocusChangeType cause);
  33909. /** @internal */
  33910. void timerCallback();
  33911. /** @internal */
  33912. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  33913. /** @internal */
  33914. void handleAsyncUpdate();
  33915. /** @internal */
  33916. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  33917. const CodeDocument::Position& affectedTextEnd);
  33918. /** @internal */
  33919. bool isTextInputActive() const;
  33920. juce_UseDebuggingNewOperator
  33921. private:
  33922. CodeDocument& document;
  33923. Font font;
  33924. int firstLineOnScreen, gutter, spacesPerTab;
  33925. float charWidth;
  33926. int lineHeight, linesOnScreen, columnsOnScreen;
  33927. int scrollbarThickness, columnToTryToMaintain;
  33928. bool useSpacesForTabs;
  33929. double xOffset;
  33930. CodeDocument::Position caretPos;
  33931. CodeDocument::Position selectionStart, selectionEnd;
  33932. class CaretComponent;
  33933. CaretComponent* caret;
  33934. ScrollBar* verticalScrollBar;
  33935. ScrollBar* horizontalScrollBar;
  33936. enum DragType
  33937. {
  33938. notDragging,
  33939. draggingSelectionStart,
  33940. draggingSelectionEnd
  33941. };
  33942. DragType dragType;
  33943. CodeTokeniser* codeTokeniser;
  33944. Array <Colour> coloursForTokenCategories;
  33945. class CodeEditorLine;
  33946. OwnedArray <CodeEditorLine> lines;
  33947. void rebuildLineTokens();
  33948. OwnedArray <CodeDocument::Iterator> cachedIterators;
  33949. void clearCachedIterators (int firstLineToBeInvalid) throw();
  33950. void updateCachedIterators (int maxLineNum);
  33951. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  33952. void moveLineDelta (int delta, bool selecting);
  33953. void updateScrollBars();
  33954. void scrollToLineInternal (int line);
  33955. void scrollToColumnInternal (double column);
  33956. void newTransaction();
  33957. int indexToColumn (int line, int index) const throw();
  33958. int columnToIndex (int line, int column) const throw();
  33959. CodeEditorComponent (const CodeEditorComponent&);
  33960. CodeEditorComponent& operator= (const CodeEditorComponent&);
  33961. };
  33962. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33963. /*** End of inlined file: juce_CodeEditorComponent.h ***/
  33964. #endif
  33965. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  33966. #endif
  33967. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  33968. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  33969. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  33970. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  33971. /**
  33972. A simple lexical analyser for syntax colouring of C++ code.
  33973. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  33974. */
  33975. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  33976. {
  33977. public:
  33978. CPlusPlusCodeTokeniser();
  33979. ~CPlusPlusCodeTokeniser();
  33980. enum TokenType
  33981. {
  33982. tokenType_error = 0,
  33983. tokenType_comment,
  33984. tokenType_builtInKeyword,
  33985. tokenType_identifier,
  33986. tokenType_integerLiteral,
  33987. tokenType_floatLiteral,
  33988. tokenType_stringLiteral,
  33989. tokenType_operator,
  33990. tokenType_bracket,
  33991. tokenType_punctuation,
  33992. tokenType_preprocessor
  33993. };
  33994. int readNextToken (CodeDocument::Iterator& source);
  33995. const StringArray getTokenTypes();
  33996. const Colour getDefaultColour (int tokenType);
  33997. /** This is a handy method for checking whether a string is a c++ reserved keyword. */
  33998. static bool isReservedKeyword (const String& token) throw();
  33999. juce_UseDebuggingNewOperator
  34000. };
  34001. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  34002. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  34003. #endif
  34004. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  34005. #endif
  34006. #ifndef __JUCE_LABEL_JUCEHEADER__
  34007. #endif
  34008. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  34009. #endif
  34010. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  34011. /*** Start of inlined file: juce_ProgressBar.h ***/
  34012. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  34013. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  34014. /**
  34015. A progress bar component.
  34016. To use this, just create one and make it visible. It'll run its own timer
  34017. to keep an eye on a variable that you give it, and will automatically
  34018. redraw itself when the variable changes.
  34019. For an easy way of running a background task with a dialog box showing its
  34020. progress, see the ThreadWithProgressWindow class.
  34021. @see ThreadWithProgressWindow
  34022. */
  34023. class JUCE_API ProgressBar : public Component,
  34024. public SettableTooltipClient,
  34025. private Timer
  34026. {
  34027. public:
  34028. /** Creates a ProgressBar.
  34029. @param progress pass in a reference to a double that you're going to
  34030. update with your task's progress. The ProgressBar will
  34031. monitor the value of this variable and will redraw itself
  34032. when the value changes. The range is from 0 to 1.0. Obviously
  34033. you'd better be careful not to delete this variable while the
  34034. ProgressBar still exists!
  34035. */
  34036. explicit ProgressBar (double& progress);
  34037. /** Destructor. */
  34038. ~ProgressBar();
  34039. /** Turns the percentage display on or off.
  34040. By default this is on, and the progress bar will display a text string showing
  34041. its current percentage.
  34042. */
  34043. void setPercentageDisplay (const bool shouldDisplayPercentage);
  34044. /** Gives the progress bar a string to display inside it.
  34045. If you call this, it will turn off the percentage display.
  34046. @see setPercentageDisplay
  34047. */
  34048. void setTextToDisplay (const String& text);
  34049. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  34050. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34051. methods.
  34052. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34053. */
  34054. enum ColourIds
  34055. {
  34056. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  34057. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  34058. classes will probably use variations on this colour. */
  34059. };
  34060. juce_UseDebuggingNewOperator
  34061. protected:
  34062. /** @internal */
  34063. void paint (Graphics& g);
  34064. /** @internal */
  34065. void lookAndFeelChanged();
  34066. /** @internal */
  34067. void visibilityChanged();
  34068. /** @internal */
  34069. void colourChanged();
  34070. private:
  34071. double& progress;
  34072. double currentValue;
  34073. bool displayPercentage;
  34074. String displayedMessage, currentMessage;
  34075. uint32 lastCallbackTime;
  34076. void timerCallback();
  34077. ProgressBar (const ProgressBar&);
  34078. ProgressBar& operator= (const ProgressBar&);
  34079. };
  34080. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  34081. /*** End of inlined file: juce_ProgressBar.h ***/
  34082. #endif
  34083. #ifndef __JUCE_SLIDER_JUCEHEADER__
  34084. /*** Start of inlined file: juce_Slider.h ***/
  34085. #ifndef __JUCE_SLIDER_JUCEHEADER__
  34086. #define __JUCE_SLIDER_JUCEHEADER__
  34087. /*** Start of inlined file: juce_SliderListener.h ***/
  34088. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  34089. #define __JUCE_SLIDERLISTENER_JUCEHEADER__
  34090. class Slider;
  34091. /**
  34092. A class for receiving callbacks from a Slider.
  34093. To be told when a slider's value changes, you can register a SliderListener
  34094. object using Slider::addListener().
  34095. @see Slider::addListener, Slider::removeListener
  34096. */
  34097. class JUCE_API SliderListener
  34098. {
  34099. public:
  34100. /** Destructor. */
  34101. virtual ~SliderListener() {}
  34102. /** Called when the slider's value is changed.
  34103. This may be caused by dragging it, or by typing in its text entry box,
  34104. or by a call to Slider::setValue().
  34105. You can find out the new value using Slider::getValue().
  34106. @see Slider::valueChanged
  34107. */
  34108. virtual void sliderValueChanged (Slider* slider) = 0;
  34109. /** Called when the slider is about to be dragged.
  34110. This is called when a drag begins, then it's followed by multiple calls
  34111. to sliderValueChanged(), and then sliderDragEnded() is called after the
  34112. user lets go.
  34113. @see sliderDragEnded, Slider::startedDragging
  34114. */
  34115. virtual void sliderDragStarted (Slider* slider);
  34116. /** Called after a drag operation has finished.
  34117. @see sliderDragStarted, Slider::stoppedDragging
  34118. */
  34119. virtual void sliderDragEnded (Slider* slider);
  34120. };
  34121. #endif // __JUCE_SLIDERLISTENER_JUCEHEADER__
  34122. /*** End of inlined file: juce_SliderListener.h ***/
  34123. /**
  34124. A slider control for changing a value.
  34125. The slider can be horizontal, vertical, or rotary, and can optionally have
  34126. a text-box inside it to show an editable display of the current value.
  34127. To use it, create a Slider object and use the setSliderStyle() method
  34128. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  34129. To define the values that it can be set to, see the setRange() and setValue() methods.
  34130. There are also lots of custom tweaks you can do by subclassing and overriding
  34131. some of the virtual methods, such as changing the scaling, changing the format of
  34132. the text display, custom ways of limiting the values, etc.
  34133. You can register SliderListeners with a slider, which will be informed when the value
  34134. changes, or a subclass can override valueChanged() to be informed synchronously.
  34135. @see SliderListener
  34136. */
  34137. class JUCE_API Slider : public Component,
  34138. public SettableTooltipClient,
  34139. private AsyncUpdater,
  34140. private ButtonListener,
  34141. private LabelListener,
  34142. private Value::Listener
  34143. {
  34144. public:
  34145. /** Creates a slider.
  34146. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  34147. setRange(), etc.
  34148. */
  34149. explicit Slider (const String& componentName = String::empty);
  34150. /** Destructor. */
  34151. ~Slider();
  34152. /** The types of slider available.
  34153. @see setSliderStyle, setRotaryParameters
  34154. */
  34155. enum SliderStyle
  34156. {
  34157. LinearHorizontal, /**< A traditional horizontal slider. */
  34158. LinearVertical, /**< A traditional vertical slider. */
  34159. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  34160. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  34161. @see setRotaryParameters */
  34162. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  34163. @see setRotaryParameters */
  34164. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  34165. @see setRotaryParameters */
  34166. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  34167. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  34168. @see setMinValue, setMaxValue */
  34169. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  34170. @see setMinValue, setMaxValue */
  34171. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  34172. value, with the current value being somewhere between them.
  34173. @see setMinValue, setMaxValue */
  34174. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  34175. value, with the current value being somewhere between them.
  34176. @see setMinValue, setMaxValue */
  34177. };
  34178. /** Changes the type of slider interface being used.
  34179. @param newStyle the type of interface
  34180. @see setRotaryParameters, setVelocityBasedMode,
  34181. */
  34182. void setSliderStyle (SliderStyle newStyle);
  34183. /** Returns the slider's current style.
  34184. @see setSliderStyle
  34185. */
  34186. SliderStyle getSliderStyle() const { return style; }
  34187. /** Changes the properties of a rotary slider.
  34188. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  34189. the slider's minimum value is represented
  34190. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  34191. the slider's maximum value is represented. This must be
  34192. greater than startAngleRadians
  34193. @param stopAtEnd if true, then when the slider is dragged around past the
  34194. minimum or maximum, it'll stop there; if false, it'll wrap
  34195. back to the opposite value
  34196. */
  34197. void setRotaryParameters (float startAngleRadians,
  34198. float endAngleRadians,
  34199. bool stopAtEnd);
  34200. /** Sets the distance the mouse has to move to drag the slider across
  34201. the full extent of its range.
  34202. This only applies when in modes like RotaryHorizontalDrag, where it's using
  34203. relative mouse movements to adjust the slider.
  34204. */
  34205. void setMouseDragSensitivity (int distanceForFullScaleDrag);
  34206. /** Changes the way the the mouse is used when dragging the slider.
  34207. If true, this will turn on velocity-sensitive dragging, so that
  34208. the faster the mouse moves, the bigger the movement to the slider. This
  34209. helps when making accurate adjustments if the slider's range is quite large.
  34210. If false, the slider will just try to snap to wherever the mouse is.
  34211. */
  34212. void setVelocityBasedMode (bool isVelocityBased);
  34213. /** Returns true if velocity-based mode is active.
  34214. @see setVelocityBasedMode
  34215. */
  34216. bool getVelocityBasedMode() const { return isVelocityBased; }
  34217. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  34218. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  34219. or if you're holding down ctrl.
  34220. @param sensitivity higher values than 1.0 increase the range of acceleration used
  34221. @param threshold the minimum number of pixels that the mouse needs to move for it
  34222. to be treated as a movement
  34223. @param offset values greater than 0.0 increase the minimum speed that will be used when
  34224. the threshold is reached
  34225. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  34226. key to toggle velocity-sensitive mode
  34227. */
  34228. void setVelocityModeParameters (double sensitivity = 1.0,
  34229. int threshold = 1,
  34230. double offset = 0.0,
  34231. bool userCanPressKeyToSwapMode = true);
  34232. /** Returns the velocity sensitivity setting.
  34233. @see setVelocityModeParameters
  34234. */
  34235. double getVelocitySensitivity() const { return velocityModeSensitivity; }
  34236. /** Returns the velocity threshold setting.
  34237. @see setVelocityModeParameters
  34238. */
  34239. int getVelocityThreshold() const { return velocityModeThreshold; }
  34240. /** Returns the velocity offset setting.
  34241. @see setVelocityModeParameters
  34242. */
  34243. double getVelocityOffset() const { return velocityModeOffset; }
  34244. /** Returns the velocity user key setting.
  34245. @see setVelocityModeParameters
  34246. */
  34247. bool getVelocityModeIsSwappable() const { return userKeyOverridesVelocity; }
  34248. /** Sets up a skew factor to alter the way values are distributed.
  34249. You may want to use a range of values on the slider where more accuracy
  34250. is required towards one end of the range, so this will logarithmically
  34251. spread the values across the length of the slider.
  34252. If the factor is < 1.0, the lower end of the range will fill more of the
  34253. slider's length; if the factor is > 1.0, the upper end of the range
  34254. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  34255. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  34256. method instead.
  34257. @see getSkewFactor, setSkewFactorFromMidPoint
  34258. */
  34259. void setSkewFactor (double factor);
  34260. /** Sets up a skew factor to alter the way values are distributed.
  34261. This allows you to specify the slider value that should appear in the
  34262. centre of the slider's visible range.
  34263. @see setSkewFactor, getSkewFactor
  34264. */
  34265. void setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint);
  34266. /** Returns the current skew factor.
  34267. See setSkewFactor for more info.
  34268. @see setSkewFactor, setSkewFactorFromMidPoint
  34269. */
  34270. double getSkewFactor() const { return skewFactor; }
  34271. /** Used by setIncDecButtonsMode().
  34272. */
  34273. enum IncDecButtonMode
  34274. {
  34275. incDecButtonsNotDraggable,
  34276. incDecButtonsDraggable_AutoDirection,
  34277. incDecButtonsDraggable_Horizontal,
  34278. incDecButtonsDraggable_Vertical
  34279. };
  34280. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  34281. can be dragged on the buttons to drag the values.
  34282. By default this is turned off. When enabled, clicking on the buttons still works
  34283. them as normal, but by holding down the mouse on a button and dragging it a little
  34284. distance, it flips into a mode where the value can be dragged. The drag direction can
  34285. either be set explicitly to be vertical or horizontal, or can be set to
  34286. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  34287. are side-by-side or above each other.
  34288. */
  34289. void setIncDecButtonsMode (IncDecButtonMode mode);
  34290. /** The position of the slider's text-entry box.
  34291. @see setTextBoxStyle
  34292. */
  34293. enum TextEntryBoxPosition
  34294. {
  34295. NoTextBox, /**< Doesn't display a text box. */
  34296. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  34297. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  34298. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  34299. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  34300. };
  34301. /** Changes the location and properties of the text-entry box.
  34302. @param newPosition where it should go (or NoTextBox to not have one at all)
  34303. @param isReadOnly if true, it's a read-only display
  34304. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  34305. room for the slider as well!
  34306. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  34307. room for the slider as well!
  34308. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  34309. */
  34310. void setTextBoxStyle (TextEntryBoxPosition newPosition,
  34311. bool isReadOnly,
  34312. int textEntryBoxWidth,
  34313. int textEntryBoxHeight);
  34314. /** Returns the status of the text-box.
  34315. @see setTextBoxStyle
  34316. */
  34317. const TextEntryBoxPosition getTextBoxPosition() const { return textBoxPos; }
  34318. /** Returns the width used for the text-box.
  34319. @see setTextBoxStyle
  34320. */
  34321. int getTextBoxWidth() const { return textBoxWidth; }
  34322. /** Returns the height used for the text-box.
  34323. @see setTextBoxStyle
  34324. */
  34325. int getTextBoxHeight() const { return textBoxHeight; }
  34326. /** Makes the text-box editable.
  34327. By default this is true, and the user can enter values into the textbox,
  34328. but it can be turned off if that's not suitable.
  34329. @see setTextBoxStyle, getValueFromText, getTextFromValue
  34330. */
  34331. void setTextBoxIsEditable (bool shouldBeEditable);
  34332. /** Returns true if the text-box is read-only.
  34333. @see setTextBoxStyle
  34334. */
  34335. bool isTextBoxEditable() const { return editableText; }
  34336. /** If the text-box is editable, this will give it the focus so that the user can
  34337. type directly into it.
  34338. This is basically the effect as the user clicking on it.
  34339. */
  34340. void showTextBox();
  34341. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  34342. focus away from it.
  34343. @param discardCurrentEditorContents if true, the slider's value will be left
  34344. unchanged; if false, the current contents of the
  34345. text editor will be used to set the slider position
  34346. before it is hidden.
  34347. */
  34348. void hideTextBox (bool discardCurrentEditorContents);
  34349. /** Changes the slider's current value.
  34350. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34351. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34352. want to handle it.
  34353. @param newValue the new value to set - this will be restricted by the
  34354. minimum and maximum range, and will be snapped to the
  34355. nearest interval if one has been set
  34356. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34357. any SliderListeners or the valueChanged() method
  34358. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34359. synchronously; if false, it will be asynchronous
  34360. */
  34361. void setValue (double newValue,
  34362. bool sendUpdateMessage = true,
  34363. bool sendMessageSynchronously = false);
  34364. /** Returns the slider's current value. */
  34365. double getValue() const;
  34366. /** Returns the Value object that represents the slider's current position.
  34367. You can use this Value object to connect the slider's position to external values or setters,
  34368. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34369. your own Value object.
  34370. @see Value, getMaxValue, getMinValueObject
  34371. */
  34372. Value& getValueObject() { return currentValue; }
  34373. /** Sets the limits that the slider's value can take.
  34374. @param newMinimum the lowest value allowed
  34375. @param newMaximum the highest value allowed
  34376. @param newInterval the steps in which the value is allowed to increase - if this
  34377. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  34378. */
  34379. void setRange (double newMinimum,
  34380. double newMaximum,
  34381. double newInterval = 0);
  34382. /** Returns the current maximum value.
  34383. @see setRange
  34384. */
  34385. double getMaximum() const { return maximum; }
  34386. /** Returns the current minimum value.
  34387. @see setRange
  34388. */
  34389. double getMinimum() const { return minimum; }
  34390. /** Returns the current step-size for values.
  34391. @see setRange
  34392. */
  34393. double getInterval() const { return interval; }
  34394. /** For a slider with two or three thumbs, this returns the lower of its values.
  34395. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34396. A slider with three values also uses the normal getValue() and setValue() methods to
  34397. control the middle value.
  34398. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34399. */
  34400. double getMinValue() const;
  34401. /** For a slider with two or three thumbs, this returns the lower of its values.
  34402. You can use this Value object to connect the slider's position to external values or setters,
  34403. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34404. your own Value object.
  34405. @see Value, getMinValue, getMaxValueObject
  34406. */
  34407. Value& getMinValueObject() { return valueMin; }
  34408. /** For a slider with two or three thumbs, this sets the lower of its values.
  34409. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34410. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34411. want to handle it.
  34412. @param newValue the new value to set - this will be restricted by the
  34413. minimum and maximum range, and will be snapped to the nearest
  34414. interval if one has been set.
  34415. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34416. any SliderListeners or the valueChanged() method
  34417. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34418. synchronously; if false, it will be asynchronous
  34419. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  34420. max value (in a two-value slider) or the mid value (in a three-value
  34421. slider). If false, then if this value goes beyond those values,
  34422. it will push them along with it.
  34423. @see getMinValue, setMaxValue, setValue
  34424. */
  34425. void setMinValue (double newValue,
  34426. bool sendUpdateMessage = true,
  34427. bool sendMessageSynchronously = false,
  34428. bool allowNudgingOfOtherValues = false);
  34429. /** For a slider with two or three thumbs, this returns the higher of its values.
  34430. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34431. A slider with three values also uses the normal getValue() and setValue() methods to
  34432. control the middle value.
  34433. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34434. */
  34435. double getMaxValue() const;
  34436. /** For a slider with two or three thumbs, this returns the higher of its values.
  34437. You can use this Value object to connect the slider's position to external values or setters,
  34438. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34439. your own Value object.
  34440. @see Value, getMaxValue, getMinValueObject
  34441. */
  34442. Value& getMaxValueObject() { return valueMax; }
  34443. /** For a slider with two or three thumbs, this sets the lower of its values.
  34444. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34445. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34446. want to handle it.
  34447. @param newValue the new value to set - this will be restricted by the
  34448. minimum and maximum range, and will be snapped to the nearest
  34449. interval if one has been set.
  34450. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34451. any SliderListeners or the valueChanged() method
  34452. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34453. synchronously; if false, it will be asynchronous
  34454. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  34455. min value (in a two-value slider) or the mid value (in a three-value
  34456. slider). If false, then if this value goes beyond those values,
  34457. it will push them along with it.
  34458. @see getMaxValue, setMinValue, setValue
  34459. */
  34460. void setMaxValue (double newValue,
  34461. bool sendUpdateMessage = true,
  34462. bool sendMessageSynchronously = false,
  34463. bool allowNudgingOfOtherValues = false);
  34464. /** Adds a listener to be called when this slider's value changes. */
  34465. void addListener (SliderListener* listener);
  34466. /** Removes a previously-registered listener. */
  34467. void removeListener (SliderListener* listener);
  34468. /** This lets you choose whether double-clicking moves the slider to a given position.
  34469. By default this is turned off, but it's handy if you want a double-click to act
  34470. as a quick way of resetting a slider. Just pass in the value you want it to
  34471. go to when double-clicked.
  34472. @see getDoubleClickReturnValue
  34473. */
  34474. void setDoubleClickReturnValue (bool isDoubleClickEnabled,
  34475. double valueToSetOnDoubleClick);
  34476. /** Returns the values last set by setDoubleClickReturnValue() method.
  34477. Sets isEnabled to true if double-click is enabled, and returns the value
  34478. that was set.
  34479. @see setDoubleClickReturnValue
  34480. */
  34481. double getDoubleClickReturnValue (bool& isEnabled) const;
  34482. /** Tells the slider whether to keep sending change messages while the user
  34483. is dragging the slider.
  34484. If set to true, a change message will only be sent when the user has
  34485. dragged the slider and let go. If set to false (the default), then messages
  34486. will be continuously sent as they drag it while the mouse button is still
  34487. held down.
  34488. */
  34489. void setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease);
  34490. /** This lets you change whether the slider thumb jumps to the mouse position
  34491. when you click.
  34492. By default, this is true. If it's false, then the slider moves with relative
  34493. motion when you drag it.
  34494. This only applies to linear bars, and won't affect two- or three- value
  34495. sliders.
  34496. */
  34497. void setSliderSnapsToMousePosition (bool shouldSnapToMouse);
  34498. /** If enabled, this gives the slider a pop-up bubble which appears while the
  34499. slider is being dragged.
  34500. This can be handy if your slider doesn't have a text-box, so that users can
  34501. see the value just when they're changing it.
  34502. If you pass a component as the parentComponentToUse parameter, the pop-up
  34503. bubble will be added as a child of that component when it's needed. If you
  34504. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  34505. transparent window, so if you're using an OS that can't do transparent windows
  34506. you'll have to add it to a parent component instead).
  34507. */
  34508. void setPopupDisplayEnabled (bool isEnabled,
  34509. Component* parentComponentToUse);
  34510. /** If this is set to true, then right-clicking on the slider will pop-up
  34511. a menu to let the user change the way it works.
  34512. By default this is turned off, but when turned on, the menu will include
  34513. things like velocity sensitivity, and for rotary sliders, whether they
  34514. use a linear or rotary mouse-drag to move them.
  34515. */
  34516. void setPopupMenuEnabled (bool menuEnabled);
  34517. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  34518. By default it's enabled.
  34519. */
  34520. void setScrollWheelEnabled (bool enabled);
  34521. /** Returns a number to indicate which thumb is currently being dragged by the
  34522. mouse.
  34523. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  34524. the maximum-value thumb, or -1 if none is currently down.
  34525. */
  34526. int getThumbBeingDragged() const { return sliderBeingDragged; }
  34527. /** Callback to indicate that the user is about to start dragging the slider.
  34528. @see SliderListener::sliderDragStarted
  34529. */
  34530. virtual void startedDragging();
  34531. /** Callback to indicate that the user has just stopped dragging the slider.
  34532. @see SliderListener::sliderDragEnded
  34533. */
  34534. virtual void stoppedDragging();
  34535. /** Callback to indicate that the user has just moved the slider.
  34536. @see SliderListener::sliderValueChanged
  34537. */
  34538. virtual void valueChanged();
  34539. /** Subclasses can override this to convert a text string to a value.
  34540. When the user enters something into the text-entry box, this method is
  34541. called to convert it to a value.
  34542. The default routine just tries to convert it to a double.
  34543. @see getTextFromValue
  34544. */
  34545. virtual double getValueFromText (const String& text);
  34546. /** Turns the slider's current value into a text string.
  34547. Subclasses can override this to customise the formatting of the text-entry box.
  34548. The default implementation just turns the value into a string, using
  34549. a number of decimal places based on the range interval. If a suffix string
  34550. has been set using setTextValueSuffix(), this will be appended to the text.
  34551. @see getValueFromText
  34552. */
  34553. virtual const String getTextFromValue (double value);
  34554. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  34555. a string.
  34556. This is used by the default implementation of getTextFromValue(), and is just
  34557. appended to the numeric value. For more advanced formatting, you can override
  34558. getTextFromValue() and do something else.
  34559. */
  34560. void setTextValueSuffix (const String& suffix);
  34561. /** Returns the suffix that was set by setTextValueSuffix(). */
  34562. const String getTextValueSuffix() const;
  34563. /** Allows a user-defined mapping of distance along the slider to its value.
  34564. The default implementation for this performs the skewing operation that
  34565. can be set up in the setSkewFactor() method. Override it if you need
  34566. some kind of custom mapping instead, but make sure you also implement the
  34567. inverse function in valueToProportionOfLength().
  34568. @param proportion a value 0 to 1.0, indicating a distance along the slider
  34569. @returns the slider value that is represented by this position
  34570. @see valueToProportionOfLength
  34571. */
  34572. virtual double proportionOfLengthToValue (double proportion);
  34573. /** Allows a user-defined mapping of value to the position of the slider along its length.
  34574. The default implementation for this performs the skewing operation that
  34575. can be set up in the setSkewFactor() method. Override it if you need
  34576. some kind of custom mapping instead, but make sure you also implement the
  34577. inverse function in proportionOfLengthToValue().
  34578. @param value a valid slider value, between the range of values specified in
  34579. setRange()
  34580. @returns a value 0 to 1.0 indicating the distance along the slider that
  34581. represents this value
  34582. @see proportionOfLengthToValue
  34583. */
  34584. virtual double valueToProportionOfLength (double value);
  34585. /** Returns the X or Y coordinate of a value along the slider's length.
  34586. If the slider is horizontal, this will be the X coordinate of the given
  34587. value, relative to the left of the slider. If it's vertical, then this will
  34588. be the Y coordinate, relative to the top of the slider.
  34589. If the slider is rotary, this will throw an assertion and return 0. If the
  34590. value is out-of-range, it will be constrained to the length of the slider.
  34591. */
  34592. float getPositionOfValue (double value);
  34593. /** This can be overridden to allow the slider to snap to user-definable values.
  34594. If overridden, it will be called when the user tries to move the slider to
  34595. a given position, and allows a subclass to sanity-check this value, possibly
  34596. returning a different value to use instead.
  34597. @param attemptedValue the value the user is trying to enter
  34598. @param userIsDragging true if the user is dragging with the mouse; false if
  34599. they are entering the value using the text box
  34600. @returns the value to use instead
  34601. */
  34602. virtual double snapValue (double attemptedValue, bool userIsDragging);
  34603. /** This can be called to force the text box to update its contents.
  34604. (Not normally needed, as this is done automatically).
  34605. */
  34606. void updateText();
  34607. /** True if the slider moves horizontally. */
  34608. bool isHorizontal() const;
  34609. /** True if the slider moves vertically. */
  34610. bool isVertical() const;
  34611. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  34612. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34613. methods.
  34614. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34615. */
  34616. enum ColourIds
  34617. {
  34618. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  34619. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  34620. and feel class how this is used. */
  34621. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  34622. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  34623. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  34624. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  34625. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  34626. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  34627. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  34628. };
  34629. juce_UseDebuggingNewOperator
  34630. protected:
  34631. /** @internal */
  34632. void labelTextChanged (Label*);
  34633. /** @internal */
  34634. void paint (Graphics& g);
  34635. /** @internal */
  34636. void resized();
  34637. /** @internal */
  34638. void mouseDown (const MouseEvent& e);
  34639. /** @internal */
  34640. void mouseUp (const MouseEvent& e);
  34641. /** @internal */
  34642. void mouseDrag (const MouseEvent& e);
  34643. /** @internal */
  34644. void mouseDoubleClick (const MouseEvent& e);
  34645. /** @internal */
  34646. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34647. /** @internal */
  34648. void modifierKeysChanged (const ModifierKeys& modifiers);
  34649. /** @internal */
  34650. void buttonClicked (Button* button);
  34651. /** @internal */
  34652. void lookAndFeelChanged();
  34653. /** @internal */
  34654. void enablementChanged();
  34655. /** @internal */
  34656. void focusOfChildComponentChanged (FocusChangeType cause);
  34657. /** @internal */
  34658. void handleAsyncUpdate();
  34659. /** @internal */
  34660. void colourChanged();
  34661. /** @internal */
  34662. void valueChanged (Value& value);
  34663. /** Returns the best number of decimal places to use when displaying numbers.
  34664. This is calculated from the slider's interval setting.
  34665. */
  34666. int getNumDecimalPlacesToDisplay() const throw() { return numDecimalPlaces; }
  34667. private:
  34668. ListenerList <SliderListener> listeners;
  34669. Value currentValue, valueMin, valueMax;
  34670. double lastCurrentValue, lastValueMin, lastValueMax;
  34671. double minimum, maximum, interval, doubleClickReturnValue;
  34672. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  34673. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  34674. int velocityModeThreshold;
  34675. float rotaryStart, rotaryEnd;
  34676. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  34677. int mouseDragStartX, mouseDragStartY;
  34678. int sliderRegionStart, sliderRegionSize;
  34679. int sliderBeingDragged;
  34680. int pixelsForFullDragExtent;
  34681. Rectangle<int> sliderRect;
  34682. String textSuffix;
  34683. SliderStyle style;
  34684. TextEntryBoxPosition textBoxPos;
  34685. int textBoxWidth, textBoxHeight;
  34686. IncDecButtonMode incDecButtonMode;
  34687. bool editableText : 1, doubleClickToValue : 1;
  34688. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  34689. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  34690. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  34691. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  34692. Label* valueBox;
  34693. Button* incButton;
  34694. Button* decButton;
  34695. ScopedPointer <Component> popupDisplay;
  34696. Component* parentForPopupDisplay;
  34697. float getLinearSliderPos (double value);
  34698. void restoreMouseIfHidden();
  34699. void sendDragStart();
  34700. void sendDragEnd();
  34701. double constrainedValue (double value) const;
  34702. void triggerChangeMessage (bool synchronous);
  34703. bool incDecDragDirectionIsHorizontal() const;
  34704. Slider (const Slider&);
  34705. Slider& operator= (const Slider&);
  34706. };
  34707. #endif // __JUCE_SLIDER_JUCEHEADER__
  34708. /*** End of inlined file: juce_Slider.h ***/
  34709. #endif
  34710. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  34711. #endif
  34712. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34713. /*** Start of inlined file: juce_TableHeaderComponent.h ***/
  34714. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34715. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34716. class TableHeaderComponent;
  34717. /**
  34718. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  34719. You can register one of these objects for table events using TableHeaderComponent::addListener()
  34720. and TableHeaderComponent::removeListener().
  34721. @see TableHeaderComponent
  34722. */
  34723. class JUCE_API TableHeaderListener
  34724. {
  34725. public:
  34726. TableHeaderListener() {}
  34727. /** Destructor. */
  34728. virtual ~TableHeaderListener() {}
  34729. /** This is called when some of the table's columns are added, removed, hidden,
  34730. or rearranged.
  34731. */
  34732. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  34733. /** This is called when one or more of the table's columns are resized.
  34734. */
  34735. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  34736. /** This is called when the column by which the table should be sorted is changed.
  34737. */
  34738. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  34739. /** This is called when the user begins or ends dragging one of the columns around.
  34740. When the user starts dragging a column, this is called with the ID of that
  34741. column. When they finish dragging, it is called again with 0 as the ID.
  34742. */
  34743. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  34744. int columnIdNowBeingDragged);
  34745. };
  34746. /**
  34747. A component that displays a strip of column headings for a table, and allows these
  34748. to be resized, dragged around, etc.
  34749. This is just the component that goes at the top of a table. You can use it
  34750. directly for custom components, or to create a simple table, use the
  34751. TableListBox class.
  34752. To use one of these, create it and use addColumn() to add all the columns that you need.
  34753. Each column must be given a unique ID number that's used to refer to it.
  34754. @see TableListBox, TableHeaderListener
  34755. */
  34756. class JUCE_API TableHeaderComponent : public Component,
  34757. private AsyncUpdater
  34758. {
  34759. public:
  34760. /** Creates an empty table header.
  34761. */
  34762. TableHeaderComponent();
  34763. /** Destructor. */
  34764. ~TableHeaderComponent();
  34765. /** A combination of these flags are passed into the addColumn() method to specify
  34766. the properties of a column.
  34767. */
  34768. enum ColumnPropertyFlags
  34769. {
  34770. 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. */
  34771. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  34772. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  34773. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  34774. 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. */
  34775. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  34776. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  34777. /** This set of default flags is used as the default parameter value in addColumn(). */
  34778. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  34779. /** A quick way of combining flags for a column that's not resizable. */
  34780. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  34781. /** A quick way of combining flags for a column that's not resizable or sortable. */
  34782. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  34783. /** A quick way of combining flags for a column that's not sortable. */
  34784. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  34785. };
  34786. /** Adds a column to the table.
  34787. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  34788. registered listeners.
  34789. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  34790. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  34791. a unique ID. This is used to identify the column later on, after the user may have
  34792. changed the order that they appear in
  34793. @param width the initial width of the column, in pixels
  34794. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  34795. if the 'resizable' flag is specified for this column
  34796. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  34797. if the 'resizable' flag is specified for this column
  34798. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  34799. properties of this column
  34800. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  34801. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  34802. all columns, not just the index amongst those that are currently visible
  34803. */
  34804. void addColumn (const String& columnName,
  34805. int columnId,
  34806. int width,
  34807. int minimumWidth = 30,
  34808. int maximumWidth = -1,
  34809. int propertyFlags = defaultFlags,
  34810. int insertIndex = -1);
  34811. /** Removes a column with the given ID.
  34812. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  34813. registered listeners.
  34814. */
  34815. void removeColumn (int columnIdToRemove);
  34816. /** Deletes all columns from the table.
  34817. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  34818. registered listeners.
  34819. */
  34820. void removeAllColumns();
  34821. /** Returns the number of columns in the table.
  34822. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  34823. return the total number of columns, including hidden ones.
  34824. @see isColumnVisible
  34825. */
  34826. int getNumColumns (bool onlyCountVisibleColumns) const;
  34827. /** Returns the name for a column.
  34828. @see setColumnName
  34829. */
  34830. const String getColumnName (int columnId) const;
  34831. /** Changes the name of a column. */
  34832. void setColumnName (int columnId, const String& newName);
  34833. /** Moves a column to a different index in the table.
  34834. @param columnId the column to move
  34835. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  34836. */
  34837. void moveColumn (int columnId, int newVisibleIndex);
  34838. /** Returns the width of one of the columns.
  34839. */
  34840. int getColumnWidth (int columnId) const;
  34841. /** Changes the width of a column.
  34842. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  34843. */
  34844. void setColumnWidth (int columnId, int newWidth);
  34845. /** Shows or hides a column.
  34846. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  34847. @see isColumnVisible
  34848. */
  34849. void setColumnVisible (int columnId, bool shouldBeVisible);
  34850. /** Returns true if this column is currently visible.
  34851. @see setColumnVisible
  34852. */
  34853. bool isColumnVisible (int columnId) const;
  34854. /** Changes the column which is the sort column.
  34855. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  34856. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  34857. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  34858. @see getSortColumnId, isSortedForwards, reSortTable
  34859. */
  34860. void setSortColumnId (int columnId, bool sortForwards);
  34861. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  34862. @see setSortColumnId, isSortedForwards
  34863. */
  34864. int getSortColumnId() const;
  34865. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  34866. @see setSortColumnId
  34867. */
  34868. bool isSortedForwards() const;
  34869. /** Triggers a re-sort of the table according to the current sort-column.
  34870. If you modifiy the table's contents, you can call this to signal that the table needs
  34871. to be re-sorted.
  34872. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  34873. tableSortOrderChanged() method of any listeners).
  34874. */
  34875. void reSortTable();
  34876. /** Returns the total width of all the visible columns in the table.
  34877. */
  34878. int getTotalWidth() const;
  34879. /** Returns the index of a given column.
  34880. If there's no such column ID, this will return -1.
  34881. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  34882. otherwise it'll return the index amongst all the columns, including any hidden ones.
  34883. */
  34884. int getIndexOfColumnId (int columnId, bool onlyCountVisibleColumns) const;
  34885. /** Returns the ID of the column at a given index.
  34886. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  34887. otherwise it'll count it amongst all the columns, including any hidden ones.
  34888. If the index is out-of-range, it'll return 0.
  34889. */
  34890. int getColumnIdOfIndex (int index, bool onlyCountVisibleColumns) const;
  34891. /** Returns the rectangle containing of one of the columns.
  34892. The index is an index from 0 to the number of columns that are currently visible (hidden
  34893. ones are not counted). It returns a rectangle showing the position of the column relative
  34894. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  34895. */
  34896. const Rectangle<int> getColumnPosition (int index) const;
  34897. /** Finds the column ID at a given x-position in the component.
  34898. If there is a column at this point this returns its ID, or if not, it will return 0.
  34899. */
  34900. int getColumnIdAtX (int xToFind) const;
  34901. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  34902. entire width of the component.
  34903. By default this is disabled. Turning it on also means that when resizing a column, those
  34904. on the right will be squashed to fit.
  34905. */
  34906. void setStretchToFitActive (bool shouldStretchToFit);
  34907. /** Returns true if stretch-to-fit has been enabled.
  34908. @see setStretchToFitActive
  34909. */
  34910. bool isStretchToFitActive() const;
  34911. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  34912. specified width, keeping their relative proportions the same.
  34913. If the minimum widths of the columns are too wide to fit into this space, it may
  34914. actually end up wider.
  34915. */
  34916. void resizeAllColumnsToFit (int targetTotalWidth);
  34917. /** Enables or disables the pop-up menu.
  34918. The default menu allows the user to show or hide columns. You can add custom
  34919. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  34920. By default the menu is enabled.
  34921. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  34922. */
  34923. void setPopupMenuActive (bool hasMenu);
  34924. /** Returns true if the pop-up menu is enabled.
  34925. @see setPopupMenuActive
  34926. */
  34927. bool isPopupMenuActive() const;
  34928. /** Returns a string that encapsulates the table's current layout.
  34929. This can be restored later using restoreFromString(). It saves the order of
  34930. the columns, the currently-sorted column, and the widths.
  34931. @see restoreFromString
  34932. */
  34933. const String toString() const;
  34934. /** Restores the state of the table, based on a string previously created with
  34935. toString().
  34936. @see toString
  34937. */
  34938. void restoreFromString (const String& storedVersion);
  34939. /** Adds a listener to be informed about things that happen to the header. */
  34940. void addListener (TableHeaderListener* newListener);
  34941. /** Removes a previously-registered listener. */
  34942. void removeListener (TableHeaderListener* listenerToRemove);
  34943. /** This can be overridden to handle a mouse-click on one of the column headers.
  34944. The default implementation will use this click to call getSortColumnId() and
  34945. change the sort order.
  34946. */
  34947. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  34948. /** This can be overridden to add custom items to the pop-up menu.
  34949. If you override this, you should call the superclass's method to add its
  34950. column show/hide items, if you want them on the menu as well.
  34951. Then to handle the result, override reactToMenuItem().
  34952. @see reactToMenuItem
  34953. */
  34954. virtual void addMenuItems (PopupMenu& menu, int columnIdClicked);
  34955. /** Override this to handle any custom items that you have added to the
  34956. pop-up menu with an addMenuItems() override.
  34957. If the menuReturnId isn't one of your own custom menu items, you'll need to
  34958. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  34959. handle the items that it had added.
  34960. @see addMenuItems
  34961. */
  34962. virtual void reactToMenuItem (int menuReturnId, int columnIdClicked);
  34963. /** @internal */
  34964. void paint (Graphics& g);
  34965. /** @internal */
  34966. void resized();
  34967. /** @internal */
  34968. void mouseMove (const MouseEvent&);
  34969. /** @internal */
  34970. void mouseEnter (const MouseEvent&);
  34971. /** @internal */
  34972. void mouseExit (const MouseEvent&);
  34973. /** @internal */
  34974. void mouseDown (const MouseEvent&);
  34975. /** @internal */
  34976. void mouseDrag (const MouseEvent&);
  34977. /** @internal */
  34978. void mouseUp (const MouseEvent&);
  34979. /** @internal */
  34980. const MouseCursor getMouseCursor();
  34981. /** Can be overridden for more control over the pop-up menu behaviour. */
  34982. virtual void showColumnChooserMenu (int columnIdClicked);
  34983. juce_UseDebuggingNewOperator
  34984. private:
  34985. struct ColumnInfo
  34986. {
  34987. String name;
  34988. int id, propertyFlags, width, minimumWidth, maximumWidth;
  34989. double lastDeliberateWidth;
  34990. bool isVisible() const;
  34991. };
  34992. OwnedArray <ColumnInfo> columns;
  34993. Array <TableHeaderListener*> listeners;
  34994. ScopedPointer <Component> dragOverlayComp;
  34995. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  34996. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  34997. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  34998. ColumnInfo* getInfoForId (int columnId) const;
  34999. int visibleIndexToTotalIndex (int visibleIndex) const;
  35000. void sendColumnsChanged();
  35001. void handleAsyncUpdate();
  35002. void beginDrag (const MouseEvent&);
  35003. void endDrag (int finalIndex);
  35004. int getResizeDraggerAt (int mouseX) const;
  35005. void updateColumnUnderMouse (int x, int y);
  35006. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  35007. TableHeaderComponent (const TableHeaderComponent&);
  35008. TableHeaderComponent operator= (const TableHeaderComponent&);
  35009. };
  35010. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35011. /*** End of inlined file: juce_TableHeaderComponent.h ***/
  35012. #endif
  35013. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  35014. /*** Start of inlined file: juce_TableListBox.h ***/
  35015. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  35016. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  35017. /**
  35018. One of these is used by a TableListBox as the data model for the table's contents.
  35019. The virtual methods that you override in this class take care of drawing the
  35020. table cells, and reacting to events.
  35021. @see TableListBox
  35022. */
  35023. class JUCE_API TableListBoxModel
  35024. {
  35025. public:
  35026. TableListBoxModel() {}
  35027. /** Destructor. */
  35028. virtual ~TableListBoxModel() {}
  35029. /** This must return the number of rows currently in the table.
  35030. If the number of rows changes, you must call TableListBox::updateContent() to
  35031. cause it to refresh the list.
  35032. */
  35033. virtual int getNumRows() = 0;
  35034. /** This must draw the background behind one of the rows in the table.
  35035. The graphics context has its origin at the row's top-left, and your method
  35036. should fill the area specified by the width and height parameters.
  35037. */
  35038. virtual void paintRowBackground (Graphics& g,
  35039. int rowNumber,
  35040. int width, int height,
  35041. bool rowIsSelected) = 0;
  35042. /** This must draw one of the cells.
  35043. The graphics context's origin will already be set to the top-left of the cell,
  35044. whose size is specified by (width, height).
  35045. */
  35046. virtual void paintCell (Graphics& g,
  35047. int rowNumber,
  35048. int columnId,
  35049. int width, int height,
  35050. bool rowIsSelected) = 0;
  35051. /** This is used to create or update a custom component to go in a cell.
  35052. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  35053. and handle mouse clicks with cellClicked().
  35054. This method will be called whenever a custom component might need to be updated - e.g.
  35055. when the table is changed, or TableListBox::updateContent() is called.
  35056. If you don't need a custom component for the specified cell, then return 0.
  35057. If you do want a custom component, and the existingComponentToUpdate is null, then
  35058. this method must create a new component suitable for the cell, and return it.
  35059. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  35060. by this method. In this case, the method must either update it to make sure it's correctly representing
  35061. the given cell (which may be different from the one that the component was created for), or it can
  35062. delete this component and return a new one.
  35063. */
  35064. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  35065. Component* existingComponentToUpdate);
  35066. /** This callback is made when the user clicks on one of the cells in the table.
  35067. The mouse event's coordinates will be relative to the entire table row.
  35068. @see cellDoubleClicked, backgroundClicked
  35069. */
  35070. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  35071. /** This callback is made when the user clicks on one of the cells in the table.
  35072. The mouse event's coordinates will be relative to the entire table row.
  35073. @see cellClicked, backgroundClicked
  35074. */
  35075. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  35076. /** This can be overridden to react to the user double-clicking on a part of the list where
  35077. there are no rows.
  35078. @see cellClicked
  35079. */
  35080. virtual void backgroundClicked();
  35081. /** This callback is made when the table's sort order is changed.
  35082. This could be because the user has clicked a column header, or because the
  35083. TableHeaderComponent::setSortColumnId() method was called.
  35084. If you implement this, your method should re-sort the table using the given
  35085. column as the key.
  35086. */
  35087. virtual void sortOrderChanged (int newSortColumnId, bool isForwards);
  35088. /** Returns the best width for one of the columns.
  35089. If you implement this method, you should measure the width of all the items
  35090. in this column, and return the best size.
  35091. Returning 0 means that the column shouldn't be changed.
  35092. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  35093. */
  35094. virtual int getColumnAutoSizeWidth (int columnId);
  35095. /** Returns a tooltip for a particular cell in the table.
  35096. */
  35097. virtual const String getCellTooltip (int rowNumber, int columnId);
  35098. /** Override this to be informed when rows are selected or deselected.
  35099. @see ListBox::selectedRowsChanged()
  35100. */
  35101. virtual void selectedRowsChanged (int lastRowSelected);
  35102. /** Override this to be informed when the delete key is pressed.
  35103. @see ListBox::deleteKeyPressed()
  35104. */
  35105. virtual void deleteKeyPressed (int lastRowSelected);
  35106. /** Override this to be informed when the return key is pressed.
  35107. @see ListBox::returnKeyPressed()
  35108. */
  35109. virtual void returnKeyPressed (int lastRowSelected);
  35110. /** Override this to be informed when the list is scrolled.
  35111. This might be caused by the user moving the scrollbar, or by programmatic changes
  35112. to the list position.
  35113. */
  35114. virtual void listWasScrolled();
  35115. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  35116. If this returns a non-empty name then when the user drags a row, the table will try to
  35117. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  35118. drag-and-drop operation, using this string as the source description, and the listbox
  35119. itself as the source component.
  35120. @see DragAndDropContainer::startDragging
  35121. */
  35122. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  35123. };
  35124. /**
  35125. A table of cells, using a TableHeaderComponent as its header.
  35126. This component makes it easy to create a table by providing a TableListBoxModel as
  35127. the data source.
  35128. @see TableListBoxModel, TableHeaderComponent
  35129. */
  35130. class JUCE_API TableListBox : public ListBox,
  35131. private ListBoxModel,
  35132. private TableHeaderListener
  35133. {
  35134. public:
  35135. /** Creates a TableListBox.
  35136. The model pointer passed-in can be null, in which case you can set it later
  35137. with setModel().
  35138. */
  35139. TableListBox (const String& componentName,
  35140. TableListBoxModel* model);
  35141. /** Destructor. */
  35142. ~TableListBox();
  35143. /** Changes the TableListBoxModel that is being used for this table.
  35144. */
  35145. void setModel (TableListBoxModel* newModel);
  35146. /** Returns the model currently in use. */
  35147. TableListBoxModel* getModel() const { return model; }
  35148. /** Returns the header component being used in this table. */
  35149. TableHeaderComponent* getHeader() const { return header; }
  35150. /** Changes the height of the table header component.
  35151. @see getHeaderHeight
  35152. */
  35153. void setHeaderHeight (int newHeight);
  35154. /** Returns the height of the table header.
  35155. @see setHeaderHeight
  35156. */
  35157. int getHeaderHeight() const;
  35158. /** Resizes a column to fit its contents.
  35159. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  35160. and applies that to the column.
  35161. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  35162. */
  35163. void autoSizeColumn (int columnId);
  35164. /** Calls autoSizeColumn() for all columns in the table. */
  35165. void autoSizeAllColumns();
  35166. /** Enables or disables the auto size options on the popup menu.
  35167. By default, these are enabled.
  35168. */
  35169. void setAutoSizeMenuOptionShown (bool shouldBeShown);
  35170. /** True if the auto-size options should be shown on the menu.
  35171. @see setAutoSizeMenuOptionsShown
  35172. */
  35173. bool isAutoSizeMenuOptionShown() const;
  35174. /** Returns the position of one of the cells in the table.
  35175. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  35176. the table component's top-left. The row number isn't checked to see if it's
  35177. in-range, but the column ID must exist or this will return an empty rectangle.
  35178. If relativeToComponentTopLeft is false, the co-ords are relative to the
  35179. top-left of the table's top-left cell.
  35180. */
  35181. const Rectangle<int> getCellPosition (int columnId,
  35182. int rowNumber,
  35183. bool relativeToComponentTopLeft) const;
  35184. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  35185. @see ListBox::scrollToEnsureRowIsOnscreen
  35186. */
  35187. void scrollToEnsureColumnIsOnscreen (int columnId);
  35188. /** @internal */
  35189. int getNumRows();
  35190. /** @internal */
  35191. void paintListBoxItem (int, Graphics&, int, int, bool);
  35192. /** @internal */
  35193. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  35194. /** @internal */
  35195. void selectedRowsChanged (int lastRowSelected);
  35196. /** @internal */
  35197. void deleteKeyPressed (int currentSelectedRow);
  35198. /** @internal */
  35199. void returnKeyPressed (int currentSelectedRow);
  35200. /** @internal */
  35201. void backgroundClicked();
  35202. /** @internal */
  35203. void listWasScrolled();
  35204. /** @internal */
  35205. void tableColumnsChanged (TableHeaderComponent*);
  35206. /** @internal */
  35207. void tableColumnsResized (TableHeaderComponent*);
  35208. /** @internal */
  35209. void tableSortOrderChanged (TableHeaderComponent*);
  35210. /** @internal */
  35211. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  35212. /** @internal */
  35213. void resized();
  35214. juce_UseDebuggingNewOperator
  35215. private:
  35216. TableHeaderComponent* header;
  35217. TableListBoxModel* model;
  35218. int columnIdNowBeingDragged;
  35219. bool autoSizeOptionsShown;
  35220. void updateColumnComponents() const;
  35221. TableListBox (const TableListBox&);
  35222. TableListBox& operator= (const TableListBox&);
  35223. };
  35224. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  35225. /*** End of inlined file: juce_TableListBox.h ***/
  35226. #endif
  35227. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  35228. #endif
  35229. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  35230. #endif
  35231. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  35232. #endif
  35233. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35234. /*** Start of inlined file: juce_ToolbarItemFactory.h ***/
  35235. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35236. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35237. /**
  35238. A factory object which can create ToolbarItemComponent objects.
  35239. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  35240. that it can create.
  35241. Each type of item is identified by a unique ID, and multiple instances of an
  35242. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  35243. bars).
  35244. @see Toolbar, ToolbarItemComponent, ToolbarButton
  35245. */
  35246. class JUCE_API ToolbarItemFactory
  35247. {
  35248. public:
  35249. ToolbarItemFactory();
  35250. /** Destructor. */
  35251. virtual ~ToolbarItemFactory();
  35252. /** A set of reserved item ID values, used for the built-in item types.
  35253. */
  35254. enum SpecialItemIds
  35255. {
  35256. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  35257. can be placed between sets of items to break them into groups. */
  35258. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  35259. items.*/
  35260. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  35261. either side of it, filling any available space. */
  35262. };
  35263. /** Must return a list of the IDs for all the item types that this factory can create.
  35264. The ids should be added to the array that is passed-in.
  35265. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  35266. and the predefined IDs in the SpecialItemIds enum.
  35267. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  35268. to this list if you want your toolbar to be able to contain those items.
  35269. The list returned here is used by the ToolbarItemPalette class to obtain its list
  35270. of available items, and their order on the palette will reflect the order in which
  35271. they appear on this list.
  35272. @see ToolbarItemPalette
  35273. */
  35274. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  35275. /** Must return the set of items that should be added to a toolbar as its default set.
  35276. This method is used by Toolbar::addDefaultItems() to determine which items to
  35277. create.
  35278. The items that your method adds to the array that is passed-in will be added to the
  35279. toolbar in the same order. Items can appear in the list more than once.
  35280. */
  35281. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  35282. /** Must create an instance of one of the items that the factory lists in its
  35283. getAllToolbarItemIds() method.
  35284. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  35285. method, except for the built-in item types from the SpecialItemIds enum, which
  35286. are created internally by the toolbar code.
  35287. Try not to keep a pointer to the object that is returned, as it will be deleted
  35288. automatically by the toolbar, and remember that multiple instances of the same
  35289. item type are likely to exist at the same time.
  35290. */
  35291. virtual ToolbarItemComponent* createItem (int itemId) = 0;
  35292. };
  35293. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35294. /*** End of inlined file: juce_ToolbarItemFactory.h ***/
  35295. #endif
  35296. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35297. /*** Start of inlined file: juce_ToolbarItemPalette.h ***/
  35298. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35299. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35300. /**
  35301. A component containing a list of toolbar items, which the user can drag onto
  35302. a toolbar to add them.
  35303. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  35304. which automatically shows one of these in a dialog box with lots of extra controls.
  35305. @see Toolbar
  35306. */
  35307. class JUCE_API ToolbarItemPalette : public Component,
  35308. public DragAndDropContainer
  35309. {
  35310. public:
  35311. /** Creates a palette of items for a given factory, with the aim of adding them
  35312. to the specified toolbar.
  35313. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  35314. set of items that are shown in this palette.
  35315. The toolbar and factory must not be deleted while this object exists.
  35316. */
  35317. ToolbarItemPalette (ToolbarItemFactory& factory,
  35318. Toolbar* toolbar);
  35319. /** Destructor. */
  35320. ~ToolbarItemPalette();
  35321. /** @internal */
  35322. void resized();
  35323. juce_UseDebuggingNewOperator
  35324. private:
  35325. ToolbarItemFactory& factory;
  35326. Toolbar* toolbar;
  35327. Viewport* viewport;
  35328. friend class Toolbar;
  35329. void replaceComponent (ToolbarItemComponent* comp);
  35330. ToolbarItemPalette (const ToolbarItemPalette&);
  35331. ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  35332. };
  35333. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35334. /*** End of inlined file: juce_ToolbarItemPalette.h ***/
  35335. #endif
  35336. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  35337. /*** Start of inlined file: juce_TreeView.h ***/
  35338. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  35339. #define __JUCE_TREEVIEW_JUCEHEADER__
  35340. /*** Start of inlined file: juce_FileDragAndDropTarget.h ***/
  35341. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  35342. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  35343. /**
  35344. Components derived from this class can have files dropped onto them by an external application.
  35345. @see DragAndDropContainer
  35346. */
  35347. class JUCE_API FileDragAndDropTarget
  35348. {
  35349. public:
  35350. /** Destructor. */
  35351. virtual ~FileDragAndDropTarget() {}
  35352. /** Callback to check whether this target is interested in the set of files being offered.
  35353. Note that this will be called repeatedly when the user is dragging the mouse around over your
  35354. component, so don't do anything time-consuming in here, like opening the files to have a look
  35355. inside them!
  35356. @param files the set of (absolute) pathnames of the files that the user is dragging
  35357. @returns true if this component wants to receive the other callbacks regarging this
  35358. type of object; if it returns false, no other callbacks will be made.
  35359. */
  35360. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  35361. /** Callback to indicate that some files are being dragged over this component.
  35362. This gets called when the user moves the mouse into this component while dragging.
  35363. Use this callback as a trigger to make your component repaint itself to give the
  35364. user feedback about whether the files can be dropped here or not.
  35365. @param files the set of (absolute) pathnames of the files that the user is dragging
  35366. @param x the mouse x position, relative to this component
  35367. @param y the mouse y position, relative to this component
  35368. */
  35369. virtual void fileDragEnter (const StringArray& files, int x, int y);
  35370. /** Callback to indicate that the user is dragging some files over this component.
  35371. This gets called when the user moves the mouse over this component while dragging.
  35372. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  35373. this lets you know what happens in-between.
  35374. @param files the set of (absolute) pathnames of the files that the user is dragging
  35375. @param x the mouse x position, relative to this component
  35376. @param y the mouse y position, relative to this component
  35377. */
  35378. virtual void fileDragMove (const StringArray& files, int x, int y);
  35379. /** Callback to indicate that the mouse has moved away from this component.
  35380. This gets called when the user moves the mouse out of this component while dragging
  35381. the files.
  35382. If you've used fileDragEnter() to repaint your component and give feedback, use this
  35383. as a signal to repaint it in its normal state.
  35384. @param files the set of (absolute) pathnames of the files that the user is dragging
  35385. */
  35386. virtual void fileDragExit (const StringArray& files);
  35387. /** Callback to indicate that the user has dropped the files onto this component.
  35388. When the user drops the files, this get called, and you can use the files in whatever
  35389. way is appropriate.
  35390. Note that after this is called, the fileDragExit method may not be called, so you should
  35391. clean up in here if there's anything you need to do when the drag finishes.
  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 filesDropped (const StringArray& files, int x, int y) = 0;
  35397. };
  35398. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  35399. /*** End of inlined file: juce_FileDragAndDropTarget.h ***/
  35400. class TreeView;
  35401. /**
  35402. An item in a treeview.
  35403. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  35404. own sub-items.
  35405. To implement an item that contains sub-items, override the itemOpennessChanged()
  35406. method so that when it is opened, it adds the new sub-items to itself using the
  35407. addSubItem method. Depending on the nature of the item it might choose to only
  35408. do this the first time it's opened, or it might want to refresh itself each time.
  35409. It also has the option of deleting its sub-items when it is closed, or leaving them
  35410. in place.
  35411. */
  35412. class JUCE_API TreeViewItem
  35413. {
  35414. public:
  35415. /** Constructor. */
  35416. TreeViewItem();
  35417. /** Destructor. */
  35418. virtual ~TreeViewItem();
  35419. /** Returns the number of sub-items that have been added to this item.
  35420. Note that this doesn't mean much if the node isn't open.
  35421. @see getSubItem, mightContainSubItems, addSubItem
  35422. */
  35423. int getNumSubItems() const throw();
  35424. /** Returns one of the item's sub-items.
  35425. Remember that the object returned might get deleted at any time when its parent
  35426. item is closed or refreshed, depending on the nature of the items you're using.
  35427. @see getNumSubItems
  35428. */
  35429. TreeViewItem* getSubItem (int index) const throw();
  35430. /** Removes any sub-items. */
  35431. void clearSubItems();
  35432. /** Adds a sub-item.
  35433. @param newItem the object to add to the item's sub-item list. Once added, these can be
  35434. found using getSubItem(). When the items are later removed with
  35435. removeSubItem() (or when this item is deleted), they will be deleted.
  35436. @param insertPosition the index which the new item should have when it's added. If this
  35437. value is less than 0, the item will be added to the end of the list.
  35438. */
  35439. void addSubItem (TreeViewItem* newItem, int insertPosition = -1);
  35440. /** Removes one of the sub-items.
  35441. @param index the item to remove
  35442. @param deleteItem if true, the item that is removed will also be deleted.
  35443. */
  35444. void removeSubItem (int index, bool deleteItem = true);
  35445. /** Returns the TreeView to which this item belongs. */
  35446. TreeView* getOwnerView() const throw() { return ownerView; }
  35447. /** Returns the item within which this item is contained. */
  35448. TreeViewItem* getParentItem() const throw() { return parentItem; }
  35449. /** True if this item is currently open in the treeview. */
  35450. bool isOpen() const throw();
  35451. /** Opens or closes the item.
  35452. When opened or closed, the item's itemOpennessChanged() method will be called,
  35453. and a subclass should use this callback to create and add any sub-items that
  35454. it needs to.
  35455. @see itemOpennessChanged, mightContainSubItems
  35456. */
  35457. void setOpen (bool shouldBeOpen);
  35458. /** True if this item is currently selected.
  35459. Use this when painting the node, to decide whether to draw it as selected or not.
  35460. */
  35461. bool isSelected() const throw();
  35462. /** Selects or deselects the item.
  35463. This will cause a callback to itemSelectionChanged()
  35464. */
  35465. void setSelected (bool shouldBeSelected,
  35466. bool deselectOtherItemsFirst);
  35467. /** Returns the rectangle that this item occupies.
  35468. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  35469. top-left of the TreeView comp, so this will depend on the scroll-position of
  35470. the tree. If false, it is relative to the top-left of the topmost item in the
  35471. tree (so this would be unaffected by scrolling the view).
  35472. */
  35473. const Rectangle<int> getItemPosition (bool relativeToTreeViewTopLeft) const throw();
  35474. /** Sends a signal to the treeview to make it refresh itself.
  35475. Call this if your items have changed and you want the tree to update to reflect
  35476. this.
  35477. */
  35478. void treeHasChanged() const throw();
  35479. /** Sends a repaint message to redraw just this item.
  35480. Note that you should only call this if you want to repaint a superficial change. If
  35481. you're altering the tree's nodes, you should instead call treeHasChanged().
  35482. */
  35483. void repaintItem() const;
  35484. /** Returns the row number of this item in the tree.
  35485. The row number of an item will change according to which items are open.
  35486. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  35487. */
  35488. int getRowNumberInTree() const throw();
  35489. /** Returns true if all the item's parent nodes are open.
  35490. This is useful to check whether the item might actually be visible or not.
  35491. */
  35492. bool areAllParentsOpen() const throw();
  35493. /** Changes whether lines are drawn to connect any sub-items to this item.
  35494. By default, line-drawing is turned on.
  35495. */
  35496. void setLinesDrawnForSubItems (bool shouldDrawLines) throw();
  35497. /** Tells the tree whether this item can potentially be opened.
  35498. If your item could contain sub-items, this should return true; if it returns
  35499. false then the tree will not try to open the item. This determines whether or
  35500. not the item will be drawn with a 'plus' button next to it.
  35501. */
  35502. virtual bool mightContainSubItems() = 0;
  35503. /** Returns a string to uniquely identify this item.
  35504. If you're planning on using the TreeView::getOpennessState() method, then
  35505. these strings will be used to identify which nodes are open. The string
  35506. should be unique amongst the item's sibling items, but it's ok for there
  35507. to be duplicates at other levels of the tree.
  35508. If you're not going to store the state, then it's ok not to bother implementing
  35509. this method.
  35510. */
  35511. virtual const String getUniqueName() const;
  35512. /** Called when an item is opened or closed.
  35513. When setOpen() is called and the item has specified that it might
  35514. have sub-items with the mightContainSubItems() method, this method
  35515. is called to let the item create or manage its sub-items.
  35516. So when this is called with isNowOpen set to true (i.e. when the item is being
  35517. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  35518. refresh its sub-item list.
  35519. When this is called with isNowOpen set to false, the subclass might want
  35520. to use clearSubItems() to save on space, or it might choose to leave them,
  35521. depending on the nature of the tree.
  35522. You could also use this callback as a trigger to start a background process
  35523. which asynchronously creates sub-items and adds them, if that's more
  35524. appropriate for the task in hand.
  35525. @see mightContainSubItems
  35526. */
  35527. virtual void itemOpennessChanged (bool isNowOpen);
  35528. /** Must return the width required by this item.
  35529. If your item needs to have a particular width in pixels, return that value; if
  35530. you'd rather have it just fill whatever space is available in the treeview,
  35531. return -1.
  35532. If all your items return -1, no horizontal scrollbar will be shown, but if any
  35533. items have fixed widths and extend beyond the width of the treeview, a
  35534. scrollbar will appear.
  35535. Each item can be a different width, but if they change width, you should call
  35536. treeHasChanged() to update the tree.
  35537. */
  35538. virtual int getItemWidth() const { return -1; }
  35539. /** Must return the height required by this item.
  35540. This is the height in pixels that the item will take up. Items in the tree
  35541. can be different heights, but if they change height, you should call
  35542. treeHasChanged() to update the tree.
  35543. */
  35544. virtual int getItemHeight() const { return 20; }
  35545. /** You can override this method to return false if you don't want to allow the
  35546. user to select this item.
  35547. */
  35548. virtual bool canBeSelected() const { return true; }
  35549. /** Creates a component that will be used to represent this item.
  35550. You don't have to implement this method - if it returns 0 then no component
  35551. will be used for the item, and you can just draw it using the paintItem()
  35552. callback. But if you do return a component, it will be positioned in the
  35553. treeview so that it can be used to represent this item.
  35554. The component returned will be managed by the treeview, so always return
  35555. a new component, and don't keep a reference to it, as the treeview will
  35556. delete it later when it goes off the screen or is no longer needed. Also
  35557. bear in mind that if the component keeps a reference to the item that
  35558. created it, that item could be deleted before the component. Its position
  35559. and size will be completely managed by the tree, so don't attempt to move it
  35560. around.
  35561. Something you may want to do with your component is to give it a pointer to
  35562. the TreeView that created it. This is perfectly safe, and there's no danger
  35563. of it becoming a dangling pointer because the TreeView will always delete
  35564. the component before it is itself deleted.
  35565. As long as you stick to these rules you can return whatever kind of
  35566. component you like. It's most useful if you're doing things like drag-and-drop
  35567. of items, or want to use a Label component to edit item names, etc.
  35568. */
  35569. virtual Component* createItemComponent() { return 0; }
  35570. /** Draws the item's contents.
  35571. You can choose to either implement this method and draw each item, or you
  35572. can use createItemComponent() to create a component that will represent the
  35573. item.
  35574. If all you need in your tree is to be able to draw the items and detect when
  35575. the user selects or double-clicks one of them, it's probably enough to
  35576. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  35577. complicated interactions, you may need to use createItemComponent() instead.
  35578. @param g the graphics context to draw into
  35579. @param width the width of the area available for drawing
  35580. @param height the height of the area available for drawing
  35581. */
  35582. virtual void paintItem (Graphics& g, int width, int height);
  35583. /** Draws the item's open/close button.
  35584. If you don't implement this method, the default behaviour is to
  35585. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  35586. it for custom effects.
  35587. */
  35588. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  35589. /** Called when the user clicks on this item.
  35590. If you're using createItemComponent() to create a custom component for the
  35591. item, the mouse-clicks might not make it through to the treeview, but this
  35592. is how you find out about clicks when just drawing each item individually.
  35593. The associated mouse-event details are passed in, so you can find out about
  35594. which button, where it was, etc.
  35595. @see itemDoubleClicked
  35596. */
  35597. virtual void itemClicked (const MouseEvent& e);
  35598. /** Called when the user double-clicks on this item.
  35599. If you're using createItemComponent() to create a custom component for the
  35600. item, the mouse-clicks might not make it through to the treeview, but this
  35601. is how you find out about clicks when just drawing each item individually.
  35602. The associated mouse-event details are passed in, so you can find out about
  35603. which button, where it was, etc.
  35604. If not overridden, the base class method here will open or close the item as
  35605. if the 'plus' button had been clicked.
  35606. @see itemClicked
  35607. */
  35608. virtual void itemDoubleClicked (const MouseEvent& e);
  35609. /** Called when the item is selected or deselected.
  35610. Use this if you want to do something special when the item's selectedness
  35611. changes. By default it'll get repainted when this happens.
  35612. */
  35613. virtual void itemSelectionChanged (bool isNowSelected);
  35614. /** The item can return a tool tip string here if it wants to.
  35615. @see TooltipClient
  35616. */
  35617. virtual const String getTooltip();
  35618. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  35619. If this returns a non-empty name then when the user drags an item, the treeview will
  35620. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  35621. a drag-and-drop operation, using this string as the source description, with the treeview
  35622. itself as the source component.
  35623. If you need more complex drag-and-drop behaviour, you can use custom components for
  35624. the items, and use those to trigger the drag.
  35625. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  35626. isInterestedInFileDrag(), etc.
  35627. @see DragAndDropContainer::startDragging
  35628. */
  35629. virtual const String getDragSourceDescription();
  35630. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  35631. method and return true.
  35632. If you return true and allow some files to be dropped, you'll also need to implement the
  35633. filesDropped() method to do something with them.
  35634. Note that this will be called often, so make your implementation very quick! There's
  35635. certainly no time to try opening the files and having a think about what's inside them!
  35636. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  35637. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  35638. */
  35639. virtual bool isInterestedInFileDrag (const StringArray& files);
  35640. /** When files are dropped into this item, this callback is invoked.
  35641. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  35642. The insertIndex value indicates where in the list of sub-items the files were dropped.
  35643. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  35644. */
  35645. virtual void filesDropped (const StringArray& files, int insertIndex);
  35646. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  35647. If you implement this method, you'll also need to implement itemDropped() in order to handle
  35648. the items when they are dropped.
  35649. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  35650. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  35651. */
  35652. virtual bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  35653. /** When a things are dropped into this item, this callback is invoked.
  35654. For this to work, you need to have also implemented isInterestedInDragSource().
  35655. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  35656. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  35657. */
  35658. virtual void itemDropped (const String& sourceDescription, Component* sourceComponent, int insertIndex);
  35659. /** Sets a flag to indicate that the item wants to be allowed
  35660. to draw all the way across to the left edge of the treeview.
  35661. By default this is false, which means that when the paintItem()
  35662. method is called, its graphics context is clipped to only allow
  35663. drawing within the item's rectangle. If this flag is set to true,
  35664. then the graphics context isn't clipped on its left side, so it
  35665. can draw all the way across to the left margin. Note that the
  35666. context will still have its origin in the same place though, so
  35667. the coordinates of anything to its left will be negative. It's
  35668. mostly useful if you want to draw a wider bar behind the
  35669. highlighted item.
  35670. */
  35671. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  35672. /** Saves the current state of open/closed nodes so it can be restored later.
  35673. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  35674. and records it as XML. To identify node objects it uses the
  35675. TreeViewItem::getUniqueName() method to create named paths. This
  35676. means that the same state of open/closed nodes can be restored to a
  35677. completely different instance of the tree, as long as it contains nodes
  35678. whose unique names are the same.
  35679. You'd normally want to use TreeView::getOpennessState() rather than call it
  35680. for a specific item, but this can be handy if you need to briefly save the state
  35681. for a section of the tree.
  35682. The caller is responsible for deleting the object that is returned.
  35683. @see TreeView::getOpennessState, restoreOpennessState
  35684. */
  35685. XmlElement* getOpennessState() const throw();
  35686. /** Restores the openness of this item and all its sub-items from a saved state.
  35687. See TreeView::restoreOpennessState for more details.
  35688. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  35689. for a specific item, but this can be handy if you need to briefly save the state
  35690. for a section of the tree.
  35691. @see TreeView::restoreOpennessState, getOpennessState
  35692. */
  35693. void restoreOpennessState (const XmlElement& xml) throw();
  35694. /** Returns the index of this item in its parent's sub-items. */
  35695. int getIndexInParent() const throw();
  35696. /** Returns true if this item is the last of its parent's sub-itens. */
  35697. bool isLastOfSiblings() const throw();
  35698. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  35699. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  35700. The string takes the form of a path, constructed from the getUniqueName() of this
  35701. item and all its parents, so these must all be correctly implemented for it to work.
  35702. @see TreeView::findItemFromIdentifierString, getUniqueName
  35703. */
  35704. const String getItemIdentifierString() const;
  35705. juce_UseDebuggingNewOperator
  35706. private:
  35707. TreeView* ownerView;
  35708. TreeViewItem* parentItem;
  35709. OwnedArray <TreeViewItem> subItems;
  35710. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  35711. int uid;
  35712. bool selected : 1;
  35713. bool redrawNeeded : 1;
  35714. bool drawLinesInside : 1;
  35715. bool drawsInLeftMargin : 1;
  35716. unsigned int openness : 2;
  35717. friend class TreeView;
  35718. friend class TreeViewContentComponent;
  35719. void updatePositions (int newY);
  35720. int getIndentX() const throw();
  35721. void setOwnerView (TreeView* newOwner) throw();
  35722. void paintRecursively (Graphics& g, int width);
  35723. TreeViewItem* getTopLevelItem() throw();
  35724. TreeViewItem* findItemRecursively (int y) throw();
  35725. TreeViewItem* getDeepestOpenParentItem() throw();
  35726. int getNumRows() const throw();
  35727. TreeViewItem* getItemOnRow (int index) throw();
  35728. void deselectAllRecursively();
  35729. int countSelectedItemsRecursively() const throw();
  35730. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  35731. TreeViewItem* getNextVisibleItem (bool recurse) const throw();
  35732. TreeViewItem* findItemFromIdentifierString (const String& identifierString);
  35733. TreeViewItem (const TreeViewItem&);
  35734. TreeViewItem& operator= (const TreeViewItem&);
  35735. };
  35736. /**
  35737. A tree-view component.
  35738. Use one of these to hold and display a structure of TreeViewItem objects.
  35739. */
  35740. class JUCE_API TreeView : public Component,
  35741. public SettableTooltipClient,
  35742. public FileDragAndDropTarget,
  35743. public DragAndDropTarget,
  35744. private AsyncUpdater
  35745. {
  35746. public:
  35747. /** Creates an empty treeview.
  35748. Once you've got a treeview component, you'll need to give it something to
  35749. display, using the setRootItem() method.
  35750. */
  35751. TreeView (const String& componentName = String::empty);
  35752. /** Destructor. */
  35753. ~TreeView();
  35754. /** Sets the item that is displayed in the treeview.
  35755. A tree has a single root item which contains as many sub-items as it needs. If
  35756. you want the tree to contain a number of root items, you should still use a single
  35757. root item above these, but hide it using setRootItemVisible().
  35758. You can pass in 0 to this method to clear the tree and remove its current root item.
  35759. The object passed in will not be deleted by the treeview, it's up to the caller
  35760. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  35761. this item until you've removed it from the tree, either by calling setRootItem (0),
  35762. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  35763. to delete it.
  35764. */
  35765. void setRootItem (TreeViewItem* newRootItem);
  35766. /** Returns the tree's root item.
  35767. This will be the last object passed to setRootItem(), or 0 if none has been set.
  35768. */
  35769. TreeViewItem* getRootItem() const throw() { return rootItem; }
  35770. /** This will remove and delete the current root item.
  35771. It's a convenient way of deleting the item and calling setRootItem (0).
  35772. */
  35773. void deleteRootItem();
  35774. /** Changes whether the tree's root item is shown or not.
  35775. If the root item is hidden, only its sub-items will be shown in the treeview - this
  35776. lets you make the tree look as if it's got many root items. If it's hidden, this call
  35777. will also make sure the root item is open (otherwise the treeview would look empty).
  35778. */
  35779. void setRootItemVisible (bool shouldBeVisible);
  35780. /** Returns true if the root item is visible.
  35781. @see setRootItemVisible
  35782. */
  35783. bool isRootItemVisible() const throw() { return rootItemVisible; }
  35784. /** Sets whether items are open or closed by default.
  35785. Normally, items are closed until the user opens them, but you can use this
  35786. to make them default to being open until explicitly closed.
  35787. @see areItemsOpenByDefault
  35788. */
  35789. void setDefaultOpenness (bool isOpenByDefault);
  35790. /** Returns true if the tree's items default to being open.
  35791. @see setDefaultOpenness
  35792. */
  35793. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  35794. /** This sets a flag to indicate that the tree can be used for multi-selection.
  35795. You can always select multiple items internally by calling the
  35796. TreeViewItem::setSelected() method, but this flag indicates whether the user
  35797. is allowed to multi-select by clicking on the tree.
  35798. By default it is disabled.
  35799. @see isMultiSelectEnabled
  35800. */
  35801. void setMultiSelectEnabled (bool canMultiSelect);
  35802. /** Returns whether multi-select has been enabled for the tree.
  35803. @see setMultiSelectEnabled
  35804. */
  35805. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  35806. /** Sets a flag to indicate whether to hide the open/close buttons.
  35807. @see areOpenCloseButtonsVisible
  35808. */
  35809. void setOpenCloseButtonsVisible (bool shouldBeVisible);
  35810. /** Returns whether open/close buttons are shown.
  35811. @see setOpenCloseButtonsVisible
  35812. */
  35813. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  35814. /** Deselects any items that are currently selected. */
  35815. void clearSelectedItems();
  35816. /** Returns the number of items that are currently selected.
  35817. @see getSelectedItem, clearSelectedItems
  35818. */
  35819. int getNumSelectedItems() const throw();
  35820. /** Returns one of the selected items in the tree.
  35821. @param index the index, 0 to (getNumSelectedItems() - 1)
  35822. */
  35823. TreeViewItem* getSelectedItem (int index) const throw();
  35824. /** Returns the number of rows the tree is using.
  35825. This will depend on which items are open.
  35826. @see TreeViewItem::getRowNumberInTree()
  35827. */
  35828. int getNumRowsInTree() const;
  35829. /** Returns the item on a particular row of the tree.
  35830. If the index is out of range, this will return 0.
  35831. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  35832. */
  35833. TreeViewItem* getItemOnRow (int index) const;
  35834. /** Returns the item that contains a given y position.
  35835. The y is relative to the top of the TreeView component.
  35836. */
  35837. TreeViewItem* getItemAt (int yPosition) const throw();
  35838. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  35839. void scrollToKeepItemVisible (TreeViewItem* item);
  35840. /** Returns the treeview's Viewport object. */
  35841. Viewport* getViewport() const throw();
  35842. /** Returns the number of pixels by which each nested level of the tree is indented.
  35843. @see setIndentSize
  35844. */
  35845. int getIndentSize() const throw() { return indentSize; }
  35846. /** Changes the distance by which each nested level of the tree is indented.
  35847. @see getIndentSize
  35848. */
  35849. void setIndentSize (int newIndentSize);
  35850. /** Searches the tree for an item with the specified identifier.
  35851. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  35852. If no such item exists, this will return false. If the item is found, all of its items
  35853. will be automatically opened.
  35854. */
  35855. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  35856. /** Saves the current state of open/closed nodes so it can be restored later.
  35857. This takes a snapshot of which nodes have been explicitly opened or closed,
  35858. and records it as XML. To identify node objects it uses the
  35859. TreeViewItem::getUniqueName() method to create named paths. This
  35860. means that the same state of open/closed nodes can be restored to a
  35861. completely different instance of the tree, as long as it contains nodes
  35862. whose unique names are the same.
  35863. The caller is responsible for deleting the object that is returned.
  35864. @param alsoIncludeScrollPosition if this is true, the state will also
  35865. include information about where the
  35866. tree has been scrolled to vertically,
  35867. so this can also be restored
  35868. @see restoreOpennessState
  35869. */
  35870. XmlElement* getOpennessState (bool alsoIncludeScrollPosition) const;
  35871. /** Restores a previously saved arrangement of open/closed nodes.
  35872. This will try to restore a snapshot of the tree's state that was created by
  35873. the getOpennessState() method. If any of the nodes named in the original
  35874. XML aren't present in this tree, they will be ignored.
  35875. @see getOpennessState
  35876. */
  35877. void restoreOpennessState (const XmlElement& newState);
  35878. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  35879. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35880. methods.
  35881. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35882. */
  35883. enum ColourIds
  35884. {
  35885. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  35886. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  35887. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  35888. };
  35889. /** @internal */
  35890. void paint (Graphics& g);
  35891. /** @internal */
  35892. void resized();
  35893. /** @internal */
  35894. bool keyPressed (const KeyPress& key);
  35895. /** @internal */
  35896. void colourChanged();
  35897. /** @internal */
  35898. void enablementChanged();
  35899. /** @internal */
  35900. bool isInterestedInFileDrag (const StringArray& files);
  35901. /** @internal */
  35902. void fileDragEnter (const StringArray& files, int x, int y);
  35903. /** @internal */
  35904. void fileDragMove (const StringArray& files, int x, int y);
  35905. /** @internal */
  35906. void fileDragExit (const StringArray& files);
  35907. /** @internal */
  35908. void filesDropped (const StringArray& files, int x, int y);
  35909. /** @internal */
  35910. bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  35911. /** @internal */
  35912. void itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y);
  35913. /** @internal */
  35914. void itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y);
  35915. /** @internal */
  35916. void itemDragExit (const String& sourceDescription, Component* sourceComponent);
  35917. /** @internal */
  35918. void itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y);
  35919. juce_UseDebuggingNewOperator
  35920. private:
  35921. friend class TreeViewItem;
  35922. friend class TreeViewContentComponent;
  35923. class TreeViewport;
  35924. TreeViewport* viewport;
  35925. CriticalSection nodeAlterationLock;
  35926. TreeViewItem* rootItem;
  35927. class InsertPointHighlight;
  35928. class TargetGroupHighlight;
  35929. InsertPointHighlight* dragInsertPointHighlight;
  35930. TargetGroupHighlight* dragTargetGroupHighlight;
  35931. int indentSize;
  35932. bool defaultOpenness : 1;
  35933. bool needsRecalculating : 1;
  35934. bool rootItemVisible : 1;
  35935. bool multiSelectEnabled : 1;
  35936. bool openCloseButtonsVisible : 1;
  35937. void itemsChanged() throw();
  35938. void handleAsyncUpdate();
  35939. void moveSelectedRow (int delta);
  35940. void updateButtonUnderMouse (const MouseEvent& e);
  35941. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw();
  35942. void hideDragHighlight() throw();
  35943. void handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  35944. void handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  35945. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  35946. const StringArray& files, const String& sourceDescription,
  35947. Component* sourceComponent) const throw();
  35948. TreeView (const TreeView&);
  35949. TreeView& operator= (const TreeView&);
  35950. };
  35951. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  35952. /*** End of inlined file: juce_TreeView.h ***/
  35953. #endif
  35954. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  35955. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  35956. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  35957. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  35958. /*** Start of inlined file: juce_DirectoryContentsList.h ***/
  35959. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  35960. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  35961. /*** Start of inlined file: juce_FileFilter.h ***/
  35962. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  35963. #define __JUCE_FILEFILTER_JUCEHEADER__
  35964. /**
  35965. Interface for deciding which files are suitable for something.
  35966. For example, this is used by DirectoryContentsList to select which files
  35967. go into the list.
  35968. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  35969. */
  35970. class JUCE_API FileFilter
  35971. {
  35972. public:
  35973. /** Creates a filter with the given description.
  35974. The description can be returned later with the getDescription() method.
  35975. */
  35976. FileFilter (const String& filterDescription);
  35977. /** Destructor. */
  35978. virtual ~FileFilter();
  35979. /** Returns the description that the filter was created with. */
  35980. const String& getDescription() const throw();
  35981. /** Should return true if this file is suitable for inclusion in whatever context
  35982. the object is being used.
  35983. */
  35984. virtual bool isFileSuitable (const File& file) const = 0;
  35985. /** Should return true if this directory is suitable for inclusion in whatever context
  35986. the object is being used.
  35987. */
  35988. virtual bool isDirectorySuitable (const File& file) const = 0;
  35989. protected:
  35990. String description;
  35991. };
  35992. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  35993. /*** End of inlined file: juce_FileFilter.h ***/
  35994. /**
  35995. A class to asynchronously scan for details about the files in a directory.
  35996. This keeps a list of files and some information about them, using a background
  35997. thread to scan for more files. As files are found, it broadcasts change messages
  35998. to tell any listeners.
  35999. @see FileListComponent, FileBrowserComponent
  36000. */
  36001. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  36002. public TimeSliceClient
  36003. {
  36004. public:
  36005. /** Creates a directory list.
  36006. To set the directory it should point to, use setDirectory(), which will
  36007. also start it scanning for files on the background thread.
  36008. When the background thread finds and adds new files to this list, the
  36009. ChangeBroadcaster class will send a change message, so you can register
  36010. listeners and update them when the list changes.
  36011. @param fileFilter an optional filter to select which files are
  36012. included in the list. If this is 0, then all files
  36013. and directories are included. Make sure that the
  36014. filter doesn't get deleted during the lifetime of this
  36015. object
  36016. @param threadToUse a thread object that this list can use
  36017. to scan for files as a background task. Make sure
  36018. that the thread you give it has been started, or you
  36019. won't get any files!
  36020. */
  36021. DirectoryContentsList (const FileFilter* fileFilter,
  36022. TimeSliceThread& threadToUse);
  36023. /** Destructor. */
  36024. ~DirectoryContentsList();
  36025. /** Sets the directory to look in for files.
  36026. If the directory that's passed in is different to the current one, this will
  36027. also start the background thread scanning it for files.
  36028. */
  36029. void setDirectory (const File& directory,
  36030. bool includeDirectories,
  36031. bool includeFiles);
  36032. /** Returns the directory that's currently being used. */
  36033. const File& getDirectory() const;
  36034. /** Clears the list, and stops the thread scanning for files. */
  36035. void clear();
  36036. /** Clears the list and restarts scanning the directory for files. */
  36037. void refresh();
  36038. /** True if the background thread hasn't yet finished scanning for files. */
  36039. bool isStillLoading() const;
  36040. /** Tells the list whether or not to ignore hidden files.
  36041. By default these are ignored.
  36042. */
  36043. void setIgnoresHiddenFiles (bool shouldIgnoreHiddenFiles);
  36044. /** Returns true if hidden files are ignored.
  36045. @see setIgnoresHiddenFiles
  36046. */
  36047. bool ignoresHiddenFiles() const;
  36048. /** Contains cached information about one of the files in a DirectoryContentsList.
  36049. */
  36050. struct FileInfo
  36051. {
  36052. /** The filename.
  36053. This isn't a full pathname, it's just the last part of the path, same as you'd
  36054. get from File::getFileName().
  36055. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  36056. */
  36057. String filename;
  36058. /** File size in bytes. */
  36059. int64 fileSize;
  36060. /** File modification time.
  36061. As supplied by File::getLastModificationTime().
  36062. */
  36063. Time modificationTime;
  36064. /** File creation time.
  36065. As supplied by File::getCreationTime().
  36066. */
  36067. Time creationTime;
  36068. /** True if the file is a directory. */
  36069. bool isDirectory;
  36070. /** True if the file is read-only. */
  36071. bool isReadOnly;
  36072. };
  36073. /** Returns the number of files currently available in the list.
  36074. The info about one of these files can be retrieved with getFileInfo() or
  36075. getFile().
  36076. Obviously as the background thread runs and scans the directory for files, this
  36077. number will change.
  36078. @see getFileInfo, getFile
  36079. */
  36080. int getNumFiles() const;
  36081. /** Returns the cached information about one of the files in the list.
  36082. If the index is in-range, this will return true and will copy the file's details
  36083. to the structure that is passed-in.
  36084. If it returns false, then the index wasn't in range, and the structure won't
  36085. be affected.
  36086. @see getNumFiles, getFile
  36087. */
  36088. bool getFileInfo (int index, FileInfo& resultInfo) const;
  36089. /** Returns one of the files in the list.
  36090. @param index should be less than getNumFiles(). If this is out-of-range, the
  36091. return value will be File::nonexistent
  36092. @see getNumFiles, getFileInfo
  36093. */
  36094. const File getFile (int index) const;
  36095. /** Returns the file filter being used.
  36096. The filter is specified in the constructor.
  36097. */
  36098. const FileFilter* getFilter() const { return fileFilter; }
  36099. /** @internal */
  36100. bool useTimeSlice();
  36101. /** @internal */
  36102. TimeSliceThread& getTimeSliceThread() { return thread; }
  36103. /** @internal */
  36104. static int compareElements (const DirectoryContentsList::FileInfo* first,
  36105. const DirectoryContentsList::FileInfo* second);
  36106. juce_UseDebuggingNewOperator
  36107. private:
  36108. File root;
  36109. const FileFilter* fileFilter;
  36110. TimeSliceThread& thread;
  36111. int fileTypeFlags;
  36112. CriticalSection fileListLock;
  36113. OwnedArray <FileInfo> files;
  36114. ScopedPointer <DirectoryIterator> fileFindHandle;
  36115. bool volatile shouldStop;
  36116. void changed();
  36117. bool checkNextFile (bool& hasChanged);
  36118. bool addFile (const File& file, bool isDir,
  36119. const int64 fileSize, const Time& modTime,
  36120. const Time& creationTime, bool isReadOnly);
  36121. void setTypeFlags (int newFlags);
  36122. DirectoryContentsList (const DirectoryContentsList&);
  36123. DirectoryContentsList& operator= (const DirectoryContentsList&);
  36124. };
  36125. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36126. /*** End of inlined file: juce_DirectoryContentsList.h ***/
  36127. /*** Start of inlined file: juce_FileBrowserListener.h ***/
  36128. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36129. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36130. /**
  36131. A listener for user selection events in a file browser.
  36132. This is used by a FileBrowserComponent or FileListComponent.
  36133. */
  36134. class JUCE_API FileBrowserListener
  36135. {
  36136. public:
  36137. /** Destructor. */
  36138. virtual ~FileBrowserListener();
  36139. /** Callback when the user selects a different file in the browser. */
  36140. virtual void selectionChanged() = 0;
  36141. /** Callback when the user clicks on a file in the browser. */
  36142. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  36143. /** Callback when the user double-clicks on a file in the browser. */
  36144. virtual void fileDoubleClicked (const File& file) = 0;
  36145. };
  36146. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36147. /*** End of inlined file: juce_FileBrowserListener.h ***/
  36148. /**
  36149. A base class for components that display a list of the files in a directory.
  36150. @see DirectoryContentsList
  36151. */
  36152. class JUCE_API DirectoryContentsDisplayComponent
  36153. {
  36154. public:
  36155. /** Creates a DirectoryContentsDisplayComponent for a given list of files. */
  36156. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  36157. /** Destructor. */
  36158. virtual ~DirectoryContentsDisplayComponent();
  36159. /** Returns the number of files the user has got selected.
  36160. @see getSelectedFile
  36161. */
  36162. virtual int getNumSelectedFiles() const = 0;
  36163. /** Returns one of the files that the user has currently selected.
  36164. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  36165. @see getNumSelectedFiles
  36166. */
  36167. virtual const File getSelectedFile (int index) const = 0;
  36168. /** Deselects any selected files. */
  36169. virtual void deselectAllFiles() = 0;
  36170. /** Scrolls this view to the top. */
  36171. virtual void scrollToTop() = 0;
  36172. /** Adds a listener to be told when files are selected or clicked.
  36173. @see removeListener
  36174. */
  36175. void addListener (FileBrowserListener* listener);
  36176. /** Removes a listener.
  36177. @see addListener
  36178. */
  36179. void removeListener (FileBrowserListener* listener);
  36180. /** A set of colour IDs to use to change the colour of various aspects of the list.
  36181. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36182. methods.
  36183. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36184. */
  36185. enum ColourIds
  36186. {
  36187. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  36188. textColourId = 0x1000541, /**< The colour for the text. */
  36189. };
  36190. /** @internal */
  36191. void sendSelectionChangeMessage();
  36192. /** @internal */
  36193. void sendDoubleClickMessage (const File& file);
  36194. /** @internal */
  36195. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  36196. juce_UseDebuggingNewOperator
  36197. protected:
  36198. DirectoryContentsList& fileList;
  36199. ListenerList <FileBrowserListener> listeners;
  36200. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  36201. DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  36202. };
  36203. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36204. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  36205. #endif
  36206. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36207. #endif
  36208. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36209. /*** Start of inlined file: juce_FileBrowserComponent.h ***/
  36210. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36211. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36212. /*** Start of inlined file: juce_FilePreviewComponent.h ***/
  36213. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36214. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36215. /**
  36216. Base class for components that live inside a file chooser dialog box and
  36217. show previews of the files that get selected.
  36218. One of these allows special extra information to be displayed for files
  36219. in a dialog box as the user selects them. Each time the current file or
  36220. directory is changed, the selectedFileChanged() method will be called
  36221. to allow it to update itself appropriately.
  36222. @see FileChooser, ImagePreviewComponent
  36223. */
  36224. class JUCE_API FilePreviewComponent : public Component
  36225. {
  36226. public:
  36227. /** Creates a FilePreviewComponent. */
  36228. FilePreviewComponent();
  36229. /** Destructor. */
  36230. ~FilePreviewComponent();
  36231. /** Called to indicate that the user's currently selected file has changed.
  36232. @param newSelectedFile the newly selected file or directory, which may be
  36233. File::nonexistent if none is selected.
  36234. */
  36235. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  36236. juce_UseDebuggingNewOperator
  36237. private:
  36238. FilePreviewComponent (const FilePreviewComponent&);
  36239. FilePreviewComponent& operator= (const FilePreviewComponent&);
  36240. };
  36241. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36242. /*** End of inlined file: juce_FilePreviewComponent.h ***/
  36243. /**
  36244. A component for browsing and selecting a file or directory to open or save.
  36245. This contains a FileListComponent and adds various boxes and controls for
  36246. navigating and selecting a file. It can work in different modes so that it can
  36247. be used for loading or saving a file, or for choosing a directory.
  36248. @see FileChooserDialogBox, FileChooser, FileListComponent
  36249. */
  36250. class JUCE_API FileBrowserComponent : public Component,
  36251. public ChangeBroadcaster,
  36252. private FileBrowserListener,
  36253. private TextEditorListener,
  36254. private ButtonListener,
  36255. private ComboBoxListener,
  36256. private FileFilter
  36257. {
  36258. public:
  36259. /** Various options for the browser.
  36260. A combination of these is passed into the FileBrowserComponent constructor.
  36261. */
  36262. enum FileChooserFlags
  36263. {
  36264. openMode = 1, /**< specifies that the component should allow the user to
  36265. choose an existing file with the intention of opening it. */
  36266. saveMode = 2, /**< specifies that the component should allow the user to specify
  36267. the name of a file that will be used to save something. */
  36268. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  36269. conjunction with canSelectDirectories). */
  36270. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  36271. conjuction with canSelectFiles). */
  36272. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  36273. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  36274. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  36275. };
  36276. /** Creates a FileBrowserComponent.
  36277. @param flags A combination of flags from the FileChooserFlags enumeration,
  36278. used to specify the component's behaviour. The flags must contain
  36279. either openMode or saveMode, and canSelectFiles and/or
  36280. canSelectDirectories.
  36281. @param initialFileOrDirectory The file or directory that should be selected when
  36282. the component begins. If this is File::nonexistent,
  36283. a default directory will be chosen.
  36284. @param fileFilter an optional filter to use to determine which files
  36285. are shown. If this is 0 then all files are displayed. Note
  36286. that a pointer is kept internally to this object, so
  36287. make sure that it is not deleted before the browser object
  36288. is deleted.
  36289. @param previewComp an optional preview component that will be used to
  36290. show previews of files that the user selects
  36291. */
  36292. FileBrowserComponent (int flags,
  36293. const File& initialFileOrDirectory,
  36294. const FileFilter* fileFilter,
  36295. FilePreviewComponent* previewComp);
  36296. /** Destructor. */
  36297. ~FileBrowserComponent();
  36298. /** Returns the number of files that the user has got selected.
  36299. If multiple select isn't active, this will only be 0 or 1. To get the complete
  36300. list of files they've chosen, pass an index to getCurrentFile().
  36301. */
  36302. int getNumSelectedFiles() const throw();
  36303. /** Returns one of the files that the user has chosen.
  36304. If the box has multi-select enabled, the index lets you specify which of the files
  36305. to get - see getNumSelectedFiles() to find out how many files were chosen.
  36306. @see getHighlightedFile
  36307. */
  36308. const File getSelectedFile (int index) const throw();
  36309. /** Deselects any files that are currently selected.
  36310. */
  36311. void deselectAllFiles();
  36312. /** Returns true if the currently selected file(s) are usable.
  36313. This can be used to decide whether the user can press "ok" for the
  36314. current file. What it does depends on the mode, so for example in an "open"
  36315. mode, this only returns true if a file has been selected and if it exists.
  36316. In a "save" mode, a non-existent file would also be valid.
  36317. */
  36318. bool currentFileIsValid() const;
  36319. /** This returns the last item in the view that the user has highlighted.
  36320. This may be different from getCurrentFile(), which returns the value
  36321. that is shown in the filename box, and if there are multiple selections,
  36322. this will only return one of them.
  36323. @see getSelectedFile
  36324. */
  36325. const File getHighlightedFile() const throw();
  36326. /** Returns the directory whose contents are currently being shown in the listbox. */
  36327. const File getRoot() const;
  36328. /** Changes the directory that's being shown in the listbox. */
  36329. void setRoot (const File& newRootDirectory);
  36330. /** Equivalent to pressing the "up" button to browse the parent directory. */
  36331. void goUp();
  36332. /** Refreshes the directory that's currently being listed. */
  36333. void refresh();
  36334. /** Returns a verb to describe what should happen when the file is accepted.
  36335. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  36336. mode, it'll be "Save", etc.
  36337. */
  36338. virtual const String getActionVerb() const;
  36339. /** Returns true if the saveMode flag was set when this component was created.
  36340. */
  36341. bool isSaveMode() const throw();
  36342. /** Adds a listener to be told when the user selects and clicks on files.
  36343. @see removeListener
  36344. */
  36345. void addListener (FileBrowserListener* listener);
  36346. /** Removes a listener.
  36347. @see addListener
  36348. */
  36349. void removeListener (FileBrowserListener* listener);
  36350. /** @internal */
  36351. void resized();
  36352. /** @internal */
  36353. void buttonClicked (Button* b);
  36354. /** @internal */
  36355. void comboBoxChanged (ComboBox*);
  36356. /** @internal */
  36357. void textEditorTextChanged (TextEditor& editor);
  36358. /** @internal */
  36359. void textEditorReturnKeyPressed (TextEditor& editor);
  36360. /** @internal */
  36361. void textEditorEscapeKeyPressed (TextEditor& editor);
  36362. /** @internal */
  36363. void textEditorFocusLost (TextEditor& editor);
  36364. /** @internal */
  36365. bool keyPressed (const KeyPress& key);
  36366. /** @internal */
  36367. void selectionChanged();
  36368. /** @internal */
  36369. void fileClicked (const File& f, const MouseEvent& e);
  36370. /** @internal */
  36371. void fileDoubleClicked (const File& f);
  36372. /** @internal */
  36373. bool isFileSuitable (const File& file) const;
  36374. /** @internal */
  36375. bool isDirectorySuitable (const File&) const;
  36376. /** @internal */
  36377. FilePreviewComponent* getPreviewComponent() const throw();
  36378. juce_UseDebuggingNewOperator
  36379. protected:
  36380. virtual const BigInteger getRoots (StringArray& rootNames, StringArray& rootPaths);
  36381. private:
  36382. ScopedPointer <DirectoryContentsList> fileList;
  36383. const FileFilter* fileFilter;
  36384. int flags;
  36385. File currentRoot;
  36386. Array<File> chosenFiles;
  36387. ListenerList <FileBrowserListener> listeners;
  36388. DirectoryContentsDisplayComponent* fileListComponent;
  36389. FilePreviewComponent* previewComp;
  36390. ComboBox* currentPathBox;
  36391. TextEditor* filenameBox;
  36392. Button* goUpButton;
  36393. TimeSliceThread thread;
  36394. void sendListenerChangeMessage();
  36395. bool isFileOrDirSuitable (const File& f) const;
  36396. FileBrowserComponent (const FileBrowserComponent&);
  36397. FileBrowserComponent& operator= (const FileBrowserComponent&);
  36398. };
  36399. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36400. /*** End of inlined file: juce_FileBrowserComponent.h ***/
  36401. #endif
  36402. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36403. #endif
  36404. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36405. /*** Start of inlined file: juce_FileChooser.h ***/
  36406. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36407. #define __JUCE_FILECHOOSER_JUCEHEADER__
  36408. /**
  36409. Creates a dialog box to choose a file or directory to load or save.
  36410. To use a FileChooser:
  36411. - create one (as a local stack variable is the neatest way)
  36412. - call one of its browseFor.. methods
  36413. - if this returns true, the user has selected a file, so you can retrieve it
  36414. with the getResult() method.
  36415. e.g. @code
  36416. void loadMooseFile()
  36417. {
  36418. FileChooser myChooser ("Please select the moose you want to load...",
  36419. File::getSpecialLocation (File::userHomeDirectory),
  36420. "*.moose");
  36421. if (myChooser.browseForFileToOpen())
  36422. {
  36423. File mooseFile (myChooser.getResult());
  36424. loadMoose (mooseFile);
  36425. }
  36426. }
  36427. @endcode
  36428. */
  36429. class JUCE_API FileChooser
  36430. {
  36431. public:
  36432. /** Creates a FileChooser.
  36433. After creating one of these, use one of the browseFor... methods to display it.
  36434. @param dialogBoxTitle a text string to display in the dialog box to
  36435. tell the user what's going on
  36436. @param initialFileOrDirectory the file or directory that should be selected when
  36437. the dialog box opens. If this parameter is set to
  36438. File::nonexistent, a sensible default directory
  36439. will be used instead.
  36440. @param filePatternsAllowed a set of file patterns to specify which files can be
  36441. selected - each pattern should be separated by a
  36442. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  36443. empty string means that all files are allowed
  36444. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  36445. possible; if false, then a Juce-based browser dialog
  36446. box will always be used
  36447. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  36448. */
  36449. FileChooser (const String& dialogBoxTitle,
  36450. const File& initialFileOrDirectory = File::nonexistent,
  36451. const String& filePatternsAllowed = String::empty,
  36452. bool useOSNativeDialogBox = true);
  36453. /** Destructor. */
  36454. ~FileChooser();
  36455. /** Shows a dialog box to choose a file to open.
  36456. This will display the dialog box modally, using an "open file" mode, so that
  36457. it won't allow non-existent files or directories to be chosen.
  36458. @param previewComponent an optional component to display inside the dialog
  36459. box to show special info about the files that the user
  36460. is browsing. The component will not be deleted by this
  36461. object, so the caller must take care of it.
  36462. @returns true if the user selected a file, in which case, use the getResult()
  36463. method to find out what it was. Returns false if they cancelled instead.
  36464. @see browseForFileToSave, browseForDirectory
  36465. */
  36466. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  36467. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  36468. The files that are returned can be obtained by calling getResults(). See
  36469. browseForFileToOpen() for more info about the behaviour of this method.
  36470. */
  36471. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  36472. /** Shows a dialog box to choose a file to save.
  36473. This will display the dialog box modally, using an "save file" mode, so it
  36474. will allow non-existent files to be chosen, but not directories.
  36475. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  36476. the user if they're sure they want to overwrite a file that already
  36477. exists
  36478. @returns true if the user chose a file and pressed 'ok', in which case, use
  36479. the getResult() method to find out what the file was. Returns false
  36480. if they cancelled instead.
  36481. @see browseForFileToOpen, browseForDirectory
  36482. */
  36483. bool browseForFileToSave (bool warnAboutOverwritingExistingFiles);
  36484. /** Shows a dialog box to choose a directory.
  36485. This will display the dialog box modally, using an "open directory" mode, so it
  36486. will only allow directories to be returned, not files.
  36487. @returns true if the user chose a directory and pressed 'ok', in which case, use
  36488. the getResult() method to find out what they chose. Returns false
  36489. if they cancelled instead.
  36490. @see browseForFileToOpen, browseForFileToSave
  36491. */
  36492. bool browseForDirectory();
  36493. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  36494. The files that are returned can be obtained by calling getResults(). See
  36495. browseForFileToOpen() for more info about the behaviour of this method.
  36496. */
  36497. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  36498. /** Returns the last file that was chosen by one of the browseFor methods.
  36499. After calling the appropriate browseFor... method, this method lets you
  36500. find out what file or directory they chose.
  36501. Note that the file returned is only valid if the browse method returned true (i.e.
  36502. if the user pressed 'ok' rather than cancelling).
  36503. If you're using a multiple-file select, then use the getResults() method instead,
  36504. to obtain the list of all files chosen.
  36505. @see getResults
  36506. */
  36507. const File getResult() const;
  36508. /** Returns a list of all the files that were chosen during the last call to a
  36509. browse method.
  36510. This array may be empty if no files were chosen, or can contain multiple entries
  36511. if multiple files were chosen.
  36512. @see getResult
  36513. */
  36514. const Array<File>& getResults() const;
  36515. juce_UseDebuggingNewOperator
  36516. private:
  36517. String title, filters;
  36518. File startingFile;
  36519. Array<File> results;
  36520. bool useNativeDialogBox;
  36521. bool showDialog (bool selectsDirectories, bool selectsFiles, bool isSave,
  36522. bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  36523. FilePreviewComponent* previewComponent);
  36524. static void showPlatformDialog (Array<File>& results, const String& title, const File& file,
  36525. const String& filters, bool selectsDirectories, bool selectsFiles,
  36526. bool isSave, bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  36527. FilePreviewComponent* previewComponent);
  36528. };
  36529. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  36530. /*** End of inlined file: juce_FileChooser.h ***/
  36531. #endif
  36532. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36533. /*** Start of inlined file: juce_FileChooserDialogBox.h ***/
  36534. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36535. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36536. /*** Start of inlined file: juce_ResizableWindow.h ***/
  36537. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36538. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36539. /*** Start of inlined file: juce_TopLevelWindow.h ***/
  36540. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36541. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36542. /*** Start of inlined file: juce_DropShadower.h ***/
  36543. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  36544. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  36545. /**
  36546. Adds a drop-shadow to a component.
  36547. This object creates and manages a set of components which sit around a
  36548. component, creating a gaussian shadow around it. The components will track
  36549. the position of the component and if it's brought to the front they'll also
  36550. follow this.
  36551. For desktop windows you don't need to use this class directly - just
  36552. set the Component::windowHasDropShadow flag when calling
  36553. Component::addToDesktop(), and the system will create one of these if it's
  36554. needed (which it obviously isn't on the Mac, for example).
  36555. */
  36556. class JUCE_API DropShadower : public ComponentListener
  36557. {
  36558. public:
  36559. /** Creates a DropShadower.
  36560. @param alpha the opacity of the shadows, from 0 to 1.0
  36561. @param xOffset the horizontal displacement of the shadow, in pixels
  36562. @param yOffset the vertical displacement of the shadow, in pixels
  36563. @param blurRadius the radius of the blur to use for creating the shadow
  36564. */
  36565. DropShadower (float alpha = 0.5f,
  36566. int xOffset = 1,
  36567. int yOffset = 5,
  36568. float blurRadius = 10.0f);
  36569. /** Destructor. */
  36570. virtual ~DropShadower();
  36571. /** Attaches the DropShadower to the component you want to shadow. */
  36572. void setOwner (Component* componentToFollow);
  36573. /** @internal */
  36574. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  36575. /** @internal */
  36576. void componentBroughtToFront (Component& component);
  36577. /** @internal */
  36578. void componentChildrenChanged (Component& component);
  36579. /** @internal */
  36580. void componentParentHierarchyChanged (Component& component);
  36581. /** @internal */
  36582. void componentVisibilityChanged (Component& component);
  36583. juce_UseDebuggingNewOperator
  36584. private:
  36585. Component* owner;
  36586. int numShadows;
  36587. Component* shadowWindows[4];
  36588. Image shadowImageSections[12];
  36589. const int shadowEdge, xOffset, yOffset;
  36590. const float alpha, blurRadius;
  36591. bool inDestructor, reentrant;
  36592. void updateShadows();
  36593. void setShadowImage (const Image& src,
  36594. const int num,
  36595. const int w, const int h,
  36596. const int sx, const int sy);
  36597. void bringShadowWindowsToFront();
  36598. void deleteShadowWindows();
  36599. DropShadower (const DropShadower&);
  36600. DropShadower& operator= (const DropShadower&);
  36601. };
  36602. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  36603. /*** End of inlined file: juce_DropShadower.h ***/
  36604. /**
  36605. A base class for top-level windows.
  36606. This class is used for components that are considered a major part of your
  36607. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  36608. etc. Things like menus that pop up briefly aren't derived from it.
  36609. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  36610. could itself be the child of another component.
  36611. The class manages a list of all instances of top-level windows that are in use,
  36612. and each one is also given the concept of being "active". The active window is
  36613. one that is actively being used by the user. This isn't quite the same as the
  36614. component with the keyboard focus, because there may be a popup menu or other
  36615. temporary window which gets keyboard focus while the active top level window is
  36616. unchanged.
  36617. A top-level window also has an optional drop-shadow.
  36618. @see ResizableWindow, DocumentWindow, DialogWindow
  36619. */
  36620. class JUCE_API TopLevelWindow : public Component
  36621. {
  36622. public:
  36623. /** Creates a TopLevelWindow.
  36624. @param name the name to give the component
  36625. @param addToDesktop if true, the window will be automatically added to the
  36626. desktop; if false, you can use it as a child component
  36627. */
  36628. TopLevelWindow (const String& name, bool addToDesktop);
  36629. /** Destructor. */
  36630. ~TopLevelWindow();
  36631. /** True if this is currently the TopLevelWindow that is actively being used.
  36632. This isn't quite the same as having keyboard focus, because the focus may be
  36633. on a child component or a temporary pop-up menu, etc, while this window is
  36634. still considered to be active.
  36635. @see activeWindowStatusChanged
  36636. */
  36637. bool isActiveWindow() const throw() { return windowIsActive_; }
  36638. /** This will set the bounds of the window so that it's centred in front of another
  36639. window.
  36640. If your app has a few windows open and want to pop up a dialog box for one of
  36641. them, you can use this to show it in front of the relevent parent window, which
  36642. is a bit neater than just having it appear in the middle of the screen.
  36643. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  36644. be used instead. If no window is focused, it'll just default to the middle of the
  36645. screen.
  36646. */
  36647. void centreAroundComponent (Component* componentToCentreAround,
  36648. int width, int height);
  36649. /** Turns the drop-shadow on and off. */
  36650. void setDropShadowEnabled (bool useShadow);
  36651. /** Sets whether an OS-native title bar will be used, or a Juce one.
  36652. @see isUsingNativeTitleBar
  36653. */
  36654. void setUsingNativeTitleBar (bool useNativeTitleBar);
  36655. /** Returns true if the window is currently using an OS-native title bar.
  36656. @see setUsingNativeTitleBar
  36657. */
  36658. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  36659. /** Returns the number of TopLevelWindow objects currently in use.
  36660. @see getTopLevelWindow
  36661. */
  36662. static int getNumTopLevelWindows() throw();
  36663. /** Returns one of the TopLevelWindow objects currently in use.
  36664. The index is 0 to (getNumTopLevelWindows() - 1).
  36665. */
  36666. static TopLevelWindow* getTopLevelWindow (int index) throw();
  36667. /** Returns the currently-active top level window.
  36668. There might not be one, of course, so this can return 0.
  36669. */
  36670. static TopLevelWindow* getActiveTopLevelWindow() throw();
  36671. juce_UseDebuggingNewOperator
  36672. /** @internal */
  36673. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  36674. protected:
  36675. /** This callback happens when this window becomes active or inactive.
  36676. @see isActiveWindow
  36677. */
  36678. virtual void activeWindowStatusChanged();
  36679. /** @internal */
  36680. void focusOfChildComponentChanged (FocusChangeType cause);
  36681. /** @internal */
  36682. void parentHierarchyChanged();
  36683. /** @internal */
  36684. void visibilityChanged();
  36685. /** @internal */
  36686. virtual int getDesktopWindowStyleFlags() const;
  36687. /** @internal */
  36688. void recreateDesktopWindow();
  36689. private:
  36690. friend class TopLevelWindowManager;
  36691. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  36692. ScopedPointer <DropShadower> shadower;
  36693. void setWindowActive (bool isNowActive);
  36694. TopLevelWindow (const TopLevelWindow&);
  36695. TopLevelWindow& operator= (const TopLevelWindow&);
  36696. };
  36697. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36698. /*** End of inlined file: juce_TopLevelWindow.h ***/
  36699. /*** Start of inlined file: juce_ComponentDragger.h ***/
  36700. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  36701. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  36702. /*** Start of inlined file: juce_ComponentBoundsConstrainer.h ***/
  36703. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  36704. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  36705. /**
  36706. A class that imposes restrictions on a Component's size or position.
  36707. This is used by classes such as ResizableCornerComponent,
  36708. ResizableBorderComponent and ResizableWindow.
  36709. The base class can impose some basic size and position limits, but you can
  36710. also subclass this for custom uses.
  36711. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  36712. */
  36713. class JUCE_API ComponentBoundsConstrainer
  36714. {
  36715. public:
  36716. /** When first created, the object will not impose any restrictions on the components. */
  36717. ComponentBoundsConstrainer() throw();
  36718. /** Destructor. */
  36719. virtual ~ComponentBoundsConstrainer();
  36720. /** Imposes a minimum width limit. */
  36721. void setMinimumWidth (int minimumWidth) throw();
  36722. /** Returns the current minimum width. */
  36723. int getMinimumWidth() const throw() { return minW; }
  36724. /** Imposes a maximum width limit. */
  36725. void setMaximumWidth (int maximumWidth) throw();
  36726. /** Returns the current maximum width. */
  36727. int getMaximumWidth() const throw() { return maxW; }
  36728. /** Imposes a minimum height limit. */
  36729. void setMinimumHeight (int minimumHeight) throw();
  36730. /** Returns the current minimum height. */
  36731. int getMinimumHeight() const throw() { return minH; }
  36732. /** Imposes a maximum height limit. */
  36733. void setMaximumHeight (int maximumHeight) throw();
  36734. /** Returns the current maximum height. */
  36735. int getMaximumHeight() const throw() { return maxH; }
  36736. /** Imposes a minimum width and height limit. */
  36737. void setMinimumSize (int minimumWidth,
  36738. int minimumHeight) throw();
  36739. /** Imposes a maximum width and height limit. */
  36740. void setMaximumSize (int maximumWidth,
  36741. int maximumHeight) throw();
  36742. /** Set all the maximum and minimum dimensions. */
  36743. void setSizeLimits (int minimumWidth,
  36744. int minimumHeight,
  36745. int maximumWidth,
  36746. int maximumHeight) throw();
  36747. /** Sets the amount by which the component is allowed to go off-screen.
  36748. The values indicate how many pixels must remain on-screen when dragged off
  36749. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  36750. when the component goes off the top of the screen, its y-position will be
  36751. clipped so that there are always at least 10 pixels on-screen. In other words,
  36752. the lowest y-position it can take would be (10 - the component's height).
  36753. If you pass 0 or less for one of these amounts, the component is allowed
  36754. to move beyond that edge completely, with no restrictions at all.
  36755. If you pass a very large number (i.e. larger that the dimensions of the
  36756. component itself), then the component won't be allowed to overlap that
  36757. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  36758. the component will bump into the left side of the screen and go no further.
  36759. */
  36760. void setMinimumOnscreenAmounts (int minimumWhenOffTheTop,
  36761. int minimumWhenOffTheLeft,
  36762. int minimumWhenOffTheBottom,
  36763. int minimumWhenOffTheRight) throw();
  36764. /** Specifies a width-to-height ratio that the resizer should always maintain.
  36765. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  36766. will always be maintained as this multiple of the height.
  36767. @see setResizeLimits
  36768. */
  36769. void setFixedAspectRatio (double widthOverHeight) throw();
  36770. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  36771. If no aspect ratio is being enforced, this will return 0.
  36772. */
  36773. double getFixedAspectRatio() const throw();
  36774. /** This callback changes the given co-ordinates to impose whatever the current
  36775. constraints are set to be.
  36776. @param bounds the target position that should be examined and adjusted
  36777. @param previousBounds the component's current size
  36778. @param limits the region in which the component can be positioned
  36779. @param isStretchingTop whether the top edge of the component is being resized
  36780. @param isStretchingLeft whether the left edge of the component is being resized
  36781. @param isStretchingBottom whether the bottom edge of the component is being resized
  36782. @param isStretchingRight whether the right edge of the component is being resized
  36783. */
  36784. virtual void checkBounds (Rectangle<int>& bounds,
  36785. const Rectangle<int>& previousBounds,
  36786. const Rectangle<int>& limits,
  36787. bool isStretchingTop,
  36788. bool isStretchingLeft,
  36789. bool isStretchingBottom,
  36790. bool isStretchingRight);
  36791. /** This callback happens when the resizer is about to start dragging. */
  36792. virtual void resizeStart();
  36793. /** This callback happens when the resizer has finished dragging. */
  36794. virtual void resizeEnd();
  36795. /** Checks the given bounds, and then sets the component to the corrected size. */
  36796. void setBoundsForComponent (Component* const component,
  36797. const Rectangle<int>& bounds,
  36798. bool isStretchingTop,
  36799. bool isStretchingLeft,
  36800. bool isStretchingBottom,
  36801. bool isStretchingRight);
  36802. /** Performs a check on the current size of a component, and moves or resizes
  36803. it if it fails the constraints.
  36804. */
  36805. void checkComponentBounds (Component* component);
  36806. /** Called by setBoundsForComponent() to apply a new constrained size to a
  36807. component.
  36808. By default this just calls setBounds(), but it virtual in case it's needed for
  36809. extremely cunning purposes.
  36810. */
  36811. virtual void applyBoundsToComponent (Component* component,
  36812. const Rectangle<int>& bounds);
  36813. juce_UseDebuggingNewOperator
  36814. private:
  36815. int minW, maxW, minH, maxH;
  36816. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  36817. double aspectRatio;
  36818. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  36819. ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  36820. };
  36821. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  36822. /*** End of inlined file: juce_ComponentBoundsConstrainer.h ***/
  36823. /**
  36824. An object to take care of the logic for dragging components around with the mouse.
  36825. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  36826. then in your mouseDrag() callback, call dragComponent().
  36827. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  36828. to limit the component's position and keep it on-screen.
  36829. e.g. @code
  36830. class MyDraggableComp
  36831. {
  36832. ComponentDragger myDragger;
  36833. void mouseDown (const MouseEvent& e)
  36834. {
  36835. myDragger.startDraggingComponent (this, 0);
  36836. }
  36837. void mouseDrag (const MouseEvent& e)
  36838. {
  36839. myDragger.dragComponent (this, e);
  36840. }
  36841. };
  36842. @endcode
  36843. */
  36844. class JUCE_API ComponentDragger
  36845. {
  36846. public:
  36847. /** Creates a ComponentDragger. */
  36848. ComponentDragger();
  36849. /** Destructor. */
  36850. virtual ~ComponentDragger();
  36851. /** Call this from your component's mouseDown() method, to prepare for dragging.
  36852. @param componentToDrag the component that you want to drag
  36853. @param constrainer a constrainer object to use to keep the component
  36854. from going offscreen
  36855. @see dragComponent
  36856. */
  36857. void startDraggingComponent (Component* const componentToDrag,
  36858. ComponentBoundsConstrainer* constrainer);
  36859. /** Call this from your mouseDrag() callback to move the component.
  36860. This will move the component, but will first check the validity of the
  36861. component's new position using the checkPosition() method, which you
  36862. can override if you need to enforce special positioning limits on the
  36863. component.
  36864. @param componentToDrag the component that you want to drag
  36865. @param e the current mouse-drag event
  36866. @see dragComponent
  36867. */
  36868. void dragComponent (Component* const componentToDrag,
  36869. const MouseEvent& e);
  36870. juce_UseDebuggingNewOperator
  36871. private:
  36872. ComponentBoundsConstrainer* constrainer;
  36873. Point<int> originalPos;
  36874. ComponentDragger (const ComponentDragger&);
  36875. ComponentDragger& operator= (const ComponentDragger&);
  36876. };
  36877. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  36878. /*** End of inlined file: juce_ComponentDragger.h ***/
  36879. /*** Start of inlined file: juce_ResizableBorderComponent.h ***/
  36880. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36881. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36882. /**
  36883. A component that resizes its parent window when dragged.
  36884. This component forms a frame around the edge of a component, allowing it to
  36885. be dragged by the edges or corners to resize it - like the way windows are
  36886. resized in MSWindows or Linux.
  36887. To use it, just add it to your component, making it fill the entire parent component
  36888. (there's a mouse hit-test that only traps mouse-events which land around the
  36889. edge of the component, so it's even ok to put it on top of any other components
  36890. you're using). Make sure you rescale the resizer component to fill the parent
  36891. each time the parent's size changes.
  36892. @see ResizableCornerComponent
  36893. */
  36894. class JUCE_API ResizableBorderComponent : public Component
  36895. {
  36896. public:
  36897. /** Creates a resizer.
  36898. Pass in the target component which you want to be resized when this one is
  36899. dragged.
  36900. The target component will usually be a parent of the resizer component, but this
  36901. isn't mandatory.
  36902. Remember that when the target component is resized, it'll need to move and
  36903. resize this component to keep it in place, as this won't happen automatically.
  36904. If the constrainer parameter is non-zero, then this object will be used to enforce
  36905. limits on the size and position that the component can be stretched to. Make sure
  36906. that the constrainer isn't deleted while still in use by this object.
  36907. @see ComponentBoundsConstrainer
  36908. */
  36909. ResizableBorderComponent (Component* componentToResize,
  36910. ComponentBoundsConstrainer* constrainer);
  36911. /** Destructor. */
  36912. ~ResizableBorderComponent();
  36913. /** Specifies how many pixels wide the draggable edges of this component are.
  36914. @see getBorderThickness
  36915. */
  36916. void setBorderThickness (const BorderSize& newBorderSize);
  36917. /** Returns the number of pixels wide that the draggable edges of this component are.
  36918. @see setBorderThickness
  36919. */
  36920. const BorderSize getBorderThickness() const;
  36921. /** Represents the different sections of a resizable border, which allow it to
  36922. resized in different ways.
  36923. */
  36924. class Zone
  36925. {
  36926. public:
  36927. enum Zones
  36928. {
  36929. centre = 0,
  36930. left = 1,
  36931. top = 2,
  36932. right = 4,
  36933. bottom = 8
  36934. };
  36935. /** Creates a Zone from a combination of the flags in \enum Zones. */
  36936. explicit Zone (int zoneFlags = 0) throw();
  36937. Zone (const Zone& other) throw();
  36938. Zone& operator= (const Zone& other) throw();
  36939. bool operator== (const Zone& other) const throw();
  36940. bool operator!= (const Zone& other) const throw();
  36941. /** Given a point within a rectangle with a resizable border, this returns the
  36942. zone that the point lies within.
  36943. */
  36944. static const Zone fromPositionOnBorder (const Rectangle<int>& totalSize,
  36945. const BorderSize& border,
  36946. const Point<int>& position);
  36947. /** Returns an appropriate mouse-cursor for this resize zone. */
  36948. const MouseCursor getMouseCursor() const throw();
  36949. /** Returns true if dragging this zone will move the enire object without resizing it. */
  36950. bool isDraggingWholeObject() const throw() { return zone == centre; }
  36951. /** Returns true if dragging this zone will move the object's left edge. */
  36952. bool isDraggingLeftEdge() const throw() { return (zone & left) != 0; }
  36953. /** Returns true if dragging this zone will move the object's right edge. */
  36954. bool isDraggingRightEdge() const throw() { return (zone & right) != 0; }
  36955. /** Returns true if dragging this zone will move the object's top edge. */
  36956. bool isDraggingTopEdge() const throw() { return (zone & top) != 0; }
  36957. /** Returns true if dragging this zone will move the object's bottom edge. */
  36958. bool isDraggingBottomEdge() const throw() { return (zone & bottom) != 0; }
  36959. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  36960. applies to.
  36961. */
  36962. const Rectangle<int> resizeRectangleBy (Rectangle<int> original,
  36963. const Point<int>& distance) const throw();
  36964. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  36965. applies to.
  36966. */
  36967. const Rectangle<float> resizeRectangleBy (Rectangle<float> original,
  36968. const Point<float>& distance) const throw();
  36969. /** Returns the raw flags for this zone. */
  36970. int getZoneFlags() const throw() { return zone; }
  36971. private:
  36972. int zone;
  36973. };
  36974. juce_UseDebuggingNewOperator
  36975. protected:
  36976. /** @internal */
  36977. void paint (Graphics& g);
  36978. /** @internal */
  36979. void mouseEnter (const MouseEvent& e);
  36980. /** @internal */
  36981. void mouseMove (const MouseEvent& e);
  36982. /** @internal */
  36983. void mouseDown (const MouseEvent& e);
  36984. /** @internal */
  36985. void mouseDrag (const MouseEvent& e);
  36986. /** @internal */
  36987. void mouseUp (const MouseEvent& e);
  36988. /** @internal */
  36989. bool hitTest (int x, int y);
  36990. private:
  36991. Component::SafePointer<Component> component;
  36992. ComponentBoundsConstrainer* constrainer;
  36993. BorderSize borderSize;
  36994. Rectangle<int> originalBounds;
  36995. Zone mouseZone;
  36996. void updateMouseZone (const MouseEvent& e);
  36997. ResizableBorderComponent (const ResizableBorderComponent&);
  36998. ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  36999. };
  37000. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  37001. /*** End of inlined file: juce_ResizableBorderComponent.h ***/
  37002. /*** Start of inlined file: juce_ResizableCornerComponent.h ***/
  37003. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37004. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37005. /** A component that resizes a parent window when dragged.
  37006. This is the small triangular stripey resizer component you get in the bottom-right
  37007. of windows (more commonly on the Mac than Windows). Put one in the corner of
  37008. a larger component and it will automatically resize its parent when it gets dragged
  37009. around.
  37010. @see ResizableFrameComponent
  37011. */
  37012. class JUCE_API ResizableCornerComponent : public Component
  37013. {
  37014. public:
  37015. /** Creates a resizer.
  37016. Pass in the target component which you want to be resized when this one is
  37017. dragged.
  37018. The target component will usually be a parent of the resizer component, but this
  37019. isn't mandatory.
  37020. Remember that when the target component is resized, it'll need to move and
  37021. resize this component to keep it in place, as this won't happen automatically.
  37022. If the constrainer parameter is non-zero, then this object will be used to enforce
  37023. limits on the size and position that the component can be stretched to. Make sure
  37024. that the constrainer isn't deleted while still in use by this object. If you
  37025. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  37026. @see ComponentBoundsConstrainer
  37027. */
  37028. ResizableCornerComponent (Component* componentToResize,
  37029. ComponentBoundsConstrainer* constrainer);
  37030. /** Destructor. */
  37031. ~ResizableCornerComponent();
  37032. juce_UseDebuggingNewOperator
  37033. protected:
  37034. /** @internal */
  37035. void paint (Graphics& g);
  37036. /** @internal */
  37037. void mouseDown (const MouseEvent& e);
  37038. /** @internal */
  37039. void mouseDrag (const MouseEvent& e);
  37040. /** @internal */
  37041. void mouseUp (const MouseEvent& e);
  37042. /** @internal */
  37043. bool hitTest (int x, int y);
  37044. private:
  37045. Component::SafePointer<Component> component;
  37046. ComponentBoundsConstrainer* constrainer;
  37047. Rectangle<int> originalBounds;
  37048. ResizableCornerComponent (const ResizableCornerComponent&);
  37049. ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  37050. };
  37051. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37052. /*** End of inlined file: juce_ResizableCornerComponent.h ***/
  37053. /**
  37054. A base class for top-level windows that can be dragged around and resized.
  37055. To add content to the window, use its setContentComponent() method to
  37056. give it a component that will remain positioned inside it (leaving a gap around
  37057. the edges for a border).
  37058. It's not advisable to add child components directly to a ResizableWindow: put them
  37059. inside your content component instead. And overriding methods like resized(), moved(), etc
  37060. is also not recommended - instead override these methods for your content component.
  37061. (If for some obscure reason you do need to override these methods, always remember to
  37062. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  37063. decorations correctly).
  37064. By default resizing isn't enabled - use the setResizable() method to enable it and
  37065. to choose the style of resizing to use.
  37066. @see TopLevelWindow
  37067. */
  37068. class JUCE_API ResizableWindow : public TopLevelWindow
  37069. {
  37070. public:
  37071. /** Creates a ResizableWindow.
  37072. This constructor doesn't specify a background colour, so the LookAndFeel's default
  37073. background colour will be used.
  37074. @param name the name to give the component
  37075. @param addToDesktop if true, the window will be automatically added to the
  37076. desktop; if false, you can use it as a child component
  37077. */
  37078. ResizableWindow (const String& name,
  37079. bool addToDesktop);
  37080. /** Creates a ResizableWindow.
  37081. @param name the name to give the component
  37082. @param backgroundColour the colour to use for filling the window's background.
  37083. @param addToDesktop if true, the window will be automatically added to the
  37084. desktop; if false, you can use it as a child component
  37085. */
  37086. ResizableWindow (const String& name,
  37087. const Colour& backgroundColour,
  37088. bool addToDesktop);
  37089. /** Destructor.
  37090. If a content component has been set with setContentComponent(), it
  37091. will be deleted.
  37092. */
  37093. ~ResizableWindow();
  37094. /** Returns the colour currently being used for the window's background.
  37095. As a convenience the window will fill itself with this colour, but you
  37096. can override the paint() method if you need more customised behaviour.
  37097. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  37098. @see setBackgroundColour
  37099. */
  37100. const Colour getBackgroundColour() const throw();
  37101. /** Changes the colour currently being used for the window's background.
  37102. As a convenience the window will fill itself with this colour, but you
  37103. can override the paint() method if you need more customised behaviour.
  37104. Note that the opaque state of this window is altered by this call to reflect
  37105. the opacity of the colour passed-in. On window systems which can't support
  37106. semi-transparent windows this might cause problems, (though it's unlikely you'll
  37107. be using this class as a base for a semi-transparent component anyway).
  37108. You can also use the ResizableWindow::backgroundColourId colour id to set
  37109. this colour.
  37110. @see getBackgroundColour
  37111. */
  37112. void setBackgroundColour (const Colour& newColour);
  37113. /** Make the window resizable or fixed.
  37114. @param shouldBeResizable whether it's resizable at all
  37115. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  37116. bottom-right; if false, it'll use a ResizableBorderComponent
  37117. around the edge
  37118. @see setResizeLimits, isResizable
  37119. */
  37120. void setResizable (bool shouldBeResizable,
  37121. bool useBottomRightCornerResizer);
  37122. /** True if resizing is enabled.
  37123. @see setResizable
  37124. */
  37125. bool isResizable() const throw();
  37126. /** This sets the maximum and minimum sizes for the window.
  37127. If the window's current size is outside these limits, it will be resized to
  37128. make sure it's within them.
  37129. Calling setBounds() on the component will bypass any size checking - it's only when
  37130. the window is being resized by the user that these values are enforced.
  37131. @see setResizable, setFixedAspectRatio
  37132. */
  37133. void setResizeLimits (int newMinimumWidth,
  37134. int newMinimumHeight,
  37135. int newMaximumWidth,
  37136. int newMaximumHeight) throw();
  37137. /** Returns the bounds constrainer object that this window is using.
  37138. You can access this to change its properties.
  37139. */
  37140. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  37141. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  37142. A pointer to the object you pass in will be kept, but it won't be deleted
  37143. by this object, so it's the caller's responsiblity to manage it.
  37144. If you pass 0, then no contraints will be placed on the positioning of the window.
  37145. */
  37146. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  37147. /** Calls the window's setBounds method, after first checking these bounds
  37148. with the current constrainer.
  37149. @see setConstrainer
  37150. */
  37151. void setBoundsConstrained (const Rectangle<int>& bounds);
  37152. /** Returns true if the window is currently in full-screen mode.
  37153. @see setFullScreen
  37154. */
  37155. bool isFullScreen() const;
  37156. /** Puts the window into full-screen mode, or restores it to its normal size.
  37157. If true, the window will become full-screen; if false, it will return to the
  37158. last size it was before being made full-screen.
  37159. @see isFullScreen
  37160. */
  37161. void setFullScreen (bool shouldBeFullScreen);
  37162. /** Returns true if the window is currently minimised.
  37163. @see setMinimised
  37164. */
  37165. bool isMinimised() const;
  37166. /** Minimises the window, or restores it to its previous position and size.
  37167. When being un-minimised, it'll return to the last position and size it
  37168. was in before being minimised.
  37169. @see isMinimised
  37170. */
  37171. void setMinimised (bool shouldMinimise);
  37172. /** Returns a string which encodes the window's current size and position.
  37173. This string will encapsulate the window's size, position, and whether it's
  37174. in full-screen mode. It's intended for letting your application save and
  37175. restore a window's position.
  37176. Use the restoreWindowStateFromString() to restore from a saved state.
  37177. @see restoreWindowStateFromString
  37178. */
  37179. const String getWindowStateAsString();
  37180. /** Restores the window to a previously-saved size and position.
  37181. This restores the window's size, positon and full-screen status from an
  37182. string that was previously created with the getWindowStateAsString()
  37183. method.
  37184. @returns false if the string wasn't a valid window state
  37185. @see getWindowStateAsString
  37186. */
  37187. bool restoreWindowStateFromString (const String& previousState);
  37188. /** Returns the current content component.
  37189. This will be the component set by setContentComponent(), or 0 if none
  37190. has yet been specified.
  37191. @see setContentComponent
  37192. */
  37193. Component* getContentComponent() const throw() { return contentComponent; }
  37194. /** Changes the current content component.
  37195. This sets a component that will be placed in the centre of the ResizableWindow,
  37196. (leaving a space around the edge for the border).
  37197. You should never add components directly to a ResizableWindow (or any of its subclasses)
  37198. with addChildComponent(). Instead, add them to the content component.
  37199. @param newContentComponent the new component to use (or null to not use one) - this
  37200. component will be deleted either when replaced by another call
  37201. to this method, or when the ResizableWindow is deleted.
  37202. To remove a content component without deleting it, use
  37203. setContentComponent (0, false).
  37204. @param deleteOldOne if true, the previous content component will be deleted; if
  37205. false, the previous component will just be removed without
  37206. deleting it.
  37207. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  37208. it always fits around the size of the content component. If false, the
  37209. new content will be resized to fit the current space available.
  37210. */
  37211. void setContentComponent (Component* newContentComponent,
  37212. bool deleteOldOne = true,
  37213. bool resizeToFit = false);
  37214. /** Changes the window so that the content component ends up with the specified size.
  37215. This is basically a setSize call on the window, but which adds on the borders,
  37216. so you can specify the content component's target size.
  37217. */
  37218. void setContentComponentSize (int width, int height);
  37219. /** A set of colour IDs to use to change the colour of various aspects of the window.
  37220. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37221. methods.
  37222. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37223. */
  37224. enum ColourIds
  37225. {
  37226. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  37227. };
  37228. juce_UseDebuggingNewOperator
  37229. protected:
  37230. /** @internal */
  37231. void paint (Graphics& g);
  37232. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  37233. void moved();
  37234. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  37235. void resized();
  37236. /** @internal */
  37237. void mouseDown (const MouseEvent& e);
  37238. /** @internal */
  37239. void mouseDrag (const MouseEvent& e);
  37240. /** @internal */
  37241. void lookAndFeelChanged();
  37242. /** @internal */
  37243. void childBoundsChanged (Component* child);
  37244. /** @internal */
  37245. void parentSizeChanged();
  37246. /** @internal */
  37247. void visibilityChanged();
  37248. /** @internal */
  37249. void activeWindowStatusChanged();
  37250. /** @internal */
  37251. int getDesktopWindowStyleFlags() const;
  37252. /** Returns the width of the border to use around the window.
  37253. @see getContentComponentBorder
  37254. */
  37255. virtual const BorderSize getBorderThickness();
  37256. /** Returns the insets to use when positioning the content component.
  37257. @see getBorderThickness
  37258. */
  37259. virtual const BorderSize getContentComponentBorder();
  37260. #if JUCE_DEBUG
  37261. /** Overridden to warn people about adding components directly to this component
  37262. instead of using setContentComponent().
  37263. If you know what you're doing and are sure you really want to add a component, specify
  37264. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  37265. */
  37266. void addChildComponent (Component* child, int zOrder = -1);
  37267. /** Overridden to warn people about adding components directly to this component
  37268. instead of using setContentComponent().
  37269. If you know what you're doing and are sure you really want to add a component, specify
  37270. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  37271. */
  37272. void addAndMakeVisible (Component* child, int zOrder = -1);
  37273. #endif
  37274. ScopedPointer <ResizableCornerComponent> resizableCorner;
  37275. ScopedPointer <ResizableBorderComponent> resizableBorder;
  37276. private:
  37277. ScopedPointer <Component> contentComponent;
  37278. bool resizeToFitContent, fullscreen;
  37279. ComponentDragger dragger;
  37280. Rectangle<int> lastNonFullScreenPos;
  37281. ComponentBoundsConstrainer defaultConstrainer;
  37282. ComponentBoundsConstrainer* constrainer;
  37283. #if JUCE_DEBUG
  37284. bool hasBeenResized;
  37285. #endif
  37286. void updateLastPos();
  37287. ResizableWindow (const ResizableWindow&);
  37288. ResizableWindow& operator= (const ResizableWindow&);
  37289. // (xxx remove these eventually)
  37290. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  37291. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  37292. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  37293. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  37294. };
  37295. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  37296. /*** End of inlined file: juce_ResizableWindow.h ***/
  37297. /*** Start of inlined file: juce_GlyphArrangement.h ***/
  37298. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  37299. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  37300. /**
  37301. A glyph from a particular font, with a particular size, style,
  37302. typeface and position.
  37303. @see GlyphArrangement, Font
  37304. */
  37305. class JUCE_API PositionedGlyph
  37306. {
  37307. public:
  37308. PositionedGlyph (const PositionedGlyph& other);
  37309. /** Returns the character the glyph represents. */
  37310. juce_wchar getCharacter() const { return character; }
  37311. /** Checks whether the glyph is actually empty. */
  37312. bool isWhitespace() const { return CharacterFunctions::isWhitespace (character); }
  37313. /** Returns the position of the glyph's left-hand edge. */
  37314. float getLeft() const { return x; }
  37315. /** Returns the position of the glyph's right-hand edge. */
  37316. float getRight() const { return x + w; }
  37317. /** Returns the y position of the glyph's baseline. */
  37318. float getBaselineY() const { return y; }
  37319. /** Returns the y position of the top of the glyph. */
  37320. float getTop() const { return y - font.getAscent(); }
  37321. /** Returns the y position of the bottom of the glyph. */
  37322. float getBottom() const { return y + font.getDescent(); }
  37323. /** Returns the bounds of the glyph. */
  37324. const Rectangle<float> getBounds() const { return Rectangle<float> (x, getTop(), w, font.getHeight()); }
  37325. /** Shifts the glyph's position by a relative amount. */
  37326. void moveBy (float deltaX, float deltaY);
  37327. /** Draws the glyph into a graphics context. */
  37328. void draw (const Graphics& g) const;
  37329. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  37330. void draw (const Graphics& g, const AffineTransform& transform) const;
  37331. /** Returns the path for this glyph.
  37332. @param path the glyph's outline will be appended to this path
  37333. */
  37334. void createPath (Path& path) const;
  37335. /** Checks to see if a point lies within this glyph. */
  37336. bool hitTest (float x, float y) const;
  37337. juce_UseDebuggingNewOperator
  37338. private:
  37339. friend class GlyphArrangement;
  37340. float x, y, w;
  37341. Font font;
  37342. juce_wchar character;
  37343. int glyph;
  37344. PositionedGlyph (float x, float y, float w, const Font& font, juce_wchar character, int glyph);
  37345. };
  37346. /**
  37347. A set of glyphs, each with a position.
  37348. You can create a GlyphArrangement, text to it and then draw it onto a
  37349. graphics context. It's used internally by the text methods in the
  37350. Graphics class, but can be used directly if more control is needed.
  37351. @see Font, PositionedGlyph
  37352. */
  37353. class JUCE_API GlyphArrangement
  37354. {
  37355. public:
  37356. /** Creates an empty arrangement. */
  37357. GlyphArrangement();
  37358. /** Takes a copy of another arrangement. */
  37359. GlyphArrangement (const GlyphArrangement& other);
  37360. /** Copies another arrangement onto this one.
  37361. To add another arrangement without clearing this one, use addGlyphArrangement().
  37362. */
  37363. GlyphArrangement& operator= (const GlyphArrangement& other);
  37364. /** Destructor. */
  37365. ~GlyphArrangement();
  37366. /** Returns the total number of glyphs in the arrangement. */
  37367. int getNumGlyphs() const throw() { return glyphs.size(); }
  37368. /** Returns one of the glyphs from the arrangement.
  37369. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  37370. careful not to pass an out-of-range index here, as it
  37371. doesn't do any bounds-checking.
  37372. */
  37373. PositionedGlyph& getGlyph (int index) const;
  37374. /** Clears all text from the arrangement and resets it.
  37375. */
  37376. void clear();
  37377. /** Appends a line of text to the arrangement.
  37378. This will add the text as a single line, where x is the left-hand edge of the
  37379. first character, and y is the position for the text's baseline.
  37380. If the text contains new-lines or carriage-returns, this will ignore them - use
  37381. addJustifiedText() to add multi-line arrangements.
  37382. */
  37383. void addLineOfText (const Font& font,
  37384. const String& text,
  37385. float x, float y);
  37386. /** Adds a line of text, truncating it if it's wider than a specified size.
  37387. This is the same as addLineOfText(), but if the line's width exceeds the value
  37388. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  37389. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  37390. */
  37391. void addCurtailedLineOfText (const Font& font,
  37392. const String& text,
  37393. float x, float y,
  37394. float maxWidthPixels,
  37395. bool useEllipsis);
  37396. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  37397. This will add text to the arrangement, breaking it into new lines either where there
  37398. is a new-line or carriage-return character in the text, or where a line's width
  37399. exceeds the value set in maxLineWidth.
  37400. Each line that is added will be laid out using the flags set in horizontalLayout, so
  37401. the lines can be left- or right-justified, or centred horizontally in the space
  37402. between x and (x + maxLineWidth).
  37403. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  37404. lines will be placed below it, separated by a distance of font.getHeight().
  37405. */
  37406. void addJustifiedText (const Font& font,
  37407. const String& text,
  37408. float x, float y,
  37409. float maxLineWidth,
  37410. const Justification& horizontalLayout);
  37411. /** Tries to fit some text withing a given space.
  37412. This does its best to make the given text readable within the specified rectangle,
  37413. so it useful for labelling things.
  37414. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  37415. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  37416. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  37417. it's been truncated.
  37418. A Justification parameter lets you specify how the text is laid out within the rectangle,
  37419. both horizontally and vertically.
  37420. @see Graphics::drawFittedText
  37421. */
  37422. void addFittedText (const Font& font,
  37423. const String& text,
  37424. float x, float y, float width, float height,
  37425. const Justification& layout,
  37426. int maximumLinesToUse,
  37427. float minimumHorizontalScale = 0.7f);
  37428. /** Appends another glyph arrangement to this one. */
  37429. void addGlyphArrangement (const GlyphArrangement& other);
  37430. /** Draws this glyph arrangement to a graphics context.
  37431. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  37432. method, which renders the glyphs as filled vectors.
  37433. */
  37434. void draw (const Graphics& g) const;
  37435. /** Draws this glyph arrangement to a graphics context.
  37436. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  37437. method for non-transformed arrangements.
  37438. */
  37439. void draw (const Graphics& g, const AffineTransform& transform) const;
  37440. /** Converts the set of glyphs into a path.
  37441. @param path the glyphs' outlines will be appended to this path
  37442. */
  37443. void createPath (Path& path) const;
  37444. /** Looks for a glyph that contains the given co-ordinate.
  37445. @returns the index of the glyph, or -1 if none were found.
  37446. */
  37447. int findGlyphIndexAt (float x, float y) const;
  37448. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  37449. @param startIndex the first glyph to test
  37450. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  37451. startIndex will be included
  37452. @param includeWhitespace if true, the extent of any whitespace characters will also
  37453. be taken into account
  37454. */
  37455. const Rectangle<float> getBoundingBox (int startIndex, int numGlyphs, bool includeWhitespace) const;
  37456. /** Shifts a set of glyphs by a given amount.
  37457. @param startIndex the first glyph to transform
  37458. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  37459. startIndex will be used
  37460. @param deltaX the amount to add to their x-positions
  37461. @param deltaY the amount to add to their y-positions
  37462. */
  37463. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  37464. float deltaX, float deltaY);
  37465. /** Removes a set of glyphs from the arrangement.
  37466. @param startIndex the first glyph to remove
  37467. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  37468. startIndex will be deleted
  37469. */
  37470. void removeRangeOfGlyphs (int startIndex, int numGlyphs);
  37471. /** Expands or compresses a set of glyphs horizontally.
  37472. @param startIndex the first glyph to transform
  37473. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  37474. startIndex will be used
  37475. @param horizontalScaleFactor how much to scale their horizontal width by
  37476. */
  37477. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  37478. float horizontalScaleFactor);
  37479. /** Justifies a set of glyphs within a given space.
  37480. This moves the glyphs as a block so that the whole thing is located within the
  37481. given rectangle with the specified layout.
  37482. If the Justification::horizontallyJustified flag is specified, each line will
  37483. be stretched out to fill the specified width.
  37484. */
  37485. void justifyGlyphs (int startIndex, int numGlyphs,
  37486. float x, float y, float width, float height,
  37487. const Justification& justification);
  37488. juce_UseDebuggingNewOperator
  37489. private:
  37490. OwnedArray <PositionedGlyph> glyphs;
  37491. int insertEllipsis (const Font& font, float maxXPos, int startIndex, int endIndex);
  37492. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  37493. const Justification& justification, float minimumHorizontalScale);
  37494. void spreadOutLine (int start, int numGlyphs, float targetWidth);
  37495. };
  37496. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  37497. /*** End of inlined file: juce_GlyphArrangement.h ***/
  37498. /**
  37499. A file open/save dialog box.
  37500. This is a Juce-based file dialog box; to use a native file chooser, see the
  37501. FileChooser class.
  37502. To use one of these, create it and call its show() method. e.g.
  37503. @code
  37504. {
  37505. WildcardFileFilter wildcardFilter ("*.foo", "Foo files");
  37506. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  37507. File::nonexistent,
  37508. &wildcardFilter,
  37509. 0);
  37510. FileChooserDialogBox dialogBox ("Open some kind of file",
  37511. "Please choose some kind of file that you want to open...",
  37512. browser,
  37513. getLookAndFeel().alertWindowBackground);
  37514. if (dialogBox.show())
  37515. {
  37516. File selectedFile = browser.getCurrentFile();
  37517. ...
  37518. }
  37519. }
  37520. @endcode
  37521. @see FileChooser
  37522. */
  37523. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  37524. public ButtonListener,
  37525. public FileBrowserListener
  37526. {
  37527. public:
  37528. /** Creates a file chooser box.
  37529. @param title the main title to show at the top of the box
  37530. @param instructions an optional longer piece of text to show below the title in
  37531. a smaller font, describing in more detail what's required.
  37532. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  37533. box. Make sure you delete this after (but not before!) the
  37534. dialog box has been deleted.
  37535. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  37536. if they try to select a file that already exists. (This
  37537. flag is only used when saving files)
  37538. @param backgroundColour the background colour for the top level window
  37539. @see FileBrowserComponent, FilePreviewComponent
  37540. */
  37541. FileChooserDialogBox (const String& title,
  37542. const String& instructions,
  37543. FileBrowserComponent& browserComponent,
  37544. bool warnAboutOverwritingExistingFiles,
  37545. const Colour& backgroundColour);
  37546. /** Destructor. */
  37547. ~FileChooserDialogBox();
  37548. /** Displays and runs the dialog box modally.
  37549. This will show the box with the specified size, returning true if the user
  37550. pressed 'ok', or false if they cancelled.
  37551. Leave the width or height as 0 to use the default size
  37552. */
  37553. bool show (int width = 0,int height = 0);
  37554. /** A set of colour IDs to use to change the colour of various aspects of the box.
  37555. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37556. methods.
  37557. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37558. */
  37559. enum ColourIds
  37560. {
  37561. titleTextColourId = 0x1000850, /**< The colour to use to draw the box's title. */
  37562. };
  37563. /** @internal */
  37564. void buttonClicked (Button* button);
  37565. /** @internal */
  37566. void closeButtonPressed();
  37567. /** @internal */
  37568. void selectionChanged();
  37569. /** @internal */
  37570. void fileClicked (const File& file, const MouseEvent& e);
  37571. /** @internal */
  37572. void fileDoubleClicked (const File& file);
  37573. juce_UseDebuggingNewOperator
  37574. private:
  37575. class ContentComponent : public Component
  37576. {
  37577. public:
  37578. ContentComponent();
  37579. ~ContentComponent();
  37580. void paint (Graphics& g);
  37581. void resized();
  37582. String instructions;
  37583. GlyphArrangement text;
  37584. FileBrowserComponent* chooserComponent;
  37585. FilePreviewComponent* previewComponent;
  37586. TextButton* okButton;
  37587. TextButton* cancelButton;
  37588. };
  37589. ContentComponent* content;
  37590. const bool warnAboutOverwritingExistingFiles;
  37591. FileChooserDialogBox (const FileChooserDialogBox&);
  37592. FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  37593. };
  37594. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37595. /*** End of inlined file: juce_FileChooserDialogBox.h ***/
  37596. #endif
  37597. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  37598. #endif
  37599. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37600. /*** Start of inlined file: juce_FileListComponent.h ***/
  37601. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37602. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37603. /**
  37604. A component that displays the files in a directory as a listbox.
  37605. This implements the DirectoryContentsDisplayComponent base class so that
  37606. it can be used in a FileBrowserComponent.
  37607. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37608. class and the FileBrowserListener class.
  37609. @see DirectoryContentsList, FileTreeComponent
  37610. */
  37611. class JUCE_API FileListComponent : public ListBox,
  37612. public DirectoryContentsDisplayComponent,
  37613. private ListBoxModel,
  37614. private ChangeListener
  37615. {
  37616. public:
  37617. /** Creates a listbox to show the contents of a specified directory.
  37618. */
  37619. FileListComponent (DirectoryContentsList& listToShow);
  37620. /** Destructor. */
  37621. ~FileListComponent();
  37622. /** Returns the number of files the user has got selected.
  37623. @see getSelectedFile
  37624. */
  37625. int getNumSelectedFiles() const;
  37626. /** Returns one of the files that the user has currently selected.
  37627. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  37628. @see getNumSelectedFiles
  37629. */
  37630. const File getSelectedFile (int index = 0) const;
  37631. /** Deselects any files that are currently selected. */
  37632. void deselectAllFiles();
  37633. /** Scrolls to the top of the list. */
  37634. void scrollToTop();
  37635. /** @internal */
  37636. void changeListenerCallback (void*);
  37637. /** @internal */
  37638. int getNumRows();
  37639. /** @internal */
  37640. void paintListBoxItem (int, Graphics&, int, int, bool);
  37641. /** @internal */
  37642. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  37643. /** @internal */
  37644. void selectedRowsChanged (int lastRowSelected);
  37645. /** @internal */
  37646. void deleteKeyPressed (int currentSelectedRow);
  37647. /** @internal */
  37648. void returnKeyPressed (int currentSelectedRow);
  37649. juce_UseDebuggingNewOperator
  37650. private:
  37651. FileListComponent (const FileListComponent&);
  37652. FileListComponent& operator= (const FileListComponent&);
  37653. File lastDirectory;
  37654. };
  37655. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37656. /*** End of inlined file: juce_FileListComponent.h ***/
  37657. #endif
  37658. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37659. /*** Start of inlined file: juce_FilenameComponent.h ***/
  37660. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37661. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37662. class FilenameComponent;
  37663. /**
  37664. Listens for events happening to a FilenameComponent.
  37665. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  37666. register one of these objects for event callbacks when the filename is changed.
  37667. @see FilenameComponent
  37668. */
  37669. class JUCE_API FilenameComponentListener
  37670. {
  37671. public:
  37672. /** Destructor. */
  37673. virtual ~FilenameComponentListener() {}
  37674. /** This method is called after the FilenameComponent's file has been changed. */
  37675. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  37676. };
  37677. /**
  37678. Shows a filename as an editable text box, with a 'browse' button and a
  37679. drop-down list for recently selected files.
  37680. A handy component for dialogue boxes where you want the user to be able to
  37681. select a file or directory.
  37682. Attach an FilenameComponentListener using the addListener() method, and it will
  37683. get called each time the user changes the filename, either by browsing for a file
  37684. and clicking 'ok', or by typing a new filename into the box and pressing return.
  37685. @see FileChooser, ComboBox
  37686. */
  37687. class JUCE_API FilenameComponent : public Component,
  37688. public SettableTooltipClient,
  37689. public FileDragAndDropTarget,
  37690. private AsyncUpdater,
  37691. private ButtonListener,
  37692. private ComboBoxListener
  37693. {
  37694. public:
  37695. /** Creates a FilenameComponent.
  37696. @param name the name for this component.
  37697. @param currentFile the file to initially show in the box
  37698. @param canEditFilename if true, the user can manually edit the filename; if false,
  37699. they can only change it by browsing for a new file
  37700. @param isDirectory if true, the file will be treated as a directory, and
  37701. an appropriate directory browser used
  37702. @param isForSaving if true, the file browser will allow non-existent files to
  37703. be picked, as the file is assumed to be used for saving rather
  37704. than loading
  37705. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  37706. If an empty string is passed in, then the pattern is assumed to be "*"
  37707. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  37708. to any filenames that are entered or chosen
  37709. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  37710. will only appear if the initial file isn't valid)
  37711. */
  37712. FilenameComponent (const String& name,
  37713. const File& currentFile,
  37714. bool canEditFilename,
  37715. bool isDirectory,
  37716. bool isForSaving,
  37717. const String& fileBrowserWildcard,
  37718. const String& enforcedSuffix,
  37719. const String& textWhenNothingSelected);
  37720. /** Destructor. */
  37721. ~FilenameComponent();
  37722. /** Returns the currently displayed filename. */
  37723. const File getCurrentFile() const;
  37724. /** Changes the current filename.
  37725. If addToRecentlyUsedList is true, the filename will also be added to the
  37726. drop-down list of recent files.
  37727. If sendChangeNotification is false, then the listeners won't be told of the
  37728. change.
  37729. */
  37730. void setCurrentFile (File newFile,
  37731. bool addToRecentlyUsedList,
  37732. bool sendChangeNotification = true);
  37733. /** Changes whether the use can type into the filename box.
  37734. */
  37735. void setFilenameIsEditable (bool shouldBeEditable);
  37736. /** Sets a file or directory to be the default starting point for the browser to show.
  37737. This is only used if the current file hasn't been set.
  37738. */
  37739. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  37740. /** Returns all the entries on the recent files list.
  37741. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  37742. state of this list.
  37743. @see setRecentlyUsedFilenames
  37744. */
  37745. const StringArray getRecentlyUsedFilenames() const;
  37746. /** Sets all the entries on the recent files list.
  37747. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  37748. state of this list.
  37749. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  37750. */
  37751. void setRecentlyUsedFilenames (const StringArray& filenames);
  37752. /** Adds an entry to the recently-used files dropdown list.
  37753. If the file is already in the list, it will be moved to the top. A limit
  37754. is also placed on the number of items that are kept in the list.
  37755. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  37756. */
  37757. void addRecentlyUsedFile (const File& file);
  37758. /** Changes the limit for the number of files that will be stored in the recent-file list.
  37759. */
  37760. void setMaxNumberOfRecentFiles (int newMaximum);
  37761. /** Changes the text shown on the 'browse' button.
  37762. By default this button just says "..." but you can change it. The button itself
  37763. can be changed using the look-and-feel classes, so it might not actually have any
  37764. text on it.
  37765. */
  37766. void setBrowseButtonText (const String& browseButtonText);
  37767. /** Adds a listener that will be called when the selected file is changed. */
  37768. void addListener (FilenameComponentListener* listener);
  37769. /** Removes a previously-registered listener. */
  37770. void removeListener (FilenameComponentListener* listener);
  37771. /** Gives the component a tooltip. */
  37772. void setTooltip (const String& newTooltip);
  37773. /** @internal */
  37774. void paintOverChildren (Graphics& g);
  37775. /** @internal */
  37776. void resized();
  37777. /** @internal */
  37778. void lookAndFeelChanged();
  37779. /** @internal */
  37780. bool isInterestedInFileDrag (const StringArray& files);
  37781. /** @internal */
  37782. void filesDropped (const StringArray& files, int, int);
  37783. /** @internal */
  37784. void fileDragEnter (const StringArray& files, int, int);
  37785. /** @internal */
  37786. void fileDragExit (const StringArray& files);
  37787. juce_UseDebuggingNewOperator
  37788. private:
  37789. ComboBox* filenameBox;
  37790. String lastFilename;
  37791. Button* browseButton;
  37792. int maxRecentFiles;
  37793. bool isDir, isSaving, isFileDragOver;
  37794. String wildcard, enforcedSuffix, browseButtonText;
  37795. ListenerList <FilenameComponentListener> listeners;
  37796. File defaultBrowseFile;
  37797. void comboBoxChanged (ComboBox*);
  37798. void buttonClicked (Button* button);
  37799. void handleAsyncUpdate();
  37800. FilenameComponent (const FilenameComponent&);
  37801. FilenameComponent& operator= (const FilenameComponent&);
  37802. };
  37803. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37804. /*** End of inlined file: juce_FilenameComponent.h ***/
  37805. #endif
  37806. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37807. #endif
  37808. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37809. /*** Start of inlined file: juce_FileSearchPathListComponent.h ***/
  37810. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37811. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37812. /**
  37813. Shows a set of file paths in a list, allowing them to be added, removed or
  37814. re-ordered.
  37815. @see FileSearchPath
  37816. */
  37817. class JUCE_API FileSearchPathListComponent : public Component,
  37818. public SettableTooltipClient,
  37819. public FileDragAndDropTarget,
  37820. private ButtonListener,
  37821. private ListBoxModel
  37822. {
  37823. public:
  37824. /** Creates an empty FileSearchPathListComponent.
  37825. */
  37826. FileSearchPathListComponent();
  37827. /** Destructor. */
  37828. ~FileSearchPathListComponent();
  37829. /** Returns the path as it is currently shown. */
  37830. const FileSearchPath& getPath() const throw() { return path; }
  37831. /** Changes the current path. */
  37832. void setPath (const FileSearchPath& newPath);
  37833. /** Sets a file or directory to be the default starting point for the browser to show.
  37834. This is only used if the current file hasn't been set.
  37835. */
  37836. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  37837. /** A set of colour IDs to use to change the colour of various aspects of the label.
  37838. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37839. methods.
  37840. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37841. */
  37842. enum ColourIds
  37843. {
  37844. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  37845. Make this transparent if you don't want the background to be filled. */
  37846. };
  37847. /** @internal */
  37848. int getNumRows();
  37849. /** @internal */
  37850. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  37851. /** @internal */
  37852. void deleteKeyPressed (int lastRowSelected);
  37853. /** @internal */
  37854. void returnKeyPressed (int lastRowSelected);
  37855. /** @internal */
  37856. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  37857. /** @internal */
  37858. void selectedRowsChanged (int lastRowSelected);
  37859. /** @internal */
  37860. void resized();
  37861. /** @internal */
  37862. void paint (Graphics& g);
  37863. /** @internal */
  37864. bool isInterestedInFileDrag (const StringArray& files);
  37865. /** @internal */
  37866. void filesDropped (const StringArray& files, int, int);
  37867. /** @internal */
  37868. void buttonClicked (Button* button);
  37869. juce_UseDebuggingNewOperator
  37870. private:
  37871. FileSearchPath path;
  37872. File defaultBrowseTarget;
  37873. ListBox* listBox;
  37874. Button* addButton;
  37875. Button* removeButton;
  37876. TextButton* changeButton;
  37877. DrawableButton* upButton;
  37878. DrawableButton* downButton;
  37879. void changed();
  37880. void updateButtons();
  37881. FileSearchPathListComponent (const FileSearchPathListComponent&);
  37882. FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  37883. };
  37884. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37885. /*** End of inlined file: juce_FileSearchPathListComponent.h ***/
  37886. #endif
  37887. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37888. /*** Start of inlined file: juce_FileTreeComponent.h ***/
  37889. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37890. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37891. /**
  37892. A component that displays the files in a directory as a treeview.
  37893. This implements the DirectoryContentsDisplayComponent base class so that
  37894. it can be used in a FileBrowserComponent.
  37895. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37896. class and the FileBrowserListener class.
  37897. @see DirectoryContentsList, FileListComponent
  37898. */
  37899. class JUCE_API FileTreeComponent : public TreeView,
  37900. public DirectoryContentsDisplayComponent
  37901. {
  37902. public:
  37903. /** Creates a listbox to show the contents of a specified directory.
  37904. */
  37905. FileTreeComponent (DirectoryContentsList& listToShow);
  37906. /** Destructor. */
  37907. ~FileTreeComponent();
  37908. /** Returns the number of files the user has got selected.
  37909. @see getSelectedFile
  37910. */
  37911. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  37912. /** Returns one of the files that the user has currently selected.
  37913. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  37914. @see getNumSelectedFiles
  37915. */
  37916. const File getSelectedFile (int index = 0) const;
  37917. /** Deselects any files that are currently selected. */
  37918. void deselectAllFiles();
  37919. /** Scrolls the list to the top. */
  37920. void scrollToTop();
  37921. /** Setting a name for this allows tree items to be dragged.
  37922. The string that you pass in here will be returned by the getDragSourceDescription()
  37923. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  37924. */
  37925. void setDragAndDropDescription (const String& description);
  37926. /** Returns the last value that was set by setDragAndDropDescription().
  37927. */
  37928. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  37929. juce_UseDebuggingNewOperator
  37930. private:
  37931. String dragAndDropDescription;
  37932. FileTreeComponent (const FileTreeComponent&);
  37933. FileTreeComponent& operator= (const FileTreeComponent&);
  37934. };
  37935. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37936. /*** End of inlined file: juce_FileTreeComponent.h ***/
  37937. #endif
  37938. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37939. /*** Start of inlined file: juce_ImagePreviewComponent.h ***/
  37940. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37941. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37942. /**
  37943. A simple preview component that shows thumbnails of image files.
  37944. @see FileChooserDialogBox, FilePreviewComponent
  37945. */
  37946. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  37947. private Timer
  37948. {
  37949. public:
  37950. /** Creates an ImagePreviewComponent. */
  37951. ImagePreviewComponent();
  37952. /** Destructor. */
  37953. ~ImagePreviewComponent();
  37954. /** @internal */
  37955. void selectedFileChanged (const File& newSelectedFile);
  37956. /** @internal */
  37957. void paint (Graphics& g);
  37958. /** @internal */
  37959. void timerCallback();
  37960. juce_UseDebuggingNewOperator
  37961. private:
  37962. File fileToLoad;
  37963. Image currentThumbnail;
  37964. String currentDetails;
  37965. void getThumbSize (int& w, int& h) const;
  37966. ImagePreviewComponent (const ImagePreviewComponent&);
  37967. ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  37968. };
  37969. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37970. /*** End of inlined file: juce_ImagePreviewComponent.h ***/
  37971. #endif
  37972. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37973. /*** Start of inlined file: juce_WildcardFileFilter.h ***/
  37974. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37975. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37976. /**
  37977. A type of FileFilter that works by wildcard pattern matching.
  37978. This filter only allows files that match one of the specified patterns, but
  37979. allows all directories through.
  37980. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  37981. */
  37982. class JUCE_API WildcardFileFilter : public FileFilter
  37983. {
  37984. public:
  37985. /**
  37986. Creates a wildcard filter for one or more patterns.
  37987. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  37988. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  37989. or .aiff.
  37990. The description is a name to show the user in a list of possible patterns, so
  37991. for the wav/aiff example, your description might be "audio files".
  37992. */
  37993. WildcardFileFilter (const String& fileWildcardPatterns,
  37994. const String& directoryWildcardPatterns,
  37995. const String& description);
  37996. /** Destructor. */
  37997. ~WildcardFileFilter();
  37998. /** Returns true if the filename matches one of the patterns specified. */
  37999. bool isFileSuitable (const File& file) const;
  38000. /** This always returns true. */
  38001. bool isDirectorySuitable (const File& file) const;
  38002. juce_UseDebuggingNewOperator
  38003. private:
  38004. StringArray fileWildcards, directoryWildcards;
  38005. static void parse (const String& pattern, StringArray& result);
  38006. static bool match (const File& file, const StringArray& wildcards);
  38007. };
  38008. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38009. /*** End of inlined file: juce_WildcardFileFilter.h ***/
  38010. #endif
  38011. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  38012. #endif
  38013. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  38014. #endif
  38015. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  38016. #endif
  38017. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  38018. #endif
  38019. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  38020. #endif
  38021. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38022. /*** Start of inlined file: juce_KeyMappingEditorComponent.h ***/
  38023. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38024. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38025. /*** Start of inlined file: juce_KeyPressMappingSet.h ***/
  38026. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38027. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38028. /**
  38029. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  38030. command in a ApplicationCommandManager.
  38031. Normally, you won't actually create a KeyPressMappingSet directly, because
  38032. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  38033. you'd create yourself an ApplicationCommandManager, and call its
  38034. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  38035. KeyPressMappingSet.
  38036. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  38037. to the top-level component for which you want to handle keystrokes. So for example:
  38038. @code
  38039. class MyMainWindow : public Component
  38040. {
  38041. ApplicationCommandManager* myCommandManager;
  38042. public:
  38043. MyMainWindow()
  38044. {
  38045. myCommandManager = new ApplicationCommandManager();
  38046. // first, make sure the command manager has registered all the commands that its
  38047. // targets can perform..
  38048. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  38049. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  38050. // this will use the command manager to initialise the KeyPressMappingSet with
  38051. // the default keypresses that were specified when the targets added their commands
  38052. // to the manager.
  38053. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  38054. // having set up the default key-mappings, you might now want to load the last set
  38055. // of mappings that the user configured.
  38056. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  38057. // Now tell our top-level window to send any keypresses that arrive to the
  38058. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  38059. addKeyListener (myCommandManager->getKeyMappings());
  38060. }
  38061. ...
  38062. }
  38063. @endcode
  38064. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  38065. register to be told when a command or mapping is added, removed, etc.
  38066. There's also a UI component called KeyMappingEditorComponent that can be used
  38067. to easily edit the key mappings.
  38068. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  38069. */
  38070. class JUCE_API KeyPressMappingSet : public KeyListener,
  38071. public ChangeBroadcaster,
  38072. public FocusChangeListener
  38073. {
  38074. public:
  38075. /** Creates a KeyPressMappingSet for a given command manager.
  38076. Normally, you won't actually create a KeyPressMappingSet directly, because
  38077. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  38078. best thing to do is to create your ApplicationCommandManager, and use the
  38079. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  38080. When a suitable keypress happens, the manager's invoke() method will be
  38081. used to invoke the appropriate command.
  38082. @see ApplicationCommandManager
  38083. */
  38084. explicit KeyPressMappingSet (ApplicationCommandManager* commandManager);
  38085. /** Creates an copy of a KeyPressMappingSet. */
  38086. KeyPressMappingSet (const KeyPressMappingSet& other);
  38087. /** Destructor. */
  38088. ~KeyPressMappingSet();
  38089. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  38090. /** Returns a list of keypresses that are assigned to a particular command.
  38091. @param commandID the command's ID
  38092. */
  38093. const Array <KeyPress> getKeyPressesAssignedToCommand (CommandID commandID) const;
  38094. /** Assigns a keypress to a command.
  38095. If the keypress is already assigned to a different command, it will first be
  38096. removed from that command, to avoid it triggering multiple functions.
  38097. @param commandID the ID of the command that you want to add a keypress to. If
  38098. this is 0, the keypress will be removed from anything that it
  38099. was previously assigned to, but not re-assigned
  38100. @param newKeyPress the new key-press
  38101. @param insertIndex if this is less than zero, the key will be appended to the
  38102. end of the list of keypresses; otherwise the new keypress will
  38103. be inserted into the existing list at this index
  38104. */
  38105. void addKeyPress (CommandID commandID,
  38106. const KeyPress& newKeyPress,
  38107. int insertIndex = -1);
  38108. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  38109. @see resetToDefaultMapping
  38110. */
  38111. void resetToDefaultMappings();
  38112. /** Resets all key-mappings to the defaults for a particular command.
  38113. @see resetToDefaultMappings
  38114. */
  38115. void resetToDefaultMapping (CommandID commandID);
  38116. /** Removes all keypresses that are assigned to any commands. */
  38117. void clearAllKeyPresses();
  38118. /** Removes all keypresses that are assigned to a particular command. */
  38119. void clearAllKeyPresses (CommandID commandID);
  38120. /** Removes one of the keypresses that are assigned to a command.
  38121. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  38122. which the keyPressIndex refers.
  38123. */
  38124. void removeKeyPress (CommandID commandID, int keyPressIndex);
  38125. /** Removes a keypress from any command that it may be assigned to.
  38126. */
  38127. void removeKeyPress (const KeyPress& keypress);
  38128. /** Returns true if the given command is linked to this key. */
  38129. bool containsMapping (CommandID commandID, const KeyPress& keyPress) const throw();
  38130. /** Looks for a command that corresponds to a keypress.
  38131. @returns the UID of the command or 0 if none was found
  38132. */
  38133. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  38134. /** Tries to recreate the mappings from a previously stored state.
  38135. The XML passed in must have been created by the createXml() method.
  38136. If the stored state makes any reference to commands that aren't
  38137. currently available, these will be ignored.
  38138. If the set of mappings being loaded was a set of differences (using createXml (true)),
  38139. then this will call resetToDefaultMappings() and then merge the saved mappings
  38140. on top. If the saved set was created with createXml (false), then this method
  38141. will first clear all existing mappings and load the saved ones as a complete set.
  38142. @returns true if it manages to load the XML correctly
  38143. @see createXml
  38144. */
  38145. bool restoreFromXml (const XmlElement& xmlVersion);
  38146. /** Creates an XML representation of the current mappings.
  38147. This will produce a lump of XML that can be later reloaded using
  38148. restoreFromXml() to recreate the current mapping state.
  38149. The object that is returned must be deleted by the caller.
  38150. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  38151. will be saved into the XML. If it's true, then the XML will
  38152. only store the differences between the current mappings and
  38153. the default mappings you'd get from calling resetToDefaultMappings().
  38154. The advantage of saving a set of differences from the default is that
  38155. if you change the default mappings (in a new version of your app, for
  38156. example), then these will be merged into a user's saved preferences.
  38157. @see restoreFromXml
  38158. */
  38159. XmlElement* createXml (bool saveDifferencesFromDefaultSet) const;
  38160. /** @internal */
  38161. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  38162. /** @internal */
  38163. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  38164. /** @internal */
  38165. void globalFocusChanged (Component* focusedComponent);
  38166. juce_UseDebuggingNewOperator
  38167. private:
  38168. ApplicationCommandManager* commandManager;
  38169. struct CommandMapping
  38170. {
  38171. CommandID commandID;
  38172. Array <KeyPress> keypresses;
  38173. bool wantsKeyUpDownCallbacks;
  38174. };
  38175. OwnedArray <CommandMapping> mappings;
  38176. struct KeyPressTime
  38177. {
  38178. KeyPress key;
  38179. uint32 timeWhenPressed;
  38180. };
  38181. OwnedArray <KeyPressTime> keysDown;
  38182. void handleMessage (const Message& message);
  38183. void invokeCommand (const CommandID commandID,
  38184. const KeyPress& keyPress,
  38185. const bool isKeyDown,
  38186. const int millisecsSinceKeyPressed,
  38187. Component* const originatingComponent) const;
  38188. KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  38189. };
  38190. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38191. /*** End of inlined file: juce_KeyPressMappingSet.h ***/
  38192. /**
  38193. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  38194. object.
  38195. @see KeyPressMappingSet
  38196. */
  38197. class JUCE_API KeyMappingEditorComponent : public Component,
  38198. public TreeViewItem,
  38199. public ChangeListener,
  38200. private ButtonListener
  38201. {
  38202. public:
  38203. /** Creates a KeyMappingEditorComponent.
  38204. @param mappingSet this is the set of mappings to display and
  38205. edit. Make sure the mappings object is not
  38206. deleted before this component!
  38207. @param showResetToDefaultButton if true, then at the bottom of the
  38208. list, the component will include a 'reset to
  38209. defaults' button.
  38210. */
  38211. KeyMappingEditorComponent (KeyPressMappingSet* mappingSet,
  38212. bool showResetToDefaultButton);
  38213. /** Destructor. */
  38214. virtual ~KeyMappingEditorComponent();
  38215. /** Sets up the colours to use for parts of the component.
  38216. @param mainBackground colour to use for most of the background
  38217. @param textColour colour to use for the text
  38218. */
  38219. void setColours (const Colour& mainBackground,
  38220. const Colour& textColour);
  38221. /** Returns the KeyPressMappingSet that this component is acting upon.
  38222. */
  38223. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  38224. /** Can be overridden if some commands need to be excluded from the list.
  38225. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  38226. method to decide what to return, but you can override it to handle special cases.
  38227. */
  38228. virtual bool shouldCommandBeIncluded (CommandID commandID);
  38229. /** Can be overridden to indicate that some commands are shown as read-only.
  38230. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  38231. method to decide what to return, but you can override it to handle special cases.
  38232. */
  38233. virtual bool isCommandReadOnly (CommandID commandID);
  38234. /** This can be overridden to let you change the format of the string used
  38235. to describe a keypress.
  38236. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  38237. keys that are triggered by something else externally. If you override the
  38238. method, be sure to let the base class's method handle keys you're not
  38239. interested in.
  38240. */
  38241. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  38242. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  38243. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38244. methods.
  38245. To change the colours of the menu that pops up
  38246. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38247. */
  38248. enum ColourIds
  38249. {
  38250. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  38251. textColourId = 0x100ad01, /**< The colour for the text. */
  38252. };
  38253. /** @internal */
  38254. void parentHierarchyChanged();
  38255. /** @internal */
  38256. void resized();
  38257. /** @internal */
  38258. void changeListenerCallback (void*);
  38259. /** @internal */
  38260. bool mightContainSubItems();
  38261. /** @internal */
  38262. const String getUniqueName() const;
  38263. /** @internal */
  38264. void buttonClicked (Button* button);
  38265. juce_UseDebuggingNewOperator
  38266. private:
  38267. KeyPressMappingSet* mappings;
  38268. TreeView* tree;
  38269. friend class KeyMappingTreeViewItem;
  38270. friend class KeyCategoryTreeViewItem;
  38271. friend class KeyMappingItemComponent;
  38272. friend class KeyMappingChangeButton;
  38273. TextButton* resetButton;
  38274. void assignNewKey (CommandID commandID, int index);
  38275. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  38276. KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  38277. };
  38278. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38279. /*** End of inlined file: juce_KeyMappingEditorComponent.h ***/
  38280. #endif
  38281. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  38282. #endif
  38283. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38284. #endif
  38285. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  38286. #endif
  38287. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  38288. #endif
  38289. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  38290. #endif
  38291. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  38292. #endif
  38293. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38294. /*** Start of inlined file: juce_ComponentMovementWatcher.h ***/
  38295. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38296. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38297. /** An object that watches for any movement of a component or any of its parent components.
  38298. This makes it easy to check when a component is moved relative to its top-level
  38299. peer window. The normal Component::moved() method is only called when a component
  38300. moves relative to its immediate parent, and sometimes you want to know if any of
  38301. components higher up the tree have moved (which of course will affect the overall
  38302. position of all their sub-components).
  38303. It also includes a callback that lets you know when the top-level peer is changed.
  38304. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  38305. because they need to keep their custom windows in the right place and respond to
  38306. changes in the peer.
  38307. */
  38308. class JUCE_API ComponentMovementWatcher : public ComponentListener
  38309. {
  38310. public:
  38311. /** Creates a ComponentMovementWatcher to watch a given target component. */
  38312. ComponentMovementWatcher (Component* component);
  38313. /** Destructor. */
  38314. ~ComponentMovementWatcher();
  38315. /** This callback happens when the component that is being watched is moved
  38316. relative to its top-level peer window, or when it is resized.
  38317. */
  38318. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  38319. /** This callback happens when the component's top-level peer is changed.
  38320. */
  38321. virtual void componentPeerChanged() = 0;
  38322. juce_UseDebuggingNewOperator
  38323. /** @internal */
  38324. void componentParentHierarchyChanged (Component& component);
  38325. /** @internal */
  38326. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  38327. private:
  38328. Component::SafePointer<Component> component;
  38329. ComponentPeer* lastPeer;
  38330. Array <Component*> registeredParentComps;
  38331. bool reentrant;
  38332. Rectangle<int> lastBounds;
  38333. void unregister() throw();
  38334. void registerWithParentComps() throw();
  38335. ComponentMovementWatcher (const ComponentMovementWatcher&);
  38336. ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  38337. };
  38338. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38339. /*** End of inlined file: juce_ComponentMovementWatcher.h ***/
  38340. #endif
  38341. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38342. /*** Start of inlined file: juce_GroupComponent.h ***/
  38343. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38344. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38345. /**
  38346. A component that draws an outline around itself and has an optional title at
  38347. the top, for drawing an outline around a group of controls.
  38348. */
  38349. class JUCE_API GroupComponent : public Component
  38350. {
  38351. public:
  38352. /** Creates a GroupComponent.
  38353. @param componentName the name to give the component
  38354. @param labelText the text to show at the top of the outline
  38355. */
  38356. GroupComponent (const String& componentName = String::empty,
  38357. const String& labelText = String::empty);
  38358. /** Destructor. */
  38359. ~GroupComponent();
  38360. /** Changes the text that's shown at the top of the component. */
  38361. void setText (const String& newText);
  38362. /** Returns the currently displayed text label. */
  38363. const String getText() const;
  38364. /** Sets the positioning of the text label.
  38365. (The default is Justification::left)
  38366. @see getTextLabelPosition
  38367. */
  38368. void setTextLabelPosition (const Justification& justification);
  38369. /** Returns the current text label position.
  38370. @see setTextLabelPosition
  38371. */
  38372. const Justification getTextLabelPosition() const throw() { return justification; }
  38373. /** A set of colour IDs to use to change the colour of various aspects of the component.
  38374. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38375. methods.
  38376. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38377. */
  38378. enum ColourIds
  38379. {
  38380. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  38381. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  38382. };
  38383. /** @internal */
  38384. void paint (Graphics& g);
  38385. /** @internal */
  38386. void enablementChanged();
  38387. /** @internal */
  38388. void colourChanged();
  38389. private:
  38390. String text;
  38391. Justification justification;
  38392. GroupComponent (const GroupComponent&);
  38393. GroupComponent& operator= (const GroupComponent&);
  38394. };
  38395. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38396. /*** End of inlined file: juce_GroupComponent.h ***/
  38397. #endif
  38398. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  38399. /*** Start of inlined file: juce_MultiDocumentPanel.h ***/
  38400. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  38401. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  38402. /*** Start of inlined file: juce_TabbedComponent.h ***/
  38403. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  38404. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  38405. /*** Start of inlined file: juce_TabbedButtonBar.h ***/
  38406. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  38407. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  38408. class TabbedButtonBar;
  38409. /** In a TabbedButtonBar, this component is used for each of the buttons.
  38410. If you want to create a TabbedButtonBar with custom tab components, derive
  38411. your component from this class, and override the TabbedButtonBar::createTabButton()
  38412. method to create it instead of the default one.
  38413. @see TabbedButtonBar
  38414. */
  38415. class JUCE_API TabBarButton : public Button
  38416. {
  38417. public:
  38418. /** Creates the tab button. */
  38419. TabBarButton (const String& name,
  38420. TabbedButtonBar* ownerBar,
  38421. int tabIndex);
  38422. /** Destructor. */
  38423. ~TabBarButton();
  38424. /** Chooses the best length for the tab, given the specified depth.
  38425. If the tab is horizontal, this should return its width, and the depth
  38426. specifies its height. If it's vertical, it should return the height, and
  38427. the depth is actually its width.
  38428. */
  38429. virtual int getBestTabLength (int depth);
  38430. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  38431. void clicked (const ModifierKeys& mods);
  38432. bool hitTest (int x, int y);
  38433. juce_UseDebuggingNewOperator
  38434. protected:
  38435. friend class TabbedButtonBar;
  38436. TabbedButtonBar* const owner;
  38437. int tabIndex, overlapPixels;
  38438. DropShadowEffect shadow;
  38439. /** Returns an area of the component that's safe to draw in.
  38440. This deals with the orientation of the tabs, which affects which side is
  38441. touching the tabbed box's content component.
  38442. */
  38443. void getActiveArea (int& x, int& y, int& w, int& h);
  38444. private:
  38445. TabBarButton (const TabBarButton&);
  38446. TabBarButton& operator= (const TabBarButton&);
  38447. };
  38448. /**
  38449. A vertical or horizontal bar containing tabs that you can select.
  38450. You can use one of these to generate things like a dialog box that has
  38451. tabbed pages you can flip between. Attach a ChangeListener to the
  38452. button bar to be told when the user changes the page.
  38453. An easier method than doing this is to use a TabbedComponent, which
  38454. contains its own TabbedButtonBar and which takes care of the layout
  38455. and other housekeeping.
  38456. @see TabbedComponent
  38457. */
  38458. class JUCE_API TabbedButtonBar : public Component,
  38459. public ChangeBroadcaster,
  38460. public ButtonListener
  38461. {
  38462. public:
  38463. /** The placement of the tab-bar
  38464. @see setOrientation, getOrientation
  38465. */
  38466. enum Orientation
  38467. {
  38468. TabsAtTop,
  38469. TabsAtBottom,
  38470. TabsAtLeft,
  38471. TabsAtRight
  38472. };
  38473. /** Creates a TabbedButtonBar with a given placement.
  38474. You can change the orientation later if you need to.
  38475. */
  38476. TabbedButtonBar (Orientation orientation);
  38477. /** Destructor. */
  38478. ~TabbedButtonBar();
  38479. /** Changes the bar's orientation.
  38480. This won't change the bar's actual size - you'll need to do that yourself,
  38481. but this determines which direction the tabs go in, and which side they're
  38482. stuck to.
  38483. */
  38484. void setOrientation (Orientation orientation);
  38485. /** Returns the current orientation.
  38486. @see setOrientation
  38487. */
  38488. Orientation getOrientation() const throw() { return orientation; }
  38489. /** Deletes all the tabs from the bar.
  38490. @see addTab
  38491. */
  38492. void clearTabs();
  38493. /** Adds a tab to the bar.
  38494. Tabs are added in left-to-right reading order.
  38495. If this is the first tab added, it'll also be automatically selected.
  38496. */
  38497. void addTab (const String& tabName,
  38498. const Colour& tabBackgroundColour,
  38499. int insertIndex = -1);
  38500. /** Changes the name of one of the tabs. */
  38501. void setTabName (int tabIndex,
  38502. const String& newName);
  38503. /** Gets rid of one of the tabs. */
  38504. void removeTab (int tabIndex);
  38505. /** Moves a tab to a new index in the list.
  38506. Pass -1 as the index to move it to the end of the list.
  38507. */
  38508. void moveTab (int currentIndex, int newIndex);
  38509. /** Returns the number of tabs in the bar. */
  38510. int getNumTabs() const;
  38511. /** Returns a list of all the tab names in the bar. */
  38512. const StringArray getTabNames() const;
  38513. /** Changes the currently selected tab.
  38514. This will send a change message and cause a synchronous callback to
  38515. the currentTabChanged() method. (But if the given tab is already selected,
  38516. nothing will be done).
  38517. To deselect all the tabs, use an index of -1.
  38518. */
  38519. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  38520. /** Returns the name of the currently selected tab.
  38521. This could be an empty string if none are selected.
  38522. */
  38523. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  38524. /** Returns the index of the currently selected tab.
  38525. This could return -1 if none are selected.
  38526. */
  38527. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  38528. /** Returns the button for a specific tab.
  38529. The button that is returned may be deleted later by this component, so don't hang
  38530. on to the pointer that is returned. A null pointer may be returned if the index is
  38531. out of range.
  38532. */
  38533. TabBarButton* getTabButton (int index) const;
  38534. /** Callback method to indicate the selected tab has been changed.
  38535. @see setCurrentTabIndex
  38536. */
  38537. virtual void currentTabChanged (int newCurrentTabIndex,
  38538. const String& newCurrentTabName);
  38539. /** Callback method to indicate that the user has right-clicked on a tab.
  38540. (Or ctrl-clicked on the Mac)
  38541. */
  38542. virtual void popupMenuClickOnTab (int tabIndex, const String& tabName);
  38543. /** Returns the colour of a tab.
  38544. This is the colour that was specified in addTab().
  38545. */
  38546. const Colour getTabBackgroundColour (int tabIndex);
  38547. /** Changes the background colour of a tab.
  38548. @see addTab, getTabBackgroundColour
  38549. */
  38550. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  38551. /** A set of colour IDs to use to change the colour of various aspects of the component.
  38552. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38553. methods.
  38554. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38555. */
  38556. enum ColourIds
  38557. {
  38558. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  38559. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  38560. the look and feel will choose an appropriate colour. */
  38561. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  38562. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  38563. this isn't specified, the look and feel will choose an appropriate
  38564. colour. */
  38565. };
  38566. /** @internal */
  38567. void resized();
  38568. /** @internal */
  38569. void buttonClicked (Button* button);
  38570. /** @internal */
  38571. void lookAndFeelChanged();
  38572. juce_UseDebuggingNewOperator
  38573. protected:
  38574. /** This creates one of the tabs.
  38575. If you need to use custom tab components, you can override this method and
  38576. return your own class instead of the default.
  38577. */
  38578. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  38579. private:
  38580. Orientation orientation;
  38581. StringArray tabs;
  38582. Array <Colour> tabColours;
  38583. int currentTabIndex;
  38584. Component* behindFrontTab;
  38585. Button* extraTabsButton;
  38586. TabbedButtonBar (const TabbedButtonBar&);
  38587. TabbedButtonBar& operator= (const TabbedButtonBar&);
  38588. };
  38589. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  38590. /*** End of inlined file: juce_TabbedButtonBar.h ***/
  38591. /**
  38592. A component with a TabbedButtonBar along one of its sides.
  38593. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  38594. with addTab(), and this will take care of showing the pages for you when the
  38595. user clicks on a different tab.
  38596. @see TabbedButtonBar
  38597. */
  38598. class JUCE_API TabbedComponent : public Component
  38599. {
  38600. public:
  38601. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  38602. Once created, add some tabs with the addTab() method.
  38603. */
  38604. explicit TabbedComponent (TabbedButtonBar::Orientation orientation);
  38605. /** Destructor. */
  38606. ~TabbedComponent();
  38607. /** Changes the placement of the tabs.
  38608. This will rearrange the layout to place the tabs along the appropriate
  38609. side of this component, and will shift the content component accordingly.
  38610. @see TabbedButtonBar::setOrientation
  38611. */
  38612. void setOrientation (TabbedButtonBar::Orientation orientation);
  38613. /** Returns the current tab placement.
  38614. @see setOrientation, TabbedButtonBar::getOrientation
  38615. */
  38616. TabbedButtonBar::Orientation getOrientation() const throw();
  38617. /** Specifies how many pixels wide or high the tab-bar should be.
  38618. If the tabs are placed along the top or bottom, this specified the height
  38619. of the bar; if they're along the left or right edges, it'll be the width
  38620. of the bar.
  38621. */
  38622. void setTabBarDepth (int newDepth);
  38623. /** Returns the current thickness of the tab bar.
  38624. @see setTabBarDepth
  38625. */
  38626. int getTabBarDepth() const throw() { return tabDepth; }
  38627. /** Specifies the thickness of an outline that should be drawn around the content component.
  38628. If this thickness is > 0, a line will be drawn around the three sides of the content
  38629. component which don't touch the tab-bar, and the content component will be inset by this amount.
  38630. To set the colour of the line, use setColour (outlineColourId, ...).
  38631. */
  38632. void setOutline (int newThickness);
  38633. /** Specifies a gap to leave around the edge of the content component.
  38634. Each edge of the content component will be indented by the given number of pixels.
  38635. */
  38636. void setIndent (int indentThickness);
  38637. /** Removes all the tabs from the bar.
  38638. @see TabbedButtonBar::clearTabs
  38639. */
  38640. void clearTabs();
  38641. /** Adds a tab to the tab-bar.
  38642. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  38643. is true, it will be deleted when the tab is removed or when this object is
  38644. deleted.
  38645. @see TabbedButtonBar::addTab
  38646. */
  38647. void addTab (const String& tabName,
  38648. const Colour& tabBackgroundColour,
  38649. Component* contentComponent,
  38650. bool deleteComponentWhenNotNeeded,
  38651. int insertIndex = -1);
  38652. /** Changes the name of one of the tabs. */
  38653. void setTabName (int tabIndex, const String& newName);
  38654. /** Gets rid of one of the tabs. */
  38655. void removeTab (int tabIndex);
  38656. /** Returns the number of tabs in the bar. */
  38657. int getNumTabs() const;
  38658. /** Returns a list of all the tab names in the bar. */
  38659. const StringArray getTabNames() const;
  38660. /** Returns the content component that was added for the given index.
  38661. Be sure not to use or delete the components that are returned, as this may interfere
  38662. with the TabbedComponent's use of them.
  38663. */
  38664. Component* getTabContentComponent (int tabIndex) const throw();
  38665. /** Returns the colour of one of the tabs. */
  38666. const Colour getTabBackgroundColour (int tabIndex) const throw();
  38667. /** Changes the background colour of one of the tabs. */
  38668. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  38669. /** Changes the currently-selected tab.
  38670. To deselect all the tabs, pass -1 as the index.
  38671. @see TabbedButtonBar::setCurrentTabIndex
  38672. */
  38673. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  38674. /** Returns the index of the currently selected tab.
  38675. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  38676. */
  38677. int getCurrentTabIndex() const;
  38678. /** Returns the name of the currently selected tab.
  38679. @see addTab, TabbedButtonBar::getCurrentTabName()
  38680. */
  38681. const String& getCurrentTabName() const;
  38682. /** Returns the current component that's filling the panel.
  38683. This will return 0 if there isn't one.
  38684. */
  38685. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  38686. /** Callback method to indicate the selected tab has been changed.
  38687. @see setCurrentTabIndex
  38688. */
  38689. virtual void currentTabChanged (int newCurrentTabIndex,
  38690. const String& newCurrentTabName);
  38691. /** Callback method to indicate that the user has right-clicked on a tab.
  38692. (Or ctrl-clicked on the Mac)
  38693. */
  38694. virtual void popupMenuClickOnTab (int tabIndex,
  38695. const String& tabName);
  38696. /** Returns the tab button bar component that is being used.
  38697. */
  38698. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  38699. /** A set of colour IDs to use to change the colour of various aspects of the component.
  38700. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38701. methods.
  38702. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38703. */
  38704. enum ColourIds
  38705. {
  38706. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  38707. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  38708. (See setOutline) */
  38709. };
  38710. /** @internal */
  38711. void paint (Graphics& g);
  38712. /** @internal */
  38713. void resized();
  38714. /** @internal */
  38715. void lookAndFeelChanged();
  38716. juce_UseDebuggingNewOperator
  38717. protected:
  38718. TabbedButtonBar* tabs;
  38719. /** This creates one of the tab buttons.
  38720. If you need to use custom tab components, you can override this method and
  38721. return your own class instead of the default.
  38722. */
  38723. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  38724. private:
  38725. Array <Component*> contentComponents;
  38726. Component* panelComponent;
  38727. int tabDepth;
  38728. int outlineThickness, edgeIndent;
  38729. static const Identifier deleteComponentId;
  38730. friend class TabCompButtonBar;
  38731. void changeCallback (int newCurrentTabIndex, const String& newTabName);
  38732. TabbedComponent (const TabbedComponent&);
  38733. TabbedComponent& operator= (const TabbedComponent&);
  38734. };
  38735. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  38736. /*** End of inlined file: juce_TabbedComponent.h ***/
  38737. /*** Start of inlined file: juce_DocumentWindow.h ***/
  38738. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  38739. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  38740. /*** Start of inlined file: juce_MenuBarComponent.h ***/
  38741. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  38742. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  38743. /*** Start of inlined file: juce_MenuBarModel.h ***/
  38744. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  38745. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  38746. class MenuBarModel;
  38747. /**
  38748. A class to receive callbacks when a MenuBarModel changes.
  38749. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  38750. */
  38751. class JUCE_API MenuBarModelListener
  38752. {
  38753. public:
  38754. /** Destructor. */
  38755. virtual ~MenuBarModelListener() {}
  38756. /** This callback is made when items are changed in the menu bar model.
  38757. */
  38758. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  38759. /** This callback is made when an application command is invoked that
  38760. is represented by one of the items in the menu bar model.
  38761. */
  38762. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  38763. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  38764. };
  38765. /**
  38766. A class for controlling MenuBar components.
  38767. This class is used to tell a MenuBar what menus to show, and to respond
  38768. to a menu being selected.
  38769. @see MenuBarModelListener, MenuBarComponent, PopupMenu
  38770. */
  38771. class JUCE_API MenuBarModel : private AsyncUpdater,
  38772. private ApplicationCommandManagerListener
  38773. {
  38774. public:
  38775. MenuBarModel() throw();
  38776. /** Destructor. */
  38777. virtual ~MenuBarModel();
  38778. /** Call this when some of your menu items have changed.
  38779. This method will cause a callback to any MenuBarListener objects that
  38780. are registered with this model.
  38781. If this model is displaying items from an ApplicationCommandManager, you
  38782. can use the setApplicationCommandManagerToWatch() method to cause
  38783. change messages to be sent automatically when the ApplicationCommandManager
  38784. is changed.
  38785. @see addListener, removeListener, MenuBarListener
  38786. */
  38787. void menuItemsChanged();
  38788. /** Tells the menu bar to listen to the specified command manager, and to update
  38789. itself when the commands change.
  38790. This will also allow it to flash a menu name when a command from that menu
  38791. is invoked using a keystroke.
  38792. */
  38793. void setApplicationCommandManagerToWatch (ApplicationCommandManager* manager) throw();
  38794. /** Registers a listener for callbacks when the menu items in this model change.
  38795. The listener object will get callbacks when this object's menuItemsChanged()
  38796. method is called.
  38797. @see removeListener
  38798. */
  38799. void addListener (MenuBarModelListener* listenerToAdd) throw();
  38800. /** Removes a listener.
  38801. @see addListener
  38802. */
  38803. void removeListener (MenuBarModelListener* listenerToRemove) throw();
  38804. /** This method must return a list of the names of the menus. */
  38805. virtual const StringArray getMenuBarNames() = 0;
  38806. /** This should return the popup menu to display for a given top-level menu.
  38807. @param topLevelMenuIndex the index of the top-level menu to show
  38808. @param menuName the name of the top-level menu item to show
  38809. */
  38810. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  38811. const String& menuName) = 0;
  38812. /** This is called when a menu item has been clicked on.
  38813. @param menuItemID the item ID of the PopupMenu item that was selected
  38814. @param topLevelMenuIndex the index of the top-level menu from which the item was
  38815. chosen (just in case you've used duplicate ID numbers
  38816. on more than one of the popup menus)
  38817. */
  38818. virtual void menuItemSelected (int menuItemID,
  38819. int topLevelMenuIndex) = 0;
  38820. #if JUCE_MAC || DOXYGEN
  38821. /** MAC ONLY - Sets the model that is currently being shown as the main
  38822. menu bar at the top of the screen on the Mac.
  38823. You can pass 0 to stop the current model being displayed. Be careful
  38824. not to delete a model while it is being used.
  38825. An optional extra menu can be specified, containing items to add to the top of
  38826. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  38827. an apple, it's the one next to it, with your application's name at the top
  38828. and the services menu etc on it). When one of these items is selected, the
  38829. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  38830. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  38831. object then newMenuBarModel must be non-null.
  38832. */
  38833. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  38834. const PopupMenu* extraAppleMenuItems = 0);
  38835. /** MAC ONLY - Returns the menu model that is currently being shown as
  38836. the main menu bar.
  38837. */
  38838. static MenuBarModel* getMacMainMenu();
  38839. #endif
  38840. /** @internal */
  38841. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  38842. /** @internal */
  38843. void applicationCommandListChanged();
  38844. /** @internal */
  38845. void handleAsyncUpdate();
  38846. juce_UseDebuggingNewOperator
  38847. private:
  38848. ApplicationCommandManager* manager;
  38849. ListenerList <MenuBarModelListener> listeners;
  38850. MenuBarModel (const MenuBarModel&);
  38851. MenuBarModel& operator= (const MenuBarModel&);
  38852. };
  38853. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  38854. /*** End of inlined file: juce_MenuBarModel.h ***/
  38855. /**
  38856. A menu bar component.
  38857. @see MenuBarModel
  38858. */
  38859. class JUCE_API MenuBarComponent : public Component,
  38860. private MenuBarModelListener,
  38861. private Timer
  38862. {
  38863. public:
  38864. /** Creates a menu bar.
  38865. @param model the model object to use to control this bar. You can
  38866. pass 0 into this if you like, and set the model later
  38867. using the setModel() method
  38868. */
  38869. MenuBarComponent (MenuBarModel* model);
  38870. /** Destructor. */
  38871. ~MenuBarComponent();
  38872. /** Changes the model object to use to control the bar.
  38873. This can be 0, in which case the bar will be empty. Don't delete the object
  38874. that is passed-in while it's still being used by this MenuBar.
  38875. */
  38876. void setModel (MenuBarModel* newModel);
  38877. /** Pops up one of the menu items.
  38878. This lets you manually open one of the menus - it could be triggered by a
  38879. key shortcut, for example.
  38880. */
  38881. void showMenu (int menuIndex);
  38882. /** @internal */
  38883. void paint (Graphics& g);
  38884. /** @internal */
  38885. void resized();
  38886. /** @internal */
  38887. void mouseEnter (const MouseEvent& e);
  38888. /** @internal */
  38889. void mouseExit (const MouseEvent& e);
  38890. /** @internal */
  38891. void mouseDown (const MouseEvent& e);
  38892. /** @internal */
  38893. void mouseDrag (const MouseEvent& e);
  38894. /** @internal */
  38895. void mouseUp (const MouseEvent& e);
  38896. /** @internal */
  38897. void mouseMove (const MouseEvent& e);
  38898. /** @internal */
  38899. void inputAttemptWhenModal();
  38900. /** @internal */
  38901. void handleCommandMessage (int commandId);
  38902. /** @internal */
  38903. bool keyPressed (const KeyPress& key);
  38904. /** @internal */
  38905. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  38906. /** @internal */
  38907. void menuCommandInvoked (MenuBarModel* menuBarModel,
  38908. const ApplicationCommandTarget::InvocationInfo& info);
  38909. juce_UseDebuggingNewOperator
  38910. private:
  38911. MenuBarModel* model;
  38912. StringArray menuNames;
  38913. Array <int> xPositions;
  38914. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked, indexToShowAgain;
  38915. int lastMouseX, lastMouseY;
  38916. bool inModalState;
  38917. ScopedPointer <Component> currentPopup;
  38918. int getItemAt (int x, int y);
  38919. void updateItemUnderMouse (int x, int y);
  38920. void hideCurrentMenu();
  38921. void timerCallback();
  38922. void repaintMenuItem (int index);
  38923. MenuBarComponent (const MenuBarComponent&);
  38924. MenuBarComponent& operator= (const MenuBarComponent&);
  38925. };
  38926. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  38927. /*** End of inlined file: juce_MenuBarComponent.h ***/
  38928. /**
  38929. A resizable window with a title bar and maximise, minimise and close buttons.
  38930. This subclass of ResizableWindow creates a fairly standard type of window with
  38931. a title bar and various buttons. The name of the component is shown in the
  38932. title bar, and an icon can optionally be specified with setIcon().
  38933. All the methods available to a ResizableWindow are also available to this,
  38934. so it can easily be made resizable, minimised, maximised, etc.
  38935. It's not advisable to add child components directly to a DocumentWindow: put them
  38936. inside your content component instead. And overriding methods like resized(), moved(), etc
  38937. is also not recommended - instead override these methods for your content component.
  38938. (If for some obscure reason you do need to override these methods, always remember to
  38939. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  38940. decorations correctly).
  38941. You can also automatically add a menu bar to the window, using the setMenuBar()
  38942. method.
  38943. @see ResizableWindow, DialogWindow
  38944. */
  38945. class JUCE_API DocumentWindow : public ResizableWindow
  38946. {
  38947. public:
  38948. /** The set of available button-types that can be put on the title bar.
  38949. @see setTitleBarButtonsRequired
  38950. */
  38951. enum TitleBarButtons
  38952. {
  38953. minimiseButton = 1,
  38954. maximiseButton = 2,
  38955. closeButton = 4,
  38956. /** A combination of all the buttons above. */
  38957. allButtons = 7
  38958. };
  38959. /** Creates a DocumentWindow.
  38960. @param name the name to give the component - this is also
  38961. the title shown at the top of the window. To change
  38962. this later, use setName()
  38963. @param backgroundColour the colour to use for filling the window's background.
  38964. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  38965. should be shown on the title bar. This value is a bitwise
  38966. combination of values from the TitleBarButtons enum. Note
  38967. that it can be "allButtons" to get them all. You
  38968. can change this later with the setTitleBarButtonsRequired()
  38969. method, which can also specify where they are positioned.
  38970. @param addToDesktop if true, the window will be automatically added to the
  38971. desktop; if false, you can use it as a child component
  38972. @see TitleBarButtons
  38973. */
  38974. DocumentWindow (const String& name,
  38975. const Colour& backgroundColour,
  38976. int requiredButtons,
  38977. bool addToDesktop = true);
  38978. /** Destructor.
  38979. If a content component has been set with setContentComponent(), it
  38980. will be deleted.
  38981. */
  38982. ~DocumentWindow();
  38983. /** Changes the component's name.
  38984. (This is overridden from Component::setName() to cause a repaint, as
  38985. the name is what gets drawn across the window's title bar).
  38986. */
  38987. void setName (const String& newName);
  38988. /** Sets an icon to show in the title bar, next to the title.
  38989. A copy is made internally of the image, so the caller can delete the
  38990. image after calling this. If 0 is passed-in, any existing icon will be
  38991. removed.
  38992. */
  38993. void setIcon (const Image& imageToUse);
  38994. /** Changes the height of the title-bar. */
  38995. void setTitleBarHeight (int newHeight);
  38996. /** Returns the current title bar height. */
  38997. int getTitleBarHeight() const;
  38998. /** Changes the set of title-bar buttons being shown.
  38999. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  39000. should be shown on the title bar. This value is a bitwise
  39001. combination of values from the TitleBarButtons enum. Note
  39002. that it can be "allButtons" to get them all.
  39003. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  39004. left side of the bar; if false, they'll be placed at the right
  39005. */
  39006. void setTitleBarButtonsRequired (int requiredButtons,
  39007. bool positionTitleBarButtonsOnLeft);
  39008. /** Sets whether the title should be centred within the window.
  39009. If true, the title text is shown in the middle of the title-bar; if false,
  39010. it'll be shown at the left of the bar.
  39011. */
  39012. void setTitleBarTextCentred (bool textShouldBeCentred);
  39013. /** Creates a menu inside this window.
  39014. @param menuBarModel this specifies a MenuBarModel that should be used to
  39015. generate the contents of a menu bar that will be placed
  39016. just below the title bar, and just above any content
  39017. component. If this value is zero, any existing menu bar
  39018. will be removed from the component; if non-zero, one will
  39019. be added if it's required.
  39020. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  39021. or less to use the look-and-feel's default size.
  39022. */
  39023. void setMenuBar (MenuBarModel* menuBarModel,
  39024. int menuBarHeight = 0);
  39025. /** This method is called when the user tries to close the window.
  39026. This is triggered by the user clicking the close button, or using some other
  39027. OS-specific key shortcut or OS menu for getting rid of a window.
  39028. If the window is just a pop-up, you should override this closeButtonPressed()
  39029. method and make it delete the window in whatever way is appropriate for your
  39030. app. E.g. you might just want to call "delete this".
  39031. If your app is centred around this window such that the whole app should quit when
  39032. the window is closed, then you will probably want to use this method as an opportunity
  39033. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  39034. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  39035. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  39036. or closing it via the taskbar icon on Windows).
  39037. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  39038. redirects it to call this method, so any methods of closing the window that are
  39039. caught by userTriedToCloseWindow() will also end up here).
  39040. */
  39041. virtual void closeButtonPressed();
  39042. /** Callback that is triggered when the minimise button is pressed.
  39043. The default implementation of this calls ResizableWindow::setMinimised(), but
  39044. you can override it to do more customised behaviour.
  39045. */
  39046. virtual void minimiseButtonPressed();
  39047. /** Callback that is triggered when the maximise button is pressed, or when the
  39048. title-bar is double-clicked.
  39049. The default implementation of this calls ResizableWindow::setFullScreen(), but
  39050. you can override it to do more customised behaviour.
  39051. */
  39052. virtual void maximiseButtonPressed();
  39053. /** Returns the close button, (or 0 if there isn't one). */
  39054. Button* getCloseButton() const throw();
  39055. /** Returns the minimise button, (or 0 if there isn't one). */
  39056. Button* getMinimiseButton() const throw();
  39057. /** Returns the maximise button, (or 0 if there isn't one). */
  39058. Button* getMaximiseButton() const throw();
  39059. /** A set of colour IDs to use to change the colour of various aspects of the window.
  39060. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39061. methods.
  39062. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39063. */
  39064. enum ColourIds
  39065. {
  39066. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  39067. and feel class how this is used. */
  39068. };
  39069. /** @internal */
  39070. void paint (Graphics& g);
  39071. /** @internal */
  39072. void resized();
  39073. /** @internal */
  39074. void lookAndFeelChanged();
  39075. /** @internal */
  39076. const BorderSize getBorderThickness();
  39077. /** @internal */
  39078. const BorderSize getContentComponentBorder();
  39079. /** @internal */
  39080. void mouseDoubleClick (const MouseEvent& e);
  39081. /** @internal */
  39082. void userTriedToCloseWindow();
  39083. /** @internal */
  39084. void activeWindowStatusChanged();
  39085. /** @internal */
  39086. int getDesktopWindowStyleFlags() const;
  39087. /** @internal */
  39088. void parentHierarchyChanged();
  39089. /** @internal */
  39090. const Rectangle<int> getTitleBarArea();
  39091. juce_UseDebuggingNewOperator
  39092. private:
  39093. int titleBarHeight, menuBarHeight, requiredButtons;
  39094. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  39095. ScopedPointer <Button> titleBarButtons [3];
  39096. Image titleBarIcon;
  39097. ScopedPointer <MenuBarComponent> menuBar;
  39098. MenuBarModel* menuBarModel;
  39099. class ButtonListenerProxy;
  39100. friend class ScopedPointer <ButtonListenerProxy>;
  39101. ScopedPointer <ButtonListenerProxy> buttonListener;
  39102. void repaintTitleBar();
  39103. DocumentWindow (const DocumentWindow&);
  39104. DocumentWindow& operator= (const DocumentWindow&);
  39105. };
  39106. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  39107. /*** End of inlined file: juce_DocumentWindow.h ***/
  39108. class MultiDocumentPanel;
  39109. class MDITabbedComponentInternal;
  39110. /**
  39111. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  39112. component.
  39113. It's like a normal DocumentWindow but has some extra functionality to make sure
  39114. everything works nicely inside a MultiDocumentPanel.
  39115. @see MultiDocumentPanel
  39116. */
  39117. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  39118. {
  39119. public:
  39120. /**
  39121. */
  39122. MultiDocumentPanelWindow (const Colour& backgroundColour);
  39123. /** Destructor. */
  39124. ~MultiDocumentPanelWindow();
  39125. /** @internal */
  39126. void maximiseButtonPressed();
  39127. /** @internal */
  39128. void closeButtonPressed();
  39129. /** @internal */
  39130. void activeWindowStatusChanged();
  39131. /** @internal */
  39132. void broughtToFront();
  39133. juce_UseDebuggingNewOperator
  39134. private:
  39135. void updateOrder();
  39136. MultiDocumentPanel* getOwner() const throw();
  39137. };
  39138. /**
  39139. A component that contains a set of other components either in floating windows
  39140. or tabs.
  39141. This acts as a panel that can be used to hold a set of open document windows, with
  39142. different layout modes.
  39143. Use addDocument() and closeDocument() to add or remove components from the
  39144. panel - never use any of the Component methods to access the panel's child
  39145. components directly, as these are managed internally.
  39146. */
  39147. class JUCE_API MultiDocumentPanel : public Component,
  39148. private ComponentListener
  39149. {
  39150. public:
  39151. /** Creates an empty panel.
  39152. Use addDocument() and closeDocument() to add or remove components from the
  39153. panel - never use any of the Component methods to access the panel's child
  39154. components directly, as these are managed internally.
  39155. */
  39156. MultiDocumentPanel();
  39157. /** Destructor.
  39158. When deleted, this will call closeAllDocuments (false) to make sure all its
  39159. components are deleted. If you need to make sure all documents are saved
  39160. before closing, then you should call closeAllDocuments (true) and check that
  39161. it returns true before deleting the panel.
  39162. */
  39163. ~MultiDocumentPanel();
  39164. /** Tries to close all the documents.
  39165. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  39166. be called for each open document, and any of these calls fails, this method
  39167. will stop and return false, leaving some documents still open.
  39168. If checkItsOkToCloseFirst is false, then all documents will be closed
  39169. unconditionally.
  39170. @see closeDocument
  39171. */
  39172. bool closeAllDocuments (bool checkItsOkToCloseFirst);
  39173. /** Adds a document component to the panel.
  39174. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  39175. this will fail and return false. (If it does fail, the component passed-in will not be
  39176. deleted, even if deleteWhenRemoved was set to true).
  39177. The MultiDocumentPanel will deal with creating a window border to go around your component,
  39178. so just pass in the bare content component here, no need to give it a ResizableWindow
  39179. or DocumentWindow.
  39180. @param component the component to add
  39181. @param backgroundColour the background colour to use to fill the component's
  39182. window or tab
  39183. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  39184. or closeAllDocuments(), then it will be deleted. If false, then
  39185. the caller must handle the component's deletion
  39186. */
  39187. bool addDocument (Component* component,
  39188. const Colour& backgroundColour,
  39189. bool deleteWhenRemoved);
  39190. /** Closes one of the documents.
  39191. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  39192. be called, and if it fails, this method will return false without closing the
  39193. document.
  39194. If checkItsOkToCloseFirst is false, then the documents will be closed
  39195. unconditionally.
  39196. The component will be deleted if the deleteWhenRemoved parameter was set to
  39197. true when it was added with addDocument.
  39198. @see addDocument, closeAllDocuments
  39199. */
  39200. bool closeDocument (Component* component,
  39201. bool checkItsOkToCloseFirst);
  39202. /** Returns the number of open document windows.
  39203. @see getDocument
  39204. */
  39205. int getNumDocuments() const throw();
  39206. /** Returns one of the open documents.
  39207. The order of the documents in this array may change when they are added, removed
  39208. or moved around.
  39209. @see getNumDocuments
  39210. */
  39211. Component* getDocument (int index) const throw();
  39212. /** Returns the document component that is currently focused or on top.
  39213. If currently using floating windows, then this will be the component in the currently
  39214. active window, or the top component if none are active.
  39215. If it's currently in tabbed mode, then it'll return the component in the active tab.
  39216. @see setActiveDocument
  39217. */
  39218. Component* getActiveDocument() const throw();
  39219. /** Makes one of the components active and brings it to the top.
  39220. @see getActiveDocument
  39221. */
  39222. void setActiveDocument (Component* component);
  39223. /** Callback which gets invoked when the currently-active document changes. */
  39224. virtual void activeDocumentChanged();
  39225. /** Sets a limit on how many windows can be open at once.
  39226. If this is zero or less there's no limit (the default). addDocument() will fail
  39227. if this number is exceeded.
  39228. */
  39229. void setMaximumNumDocuments (int maximumNumDocuments);
  39230. /** Sets an option to make the document fullscreen if there's only one document open.
  39231. If set to true, then if there's only one document, it'll fill the whole of this
  39232. component without tabs or a window border. If false, then tabs or a window
  39233. will always be shown, even if there's only one document. If there's more than
  39234. one document open, then this option makes no difference.
  39235. */
  39236. void useFullscreenWhenOneDocument (bool shouldUseTabs);
  39237. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  39238. */
  39239. bool isFullscreenWhenOneDocument() const throw();
  39240. /** The different layout modes available. */
  39241. enum LayoutMode
  39242. {
  39243. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  39244. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  39245. };
  39246. /** Changes the panel's mode.
  39247. @see LayoutMode, getLayoutMode
  39248. */
  39249. void setLayoutMode (LayoutMode newLayoutMode);
  39250. /** Returns the current layout mode. */
  39251. LayoutMode getLayoutMode() const throw() { return mode; }
  39252. /** Sets the background colour for the whole panel.
  39253. Each document has its own background colour, but this is the one used to fill the areas
  39254. behind them.
  39255. */
  39256. void setBackgroundColour (const Colour& newBackgroundColour);
  39257. /** Returns the current background colour.
  39258. @see setBackgroundColour
  39259. */
  39260. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  39261. /** A subclass must override this to say whether its currently ok for a document
  39262. to be closed.
  39263. This method is called by closeDocument() and closeAllDocuments() to indicate that
  39264. a document should be saved if possible, ready for it to be closed.
  39265. If this method returns true, then it means the document is ok and can be closed.
  39266. If it returns false, then it means that the closeDocument() method should stop
  39267. and not close.
  39268. Normally, you'd use this method to ask the user if they want to save any changes,
  39269. then return true if the save operation went ok. If the user cancelled the save
  39270. operation you could return false here to abort the close operation.
  39271. If your component is based on the FileBasedDocument class, then you'd probably want
  39272. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  39273. FileBasedDocument::savedOk
  39274. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  39275. */
  39276. virtual bool tryToCloseDocument (Component* component) = 0;
  39277. /** Creates a new window to be used for a document.
  39278. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  39279. but you might want to override it to return a custom component.
  39280. */
  39281. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  39282. /** @internal */
  39283. void paint (Graphics& g);
  39284. /** @internal */
  39285. void resized();
  39286. /** @internal */
  39287. void componentNameChanged (Component&);
  39288. juce_UseDebuggingNewOperator
  39289. private:
  39290. LayoutMode mode;
  39291. Array <Component*> components;
  39292. TabbedComponent* tabComponent;
  39293. Colour backgroundColour;
  39294. int maximumNumDocuments, numDocsBeforeTabsUsed;
  39295. friend class MultiDocumentPanelWindow;
  39296. friend class MDITabbedComponentInternal;
  39297. Component* getContainerComp (Component* c) const;
  39298. void updateOrder();
  39299. void addWindow (Component* component);
  39300. };
  39301. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  39302. /*** End of inlined file: juce_MultiDocumentPanel.h ***/
  39303. #endif
  39304. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  39305. #endif
  39306. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  39307. #endif
  39308. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  39309. #endif
  39310. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39311. /*** Start of inlined file: juce_StretchableLayoutManager.h ***/
  39312. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39313. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39314. /**
  39315. For laying out a set of components, where the components have preferred sizes
  39316. and size limits, but where they are allowed to stretch to fill the available
  39317. space.
  39318. For example, if you have a component containing several other components, and
  39319. each one should be given a share of the total size, you could use one of these
  39320. to resize the child components when the parent component is resized. Then
  39321. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  39322. A StretchableLayoutManager operates only in one dimension, so if you have a set
  39323. of components stacked vertically on top of each other, you'd use one to manage their
  39324. heights. To build up complex arrangements of components, e.g. for applications
  39325. with multiple nested panels, you would use more than one StretchableLayoutManager.
  39326. E.g. by using two (one vertical, one horizontal), you could create a resizable
  39327. spreadsheet-style table.
  39328. E.g.
  39329. @code
  39330. class MyComp : public Component
  39331. {
  39332. StretchableLayoutManager myLayout;
  39333. MyComp()
  39334. {
  39335. myLayout.setItemLayout (0, // for item 0
  39336. 50, 100, // must be between 50 and 100 pixels in size
  39337. -0.6); // and its preferred size is 60% of the total available space
  39338. myLayout.setItemLayout (1, // for item 1
  39339. -0.2, -0.6, // size must be between 20% and 60% of the available space
  39340. 50); // and its preferred size is 50 pixels
  39341. }
  39342. void resized()
  39343. {
  39344. // make a list of two of our child components that we want to reposition
  39345. Component* comps[] = { myComp1, myComp2 };
  39346. // this will position the 2 components, one above the other, to fit
  39347. // vertically into the rectangle provided.
  39348. myLayout.layOutComponents (comps, 2,
  39349. 0, 0, getWidth(), getHeight(),
  39350. true);
  39351. }
  39352. };
  39353. @endcode
  39354. @see StretchableLayoutResizerBar
  39355. */
  39356. class JUCE_API StretchableLayoutManager
  39357. {
  39358. public:
  39359. /** Creates an empty layout.
  39360. You'll need to add some item properties to the layout before it can be used
  39361. to resize things - see setItemLayout().
  39362. */
  39363. StretchableLayoutManager();
  39364. /** Destructor. */
  39365. ~StretchableLayoutManager();
  39366. /** For a numbered item, this sets its size limits and preferred size.
  39367. @param itemIndex the index of the item to change.
  39368. @param minimumSize the minimum size that this item is allowed to be - a positive number
  39369. indicates an absolute size in pixels. A negative number indicates a
  39370. proportion of the available space (e.g -0.5 is 50%)
  39371. @param maximumSize the maximum size that this item is allowed to be - a positive number
  39372. indicates an absolute size in pixels. A negative number indicates a
  39373. proportion of the available space
  39374. @param preferredSize the size that this item would like to be, if there's enough room. A
  39375. positive number indicates an absolute size in pixels. A negative number
  39376. indicates a proportion of the available space
  39377. @see getItemLayout
  39378. */
  39379. void setItemLayout (int itemIndex,
  39380. double minimumSize,
  39381. double maximumSize,
  39382. double preferredSize);
  39383. /** For a numbered item, this returns its size limits and preferred size.
  39384. @param itemIndex the index of the item.
  39385. @param minimumSize the minimum size that this item is allowed to be - a positive number
  39386. indicates an absolute size in pixels. A negative number indicates a
  39387. proportion of the available space (e.g -0.5 is 50%)
  39388. @param maximumSize the maximum size that this item is allowed to be - a positive number
  39389. indicates an absolute size in pixels. A negative number indicates a
  39390. proportion of the available space
  39391. @param preferredSize the size that this item would like to be, if there's enough room. A
  39392. positive number indicates an absolute size in pixels. A negative number
  39393. indicates a proportion of the available space
  39394. @returns false if the item's properties hadn't been set
  39395. @see setItemLayout
  39396. */
  39397. bool getItemLayout (int itemIndex,
  39398. double& minimumSize,
  39399. double& maximumSize,
  39400. double& preferredSize) const;
  39401. /** Clears all the properties that have been set with setItemLayout() and resets
  39402. this object to its initial state.
  39403. */
  39404. void clearAllItems();
  39405. /** Takes a set of components that correspond to the layout's items, and positions
  39406. them to fill a space.
  39407. This will try to give each item its preferred size, whether that's a relative size
  39408. or an absolute one.
  39409. @param components an array of components that correspond to each of the
  39410. numbered items that the StretchableLayoutManager object
  39411. has been told about with setItemLayout()
  39412. @param numComponents the number of components in the array that is passed-in. This
  39413. should be the same as the number of items this object has been
  39414. told about.
  39415. @param x the left of the rectangle in which the components should
  39416. be laid out
  39417. @param y the top of the rectangle in which the components should
  39418. be laid out
  39419. @param width the width of the rectangle in which the components should
  39420. be laid out
  39421. @param height the height of the rectangle in which the components should
  39422. be laid out
  39423. @param vertically if true, the components will be positioned in a vertical stack,
  39424. so that they fill the height of the rectangle. If false, they
  39425. will be placed side-by-side in a horizontal line, filling the
  39426. available width
  39427. @param resizeOtherDimension if true, this means that the components will have their
  39428. other dimension resized to fit the space - i.e. if the 'vertically'
  39429. parameter is true, their x-positions and widths are adjusted to fit
  39430. the x and width parameters; if 'vertically' is false, their y-positions
  39431. and heights are adjusted to fit the y and height parameters.
  39432. */
  39433. void layOutComponents (Component** components,
  39434. int numComponents,
  39435. int x, int y, int width, int height,
  39436. bool vertically,
  39437. bool resizeOtherDimension);
  39438. /** Returns the current position of one of the items.
  39439. This is only a valid call after layOutComponents() has been called, as it
  39440. returns the last position that this item was placed at. If the layout was
  39441. vertical, the value returned will be the y position of the top of the item,
  39442. relative to the top of the rectangle in which the items were placed (so for
  39443. example, item 0 will always have position of 0, even in the rectangle passed
  39444. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  39445. the position returned is the item's left-hand position, again relative to the
  39446. x position of the rectangle used.
  39447. @see getItemCurrentSize, setItemPosition
  39448. */
  39449. int getItemCurrentPosition (int itemIndex) const;
  39450. /** Returns the current size of one of the items.
  39451. This is only meaningful after layOutComponents() has been called, as it
  39452. returns the last size that this item was given. If the layout was done
  39453. vertically, it'll return the item's height in pixels; if it was horizontal,
  39454. it'll return its width.
  39455. @see getItemCurrentRelativeSize
  39456. */
  39457. int getItemCurrentAbsoluteSize (int itemIndex) const;
  39458. /** Returns the current size of one of the items.
  39459. This is only meaningful after layOutComponents() has been called, as it
  39460. returns the last size that this item was given. If the layout was done
  39461. vertically, it'll return a negative value representing the item's height relative
  39462. to the last size used for laying the components out; if the layout was done
  39463. horizontally it'll be the proportion of its width.
  39464. @see getItemCurrentAbsoluteSize
  39465. */
  39466. double getItemCurrentRelativeSize (int itemIndex) const;
  39467. /** Moves one of the items, shifting along any other items as necessary in
  39468. order to get it to the desired position.
  39469. Calling this method will also update the preferred sizes of the items it
  39470. shuffles along, so that they reflect their new positions.
  39471. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  39472. about when it's dragged).
  39473. @param itemIndex the item to move
  39474. @param newPosition the absolute position that you'd like this item to move
  39475. to. The item might not be able to always reach exactly this position,
  39476. because other items may have minimum sizes that constrain how
  39477. far it can go
  39478. */
  39479. void setItemPosition (int itemIndex,
  39480. int newPosition);
  39481. juce_UseDebuggingNewOperator
  39482. private:
  39483. struct ItemLayoutProperties
  39484. {
  39485. int itemIndex;
  39486. int currentSize;
  39487. double minSize, maxSize, preferredSize;
  39488. };
  39489. OwnedArray <ItemLayoutProperties> items;
  39490. int totalSize;
  39491. static int sizeToRealSize (double size, int totalSpace);
  39492. ItemLayoutProperties* getInfoFor (int itemIndex) const;
  39493. void setTotalSize (int newTotalSize);
  39494. int fitComponentsIntoSpace (int startIndex, int endIndex, int availableSpace, int startPos);
  39495. int getMinimumSizeOfItems (int startIndex, int endIndex) const;
  39496. int getMaximumSizeOfItems (int startIndex, int endIndex) const;
  39497. void updatePrefSizesToMatchCurrentPositions();
  39498. StretchableLayoutManager (const StretchableLayoutManager&);
  39499. StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  39500. };
  39501. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39502. /*** End of inlined file: juce_StretchableLayoutManager.h ***/
  39503. #endif
  39504. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39505. /*** Start of inlined file: juce_StretchableLayoutResizerBar.h ***/
  39506. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39507. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39508. /**
  39509. A component that acts as one of the vertical or horizontal bars you see being
  39510. used to resize panels in a window.
  39511. One of these acts with a StretchableLayoutManager to resize the other components.
  39512. @see StretchableLayoutManager
  39513. */
  39514. class JUCE_API StretchableLayoutResizerBar : public Component
  39515. {
  39516. public:
  39517. /** Creates a resizer bar for use on a specified layout.
  39518. @param layoutToUse the layout that will be affected when this bar
  39519. is dragged
  39520. @param itemIndexInLayout the item index in the layout that corresponds to
  39521. this bar component. You'll need to set up the item
  39522. properties in a suitable way for a divider bar, e.g.
  39523. for an 8-pixel wide bar which, you could call
  39524. myLayout->setItemLayout (barIndex, 8, 8, 8)
  39525. @param isBarVertical true if it's an upright bar that you drag left and
  39526. right; false for a horizontal one that you drag up and
  39527. down
  39528. */
  39529. StretchableLayoutResizerBar (StretchableLayoutManager* layoutToUse,
  39530. int itemIndexInLayout,
  39531. bool isBarVertical);
  39532. /** Destructor. */
  39533. ~StretchableLayoutResizerBar();
  39534. /** This is called when the bar is dragged.
  39535. This method must update the positions of any components whose position is
  39536. determined by the StretchableLayoutManager, because they might have just
  39537. moved.
  39538. The default implementation calls the resized() method of this component's
  39539. parent component, because that's often where you're likely to apply the
  39540. layout, but it can be overridden for more specific needs.
  39541. */
  39542. virtual void hasBeenMoved();
  39543. /** @internal */
  39544. void paint (Graphics& g);
  39545. /** @internal */
  39546. void mouseDown (const MouseEvent& e);
  39547. /** @internal */
  39548. void mouseDrag (const MouseEvent& e);
  39549. juce_UseDebuggingNewOperator
  39550. private:
  39551. StretchableLayoutManager* layout;
  39552. int itemIndex, mouseDownPos;
  39553. bool isVertical;
  39554. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  39555. StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  39556. };
  39557. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39558. /*** End of inlined file: juce_StretchableLayoutResizerBar.h ***/
  39559. #endif
  39560. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39561. /*** Start of inlined file: juce_StretchableObjectResizer.h ***/
  39562. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39563. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39564. /**
  39565. A utility class for fitting a set of objects whose sizes can vary between
  39566. a minimum and maximum size, into a space.
  39567. This is a trickier algorithm than it would first seem, so I've put it in this
  39568. class to allow it to be shared by various bits of code.
  39569. To use it, create one of these objects, call addItem() to add the list of items
  39570. you need, then call resizeToFit(), which will change all their sizes. You can
  39571. then retrieve the new sizes with getItemSize() and getNumItems().
  39572. It's currently used by the TableHeaderComponent for stretching out the table
  39573. headings to fill the table's width.
  39574. */
  39575. class StretchableObjectResizer
  39576. {
  39577. public:
  39578. /** Creates an empty object resizer. */
  39579. StretchableObjectResizer();
  39580. /** Destructor. */
  39581. ~StretchableObjectResizer();
  39582. /** Adds an item to the list.
  39583. The order parameter lets you specify groups of items that are resized first when some
  39584. space needs to be found. Those items with an order of 0 will be the first ones to be
  39585. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  39586. will then try resizing the items with an order of 1, then 2, and so on.
  39587. */
  39588. void addItem (double currentSize,
  39589. double minSize,
  39590. double maxSize,
  39591. int order = 0);
  39592. /** Resizes all the items to fit this amount of space.
  39593. This will attempt to fit them in without exceeding each item's miniumum and
  39594. maximum sizes. In cases where none of the items can be expanded or enlarged any
  39595. further, the final size may be greater or less than the size passed in.
  39596. After calling this method, you can retrieve the new sizes with the getItemSize()
  39597. method.
  39598. */
  39599. void resizeToFit (double targetSize);
  39600. /** Returns the number of items that have been added. */
  39601. int getNumItems() const throw() { return items.size(); }
  39602. /** Returns the size of one of the items. */
  39603. double getItemSize (int index) const throw();
  39604. juce_UseDebuggingNewOperator
  39605. private:
  39606. struct Item
  39607. {
  39608. double size;
  39609. double minSize;
  39610. double maxSize;
  39611. int order;
  39612. };
  39613. OwnedArray <Item> items;
  39614. StretchableObjectResizer (const StretchableObjectResizer&);
  39615. StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  39616. };
  39617. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39618. /*** End of inlined file: juce_StretchableObjectResizer.h ***/
  39619. #endif
  39620. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  39621. #endif
  39622. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  39623. #endif
  39624. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  39625. #endif
  39626. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39627. /*** Start of inlined file: juce_LookAndFeel.h ***/
  39628. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39629. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  39630. /*** Start of inlined file: juce_AlertWindow.h ***/
  39631. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  39632. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  39633. /*** Start of inlined file: juce_TextLayout.h ***/
  39634. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  39635. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  39636. class Graphics;
  39637. /**
  39638. A laid-out arrangement of text.
  39639. You can add text in different fonts to a TextLayout object, then call its
  39640. layout() method to word-wrap it into lines. The layout can then be drawn
  39641. using a graphics context.
  39642. It's handy if you've got a message to display, because you can format it,
  39643. measure the extent of the layout, and then create a suitably-sized window
  39644. to show it in.
  39645. @see Font, Graphics::drawFittedText, GlyphArrangement
  39646. */
  39647. class JUCE_API TextLayout
  39648. {
  39649. public:
  39650. /** Creates an empty text layout.
  39651. Text can then be appended using the appendText() method.
  39652. */
  39653. TextLayout();
  39654. /** Creates a copy of another layout object. */
  39655. TextLayout (const TextLayout& other);
  39656. /** Creates a text layout from an initial string and font. */
  39657. TextLayout (const String& text, const Font& font);
  39658. /** Destructor. */
  39659. ~TextLayout();
  39660. /** Copies another layout onto this one. */
  39661. TextLayout& operator= (const TextLayout& layoutToCopy);
  39662. /** Clears the layout, removing all its text. */
  39663. void clear();
  39664. /** Adds a string to the end of the arrangement.
  39665. The string will be broken onto new lines wherever it contains
  39666. carriage-returns or linefeeds. After adding it, you can call layout()
  39667. to wrap long lines into a paragraph and justify it.
  39668. */
  39669. void appendText (const String& textToAppend,
  39670. const Font& fontToUse);
  39671. /** Replaces all the text with a new string.
  39672. This is equivalent to calling clear() followed by appendText().
  39673. */
  39674. void setText (const String& newText,
  39675. const Font& fontToUse);
  39676. /** Breaks the text up to form a paragraph with the given width.
  39677. @param maximumWidth any text wider than this will be split
  39678. across multiple lines
  39679. @param justification how the lines are to be laid-out horizontally
  39680. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  39681. width that keeps all the lines of text at a
  39682. similar length - this is good when you're displaying
  39683. a short message and don't want it to get split
  39684. onto two lines with only a couple of words on
  39685. the second line, which looks untidy.
  39686. */
  39687. void layout (int maximumWidth,
  39688. const Justification& justification,
  39689. bool attemptToBalanceLineLengths);
  39690. /** Returns the overall width of the entire text layout. */
  39691. int getWidth() const;
  39692. /** Returns the overall height of the entire text layout. */
  39693. int getHeight() const;
  39694. /** Returns the total number of lines of text. */
  39695. int getNumLines() const { return totalLines; }
  39696. /** Returns the width of a particular line of text.
  39697. @param lineNumber the line, from 0 to (getNumLines() - 1)
  39698. */
  39699. int getLineWidth (int lineNumber) const;
  39700. /** Renders the text at a specified position using a graphics context.
  39701. */
  39702. void draw (Graphics& g, int topLeftX, int topLeftY) const;
  39703. /** Renders the text within a specified rectangle using a graphics context.
  39704. The justification flags dictate how the block of text should be positioned
  39705. within the rectangle.
  39706. */
  39707. void drawWithin (Graphics& g,
  39708. int x, int y, int w, int h,
  39709. const Justification& layoutFlags) const;
  39710. juce_UseDebuggingNewOperator
  39711. private:
  39712. class Token;
  39713. friend class OwnedArray <Token>;
  39714. OwnedArray <Token> tokens;
  39715. int totalLines;
  39716. };
  39717. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  39718. /*** End of inlined file: juce_TextLayout.h ***/
  39719. /** A window that displays a message and has buttons for the user to react to it.
  39720. For simple dialog boxes with just a couple of buttons on them, there are
  39721. some static methods for running these.
  39722. For more complex dialogs, an AlertWindow can be created, then it can have some
  39723. buttons and components added to it, and its runModalLoop() method is then used to
  39724. show it. The value returned by runModalLoop() shows which button the
  39725. user pressed to dismiss the box.
  39726. @see ThreadWithProgressWindow
  39727. */
  39728. class JUCE_API AlertWindow : public TopLevelWindow,
  39729. private ButtonListener
  39730. {
  39731. public:
  39732. /** The type of icon to show in the dialog box. */
  39733. enum AlertIconType
  39734. {
  39735. NoIcon, /**< No icon will be shown on the dialog box. */
  39736. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  39737. user to answer a question. */
  39738. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  39739. warning about something and shouldn't be ignored. */
  39740. InfoIcon /**< An icon that indicates that the dialog box is just
  39741. giving the user some information, which doesn't require
  39742. a response from them. */
  39743. };
  39744. /** Creates an AlertWindow.
  39745. @param title the headline to show at the top of the dialog box
  39746. @param message a longer, more descriptive message to show underneath the
  39747. headline
  39748. @param iconType the type of icon to display
  39749. @param associatedComponent if this is non-zero, it specifies the component that the
  39750. alert window should be associated with. Depending on the look
  39751. and feel, this might be used for positioning of the alert window.
  39752. */
  39753. AlertWindow (const String& title,
  39754. const String& message,
  39755. AlertIconType iconType,
  39756. Component* associatedComponent = 0);
  39757. /** Destroys the AlertWindow */
  39758. ~AlertWindow();
  39759. /** Returns the type of alert icon that was specified when the window
  39760. was created. */
  39761. AlertIconType getAlertType() const throw() { return alertIconType; }
  39762. /** Changes the dialog box's message.
  39763. This will also resize the window to fit the new message if required.
  39764. */
  39765. void setMessage (const String& message);
  39766. /** Adds a button to the window.
  39767. @param name the text to show on the button
  39768. @param returnValue the value that should be returned from runModalLoop()
  39769. if this is the button that the user presses.
  39770. @param shortcutKey1 an optional key that can be pressed to trigger this button
  39771. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  39772. */
  39773. void addButton (const String& name,
  39774. int returnValue,
  39775. const KeyPress& shortcutKey1 = KeyPress(),
  39776. const KeyPress& shortcutKey2 = KeyPress());
  39777. /** Returns the number of buttons that the window currently has. */
  39778. int getNumButtons() const;
  39779. /** Invokes a click of one of the buttons. */
  39780. void triggerButtonClick (const String& buttonName);
  39781. /** Adds a textbox to the window for entering strings.
  39782. @param name an internal name for the text-box. This is the name to pass to
  39783. the getTextEditorContents() method to find out what the
  39784. user typed-in.
  39785. @param initialContents a string to show in the text box when it's first shown
  39786. @param onScreenLabel if this is non-empty, it will be displayed next to the
  39787. text-box to label it.
  39788. @param isPasswordBox if true, the text editor will display asterisks instead of
  39789. the actual text
  39790. @see getTextEditorContents
  39791. */
  39792. void addTextEditor (const String& name,
  39793. const String& initialContents,
  39794. const String& onScreenLabel = String::empty,
  39795. bool isPasswordBox = false);
  39796. /** Returns the contents of a named textbox.
  39797. After showing an AlertWindow that contains a text editor, this can be
  39798. used to find out what the user has typed into it.
  39799. @param nameOfTextEditor the name of the text box that you're interested in
  39800. @see addTextEditor
  39801. */
  39802. const String getTextEditorContents (const String& nameOfTextEditor) const;
  39803. /** Adds a drop-down list of choices to the box.
  39804. After the box has been shown, the getComboBoxComponent() method can
  39805. be used to find out which item the user picked.
  39806. @param name the label to use for the drop-down list
  39807. @param items the list of items to show in it
  39808. @param onScreenLabel if this is non-empty, it will be displayed next to the
  39809. combo-box to label it.
  39810. @see getComboBoxComponent
  39811. */
  39812. void addComboBox (const String& name,
  39813. const StringArray& items,
  39814. const String& onScreenLabel = String::empty);
  39815. /** Returns a drop-down list that was added to the AlertWindow.
  39816. @param nameOfList the name that was passed into the addComboBox() method
  39817. when creating the drop-down
  39818. @returns the ComboBox component, or 0 if none was found for the given name.
  39819. */
  39820. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  39821. /** Adds a block of text.
  39822. This is handy for adding a multi-line note next to a textbox or combo-box,
  39823. to provide more details about what's going on.
  39824. */
  39825. void addTextBlock (const String& text);
  39826. /** Adds a progress-bar to the window.
  39827. @param progressValue a variable that will be repeatedly checked while the
  39828. dialog box is visible, to see how far the process has
  39829. got. The value should be in the range 0 to 1.0
  39830. */
  39831. void addProgressBarComponent (double& progressValue);
  39832. /** Adds a user-defined component to the dialog box.
  39833. @param component the component to add - its size should be set up correctly
  39834. before it is passed in. The caller is responsible for deleting
  39835. the component later on - the AlertWindow won't delete it.
  39836. */
  39837. void addCustomComponent (Component* component);
  39838. /** Returns the number of custom components in the dialog box.
  39839. @see getCustomComponent, addCustomComponent
  39840. */
  39841. int getNumCustomComponents() const;
  39842. /** Returns one of the custom components in the dialog box.
  39843. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  39844. will return 0
  39845. @see getNumCustomComponents, addCustomComponent
  39846. */
  39847. Component* getCustomComponent (int index) const;
  39848. /** Removes one of the custom components in the dialog box.
  39849. Note that this won't delete it, it just removes the component from the window
  39850. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  39851. will return 0
  39852. @returns the component that was removed (or zero)
  39853. @see getNumCustomComponents, addCustomComponent
  39854. */
  39855. Component* removeCustomComponent (int index);
  39856. /** Returns true if the window contains any components other than just buttons.*/
  39857. bool containsAnyExtraComponents() const;
  39858. // easy-to-use message box functions:
  39859. /** Shows a dialog box that just has a message and a single button to get rid of it.
  39860. The box is shown modally, and the method returns after the user
  39861. has clicked the button (or pressed the escape or return keys).
  39862. @param iconType the type of icon to show
  39863. @param title the headline to show at the top of the box
  39864. @param message a longer, more descriptive message to show underneath the
  39865. headline
  39866. @param buttonText the text to show in the button - if this string is empty, the
  39867. default string "ok" (or a localised version) will be used.
  39868. @param associatedComponent if this is non-zero, it specifies the component that the
  39869. alert window should be associated with. Depending on the look
  39870. and feel, this might be used for positioning of the alert window.
  39871. */
  39872. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  39873. const String& title,
  39874. const String& message,
  39875. const String& buttonText = String::empty,
  39876. Component* associatedComponent = 0);
  39877. /** Shows a dialog box with two buttons.
  39878. Ideal for ok/cancel or yes/no choices. The return key can also be used
  39879. to trigger the first button, and the escape key for the second button.
  39880. @param iconType the type of icon to show
  39881. @param title the headline to show at the top of the box
  39882. @param message a longer, more descriptive message to show underneath the
  39883. headline
  39884. @param button1Text the text to show in the first button - if this string is
  39885. empty, the default string "ok" (or a localised version of it)
  39886. will be used.
  39887. @param button2Text the text to show in the second button - if this string is
  39888. empty, the default string "cancel" (or a localised version of it)
  39889. will be used.
  39890. @param associatedComponent if this is non-zero, it specifies the component that the
  39891. alert window should be associated with. Depending on the look
  39892. and feel, this might be used for positioning of the alert window.
  39893. @returns true if button 1 was clicked, false if it was button 2
  39894. */
  39895. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  39896. const String& title,
  39897. const String& message,
  39898. const String& button1Text = String::empty,
  39899. const String& button2Text = String::empty,
  39900. Component* associatedComponent = 0);
  39901. /** Shows a dialog box with three buttons.
  39902. Ideal for yes/no/cancel boxes.
  39903. The escape key can be used to trigger the third button.
  39904. @param iconType the type of icon to show
  39905. @param title the headline to show at the top of the box
  39906. @param message a longer, more descriptive message to show underneath the
  39907. headline
  39908. @param button1Text the text to show in the first button - if an empty string, then
  39909. "yes" will be used (or a localised version of it)
  39910. @param button2Text the text to show in the first button - if an empty string, then
  39911. "no" will be used (or a localised version of it)
  39912. @param button3Text the text to show in the first button - if an empty string, then
  39913. "cancel" will be used (or a localised version of it)
  39914. @param associatedComponent if this is non-zero, it specifies the component that the
  39915. alert window should be associated with. Depending on the look
  39916. and feel, this might be used for positioning of the alert window.
  39917. @returns one of the following values:
  39918. - 0 if the third button was pressed (normally used for 'cancel')
  39919. - 1 if the first button was pressed (normally used for 'yes')
  39920. - 2 if the middle button was pressed (normally used for 'no')
  39921. */
  39922. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  39923. const String& title,
  39924. const String& message,
  39925. const String& button1Text = String::empty,
  39926. const String& button2Text = String::empty,
  39927. const String& button3Text = String::empty,
  39928. Component* associatedComponent = 0);
  39929. /** Shows an operating-system native dialog box.
  39930. @param title the title to use at the top
  39931. @param bodyText the longer message to show
  39932. @param isOkCancel if true, this will show an ok/cancel box, if false,
  39933. it'll show a box with just an ok button
  39934. @returns true if the ok button was pressed, false if they pressed cancel.
  39935. */
  39936. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  39937. const String& bodyText,
  39938. bool isOkCancel);
  39939. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  39940. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39941. methods.
  39942. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39943. */
  39944. enum ColourIds
  39945. {
  39946. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  39947. textColourId = 0x1001810, /**< The colour for the text. */
  39948. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  39949. };
  39950. juce_UseDebuggingNewOperator
  39951. protected:
  39952. /** @internal */
  39953. void paint (Graphics& g);
  39954. /** @internal */
  39955. void mouseDown (const MouseEvent& e);
  39956. /** @internal */
  39957. void mouseDrag (const MouseEvent& e);
  39958. /** @internal */
  39959. bool keyPressed (const KeyPress& key);
  39960. /** @internal */
  39961. void buttonClicked (Button* button);
  39962. /** @internal */
  39963. void lookAndFeelChanged();
  39964. /** @internal */
  39965. void userTriedToCloseWindow();
  39966. /** @internal */
  39967. int getDesktopWindowStyleFlags() const;
  39968. private:
  39969. String text;
  39970. TextLayout textLayout;
  39971. AlertIconType alertIconType;
  39972. ComponentBoundsConstrainer constrainer;
  39973. ComponentDragger dragger;
  39974. Rectangle<int> textArea;
  39975. Array<void*> buttons, textBoxes, comboBoxes;
  39976. Array<void*> progressBars, customComps, textBlocks, allComps;
  39977. StringArray textboxNames, comboBoxNames;
  39978. Font font;
  39979. Component* associatedComponent;
  39980. void updateLayout (bool onlyIncreaseSize);
  39981. // disable copy constructor
  39982. AlertWindow (const AlertWindow&);
  39983. AlertWindow& operator= (const AlertWindow&);
  39984. };
  39985. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  39986. /*** End of inlined file: juce_AlertWindow.h ***/
  39987. class ToggleButton;
  39988. class TextButton;
  39989. class AlertWindow;
  39990. class TextLayout;
  39991. class ScrollBar;
  39992. class BubbleComponent;
  39993. class ComboBox;
  39994. class Button;
  39995. class FilenameComponent;
  39996. class DocumentWindow;
  39997. class ResizableWindow;
  39998. class GroupComponent;
  39999. class MenuBarComponent;
  40000. class DropShadower;
  40001. class GlyphArrangement;
  40002. class PropertyComponent;
  40003. class TableHeaderComponent;
  40004. class Toolbar;
  40005. class ToolbarItemComponent;
  40006. class PopupMenu;
  40007. class ProgressBar;
  40008. class FileBrowserComponent;
  40009. class DirectoryContentsDisplayComponent;
  40010. class FilePreviewComponent;
  40011. class ImageButton;
  40012. /**
  40013. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  40014. can be used to apply different 'skins' to the application.
  40015. */
  40016. class JUCE_API LookAndFeel
  40017. {
  40018. public:
  40019. /** Creates the default JUCE look and feel. */
  40020. LookAndFeel();
  40021. /** Destructor. */
  40022. virtual ~LookAndFeel();
  40023. /** Returns the current default look-and-feel for a component to use when it
  40024. hasn't got one explicitly set.
  40025. @see setDefaultLookAndFeel
  40026. */
  40027. static LookAndFeel& getDefaultLookAndFeel() throw();
  40028. /** Changes the default look-and-feel.
  40029. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  40030. set to 0, it will revert to using the default one. The
  40031. object passed-in must be deleted by the caller when
  40032. it's no longer needed.
  40033. @see getDefaultLookAndFeel
  40034. */
  40035. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  40036. /** Looks for a colour that has been registered with the given colour ID number.
  40037. If a colour has been set for this ID number using setColour(), then it is
  40038. returned. If none has been set, it will just return Colours::black.
  40039. The colour IDs for various purposes are stored as enums in the components that
  40040. they are relevent to - for an example, see Slider::ColourIds,
  40041. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  40042. If you're looking up a colour for use in drawing a component, it's usually
  40043. best not to call this directly, but to use the Component::findColour() method
  40044. instead. That will first check whether a suitable colour has been registered
  40045. directly with the component, and will fall-back on calling the component's
  40046. LookAndFeel's findColour() method if none is found.
  40047. @see setColour, Component::findColour, Component::setColour
  40048. */
  40049. const Colour findColour (int colourId) const throw();
  40050. /** Registers a colour to be used for a particular purpose.
  40051. For more details, see the comments for findColour().
  40052. @see findColour, Component::findColour, Component::setColour
  40053. */
  40054. void setColour (int colourId, const Colour& colour) throw();
  40055. /** Returns true if the specified colour ID has been explicitly set using the
  40056. setColour() method.
  40057. */
  40058. bool isColourSpecified (int colourId) const throw();
  40059. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  40060. /** Allows you to change the default sans-serif font.
  40061. If you need to supply your own Typeface object for any of the default fonts, rather
  40062. than just supplying the name (e.g. if you want to use an embedded font), then
  40063. you should instead override getTypefaceForFont() to create and return the typeface.
  40064. */
  40065. void setDefaultSansSerifTypefaceName (const String& newName);
  40066. /** Override this to get the chance to swap a component's mouse cursor for a
  40067. customised one.
  40068. */
  40069. virtual const MouseCursor getMouseCursorFor (Component& component);
  40070. /** Draws the lozenge-shaped background for a standard button. */
  40071. virtual void drawButtonBackground (Graphics& g,
  40072. Button& button,
  40073. const Colour& backgroundColour,
  40074. bool isMouseOverButton,
  40075. bool isButtonDown);
  40076. virtual const Font getFontForTextButton (TextButton& button);
  40077. /** Draws the text for a TextButton. */
  40078. virtual void drawButtonText (Graphics& g,
  40079. TextButton& button,
  40080. bool isMouseOverButton,
  40081. bool isButtonDown);
  40082. /** Draws the contents of a standard ToggleButton. */
  40083. virtual void drawToggleButton (Graphics& g,
  40084. ToggleButton& button,
  40085. bool isMouseOverButton,
  40086. bool isButtonDown);
  40087. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  40088. virtual void drawTickBox (Graphics& g,
  40089. Component& component,
  40090. float x, float y, float w, float h,
  40091. bool ticked,
  40092. bool isEnabled,
  40093. bool isMouseOverButton,
  40094. bool isButtonDown);
  40095. /* AlertWindow handling..
  40096. */
  40097. virtual AlertWindow* createAlertWindow (const String& title,
  40098. const String& message,
  40099. const String& button1,
  40100. const String& button2,
  40101. const String& button3,
  40102. AlertWindow::AlertIconType iconType,
  40103. int numButtons,
  40104. Component* associatedComponent);
  40105. virtual void drawAlertBox (Graphics& g,
  40106. AlertWindow& alert,
  40107. const Rectangle<int>& textArea,
  40108. TextLayout& textLayout);
  40109. virtual int getAlertBoxWindowFlags();
  40110. virtual int getAlertWindowButtonHeight();
  40111. virtual const Font getAlertWindowFont();
  40112. /** Draws a progress bar.
  40113. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  40114. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  40115. isn't known). It can use the current time as a basis for playing an animation.
  40116. (Used by progress bars in AlertWindow).
  40117. */
  40118. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  40119. int width, int height,
  40120. double progress, const String& textToShow);
  40121. // Draws a small image that spins to indicate that something's happening..
  40122. // This method should use the current time to animate itself, so just keep
  40123. // repainting it every so often.
  40124. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  40125. int x, int y, int w, int h);
  40126. /** Draws one of the buttons on a scrollbar.
  40127. @param g the context to draw into
  40128. @param scrollbar the bar itself
  40129. @param width the width of the button
  40130. @param height the height of the button
  40131. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  40132. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  40133. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  40134. @param isButtonDown whether the mouse button's held down
  40135. */
  40136. virtual void drawScrollbarButton (Graphics& g,
  40137. ScrollBar& scrollbar,
  40138. int width, int height,
  40139. int buttonDirection,
  40140. bool isScrollbarVertical,
  40141. bool isMouseOverButton,
  40142. bool isButtonDown);
  40143. /** Draws the thumb area of a scrollbar.
  40144. @param g the context to draw into
  40145. @param scrollbar the bar itself
  40146. @param x the x position of the left edge of the thumb area to draw in
  40147. @param y the y position of the top edge of the thumb area to draw in
  40148. @param width the width of the thumb area to draw in
  40149. @param height the height of the thumb area to draw in
  40150. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  40151. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  40152. thumb, or its x position for horizontal bars
  40153. @param thumbSize for vertical bars, the height of the thumb, or its width for
  40154. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  40155. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  40156. currently dragging the thumb
  40157. @param isMouseDown whether the mouse is currently dragging the scrollbar
  40158. */
  40159. virtual void drawScrollbar (Graphics& g,
  40160. ScrollBar& scrollbar,
  40161. int x, int y,
  40162. int width, int height,
  40163. bool isScrollbarVertical,
  40164. int thumbStartPosition,
  40165. int thumbSize,
  40166. bool isMouseOver,
  40167. bool isMouseDown);
  40168. /** Returns the component effect to use for a scrollbar */
  40169. virtual ImageEffectFilter* getScrollbarEffect();
  40170. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  40171. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  40172. /** Returns the default thickness to use for a scrollbar. */
  40173. virtual int getDefaultScrollbarWidth();
  40174. /** Returns the length in pixels to use for a scrollbar button. */
  40175. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  40176. /** Returns a tick shape for use in yes/no boxes, etc. */
  40177. virtual const Path getTickShape (float height);
  40178. /** Returns a cross shape for use in yes/no boxes, etc. */
  40179. virtual const Path getCrossShape (float height);
  40180. /** Draws the + or - box in a treeview. */
  40181. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  40182. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  40183. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  40184. // these return an image from the ImageCache, so use ImageCache::release() to free it
  40185. virtual const Image getDefaultFolderImage();
  40186. virtual const Image getDefaultDocumentFileImage();
  40187. virtual void createFileChooserHeaderText (const String& title,
  40188. const String& instructions,
  40189. GlyphArrangement& destArrangement,
  40190. int width);
  40191. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  40192. const String& filename, Image* icon,
  40193. const String& fileSizeDescription,
  40194. const String& fileTimeDescription,
  40195. bool isDirectory,
  40196. bool isItemSelected,
  40197. int itemIndex);
  40198. virtual Button* createFileBrowserGoUpButton();
  40199. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  40200. DirectoryContentsDisplayComponent* fileListComponent,
  40201. FilePreviewComponent* previewComp,
  40202. ComboBox* currentPathBox,
  40203. TextEditor* filenameBox,
  40204. Button* goUpButton);
  40205. virtual void drawBubble (Graphics& g,
  40206. float tipX, float tipY,
  40207. float boxX, float boxY, float boxW, float boxH);
  40208. /** Fills the background of a popup menu component. */
  40209. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40210. /** Draws one of the items in a popup menu. */
  40211. virtual void drawPopupMenuItem (Graphics& g,
  40212. int width, int height,
  40213. bool isSeparator,
  40214. bool isActive,
  40215. bool isHighlighted,
  40216. bool isTicked,
  40217. bool hasSubMenu,
  40218. const String& text,
  40219. const String& shortcutKeyText,
  40220. Image* image,
  40221. const Colour* const textColour);
  40222. /** Returns the size and style of font to use in popup menus. */
  40223. virtual const Font getPopupMenuFont();
  40224. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  40225. int width, int height,
  40226. bool isScrollUpArrow);
  40227. /** Finds the best size for an item in a popup menu. */
  40228. virtual void getIdealPopupMenuItemSize (const String& text,
  40229. bool isSeparator,
  40230. int standardMenuItemHeight,
  40231. int& idealWidth,
  40232. int& idealHeight);
  40233. virtual int getMenuWindowFlags();
  40234. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40235. bool isMouseOverBar,
  40236. MenuBarComponent& menuBar);
  40237. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40238. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40239. virtual void drawMenuBarItem (Graphics& g,
  40240. int width, int height,
  40241. int itemIndex,
  40242. const String& itemText,
  40243. bool isMouseOverItem,
  40244. bool isMenuOpen,
  40245. bool isMouseOverBar,
  40246. MenuBarComponent& menuBar);
  40247. virtual void drawComboBox (Graphics& g, int width, int height,
  40248. bool isButtonDown,
  40249. int buttonX, int buttonY,
  40250. int buttonW, int buttonH,
  40251. ComboBox& box);
  40252. virtual const Font getComboBoxFont (ComboBox& box);
  40253. virtual Label* createComboBoxTextBox (ComboBox& box);
  40254. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  40255. virtual void drawLabel (Graphics& g, Label& label);
  40256. virtual void drawLinearSlider (Graphics& g,
  40257. int x, int y,
  40258. int width, int height,
  40259. float sliderPos,
  40260. float minSliderPos,
  40261. float maxSliderPos,
  40262. const Slider::SliderStyle style,
  40263. Slider& slider);
  40264. virtual void drawLinearSliderBackground (Graphics& g,
  40265. int x, int y,
  40266. int width, int height,
  40267. float sliderPos,
  40268. float minSliderPos,
  40269. float maxSliderPos,
  40270. const Slider::SliderStyle style,
  40271. Slider& slider);
  40272. virtual void drawLinearSliderThumb (Graphics& g,
  40273. int x, int y,
  40274. int width, int height,
  40275. float sliderPos,
  40276. float minSliderPos,
  40277. float maxSliderPos,
  40278. const Slider::SliderStyle style,
  40279. Slider& slider);
  40280. virtual int getSliderThumbRadius (Slider& slider);
  40281. virtual void drawRotarySlider (Graphics& g,
  40282. int x, int y,
  40283. int width, int height,
  40284. float sliderPosProportional,
  40285. float rotaryStartAngle,
  40286. float rotaryEndAngle,
  40287. Slider& slider);
  40288. virtual Button* createSliderButton (bool isIncrement);
  40289. virtual Label* createSliderTextBox (Slider& slider);
  40290. virtual ImageEffectFilter* getSliderEffect();
  40291. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  40292. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  40293. virtual Button* createFilenameComponentBrowseButton (const String& text);
  40294. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  40295. ComboBox* filenameBox, Button* browseButton);
  40296. virtual void drawCornerResizer (Graphics& g,
  40297. int w, int h,
  40298. bool isMouseOver,
  40299. bool isMouseDragging);
  40300. virtual void drawResizableFrame (Graphics& g,
  40301. int w, int h,
  40302. const BorderSize& borders);
  40303. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  40304. const BorderSize& border,
  40305. ResizableWindow& window);
  40306. virtual void drawResizableWindowBorder (Graphics& g,
  40307. int w, int h,
  40308. const BorderSize& border,
  40309. ResizableWindow& window);
  40310. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  40311. Graphics& g, int w, int h,
  40312. int titleSpaceX, int titleSpaceW,
  40313. const Image* icon,
  40314. bool drawTitleTextOnLeft);
  40315. virtual Button* createDocumentWindowButton (int buttonType);
  40316. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40317. int titleBarX, int titleBarY,
  40318. int titleBarW, int titleBarH,
  40319. Button* minimiseButton,
  40320. Button* maximiseButton,
  40321. Button* closeButton,
  40322. bool positionTitleBarButtonsOnLeft);
  40323. virtual int getDefaultMenuBarHeight();
  40324. virtual DropShadower* createDropShadowerForComponent (Component* component);
  40325. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  40326. int w, int h,
  40327. bool isVerticalBar,
  40328. bool isMouseOver,
  40329. bool isMouseDragging);
  40330. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  40331. const String& text,
  40332. const Justification& position,
  40333. GroupComponent& group);
  40334. virtual void createTabButtonShape (Path& p,
  40335. int width, int height,
  40336. int tabIndex,
  40337. const String& text,
  40338. Button& button,
  40339. TabbedButtonBar::Orientation orientation,
  40340. bool isMouseOver,
  40341. bool isMouseDown,
  40342. bool isFrontTab);
  40343. virtual void fillTabButtonShape (Graphics& g,
  40344. const Path& path,
  40345. const Colour& preferredBackgroundColour,
  40346. int tabIndex,
  40347. const String& text,
  40348. Button& button,
  40349. TabbedButtonBar::Orientation orientation,
  40350. bool isMouseOver,
  40351. bool isMouseDown,
  40352. bool isFrontTab);
  40353. virtual void drawTabButtonText (Graphics& g,
  40354. int x, int y, int w, int h,
  40355. const Colour& preferredBackgroundColour,
  40356. int tabIndex,
  40357. const String& text,
  40358. Button& button,
  40359. TabbedButtonBar::Orientation orientation,
  40360. bool isMouseOver,
  40361. bool isMouseDown,
  40362. bool isFrontTab);
  40363. virtual int getTabButtonOverlap (int tabDepth);
  40364. virtual int getTabButtonSpaceAroundImage();
  40365. virtual int getTabButtonBestWidth (int tabIndex,
  40366. const String& text,
  40367. int tabDepth,
  40368. Button& button);
  40369. virtual void drawTabButton (Graphics& g,
  40370. int w, int h,
  40371. const Colour& preferredColour,
  40372. int tabIndex,
  40373. const String& text,
  40374. Button& button,
  40375. TabbedButtonBar::Orientation orientation,
  40376. bool isMouseOver,
  40377. bool isMouseDown,
  40378. bool isFrontTab);
  40379. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  40380. int w, int h,
  40381. TabbedButtonBar& tabBar,
  40382. TabbedButtonBar::Orientation orientation);
  40383. virtual Button* createTabBarExtrasButton();
  40384. virtual void drawImageButton (Graphics& g, Image* image,
  40385. int imageX, int imageY, int imageW, int imageH,
  40386. const Colour& overlayColour,
  40387. float imageOpacity,
  40388. ImageButton& button);
  40389. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  40390. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  40391. int width, int height,
  40392. bool isMouseOver, bool isMouseDown,
  40393. int columnFlags);
  40394. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  40395. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  40396. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  40397. bool isMouseOver, bool isMouseDown,
  40398. ToolbarItemComponent& component);
  40399. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  40400. const String& text, ToolbarItemComponent& component);
  40401. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  40402. bool isOpen, int width, int height);
  40403. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  40404. PropertyComponent& component);
  40405. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  40406. PropertyComponent& component);
  40407. virtual const Rectangle<int> getPropertyComponentContentPosition (PropertyComponent& component);
  40408. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  40409. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  40410. /**
  40411. */
  40412. virtual void playAlertSound();
  40413. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  40414. static void drawGlassSphere (Graphics& g,
  40415. float x, float y,
  40416. float diameter,
  40417. const Colour& colour,
  40418. float outlineThickness) throw();
  40419. static void drawGlassPointer (Graphics& g,
  40420. float x, float y,
  40421. float diameter,
  40422. const Colour& colour, float outlineThickness,
  40423. int direction) throw();
  40424. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  40425. static void drawGlassLozenge (Graphics& g,
  40426. float x, float y,
  40427. float width, float height,
  40428. const Colour& colour,
  40429. float outlineThickness,
  40430. float cornerSize,
  40431. bool flatOnLeft, bool flatOnRight,
  40432. bool flatOnTop, bool flatOnBottom) throw();
  40433. juce_UseDebuggingNewOperator
  40434. private:
  40435. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  40436. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  40437. Array <int> colourIds;
  40438. Array <Colour> colours;
  40439. // default typeface names
  40440. String defaultSans, defaultSerif, defaultFixed;
  40441. void drawShinyButtonShape (Graphics& g,
  40442. float x, float y, float w, float h, float maxCornerSize,
  40443. const Colour& baseColour,
  40444. float strokeWidth,
  40445. bool flatOnLeft,
  40446. bool flatOnRight,
  40447. bool flatOnTop,
  40448. bool flatOnBottom) throw();
  40449. LookAndFeel (const LookAndFeel&);
  40450. LookAndFeel& operator= (const LookAndFeel&);
  40451. };
  40452. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  40453. /*** End of inlined file: juce_LookAndFeel.h ***/
  40454. #endif
  40455. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40456. /*** Start of inlined file: juce_OldSchoolLookAndFeel.h ***/
  40457. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40458. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40459. /**
  40460. The original Juce look-and-feel.
  40461. */
  40462. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  40463. {
  40464. public:
  40465. /** Creates the default JUCE look and feel. */
  40466. OldSchoolLookAndFeel();
  40467. /** Destructor. */
  40468. virtual ~OldSchoolLookAndFeel();
  40469. /** Draws the lozenge-shaped background for a standard button. */
  40470. virtual void drawButtonBackground (Graphics& g,
  40471. Button& button,
  40472. const Colour& backgroundColour,
  40473. bool isMouseOverButton,
  40474. bool isButtonDown);
  40475. /** Draws the contents of a standard ToggleButton. */
  40476. virtual void drawToggleButton (Graphics& g,
  40477. ToggleButton& button,
  40478. bool isMouseOverButton,
  40479. bool isButtonDown);
  40480. virtual void drawTickBox (Graphics& g,
  40481. Component& component,
  40482. float x, float y, float w, float h,
  40483. bool ticked,
  40484. bool isEnabled,
  40485. bool isMouseOverButton,
  40486. bool isButtonDown);
  40487. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  40488. int width, int height,
  40489. double progress, const String& textToShow);
  40490. virtual void drawScrollbarButton (Graphics& g,
  40491. ScrollBar& scrollbar,
  40492. int width, int height,
  40493. int buttonDirection,
  40494. bool isScrollbarVertical,
  40495. bool isMouseOverButton,
  40496. bool isButtonDown);
  40497. virtual void drawScrollbar (Graphics& g,
  40498. ScrollBar& scrollbar,
  40499. int x, int y,
  40500. int width, int height,
  40501. bool isScrollbarVertical,
  40502. int thumbStartPosition,
  40503. int thumbSize,
  40504. bool isMouseOver,
  40505. bool isMouseDown);
  40506. virtual ImageEffectFilter* getScrollbarEffect();
  40507. virtual void drawTextEditorOutline (Graphics& g,
  40508. int width, int height,
  40509. TextEditor& textEditor);
  40510. /** Fills the background of a popup menu component. */
  40511. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40512. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40513. bool isMouseOverBar,
  40514. MenuBarComponent& menuBar);
  40515. virtual void drawComboBox (Graphics& g, int width, int height,
  40516. bool isButtonDown,
  40517. int buttonX, int buttonY,
  40518. int buttonW, int buttonH,
  40519. ComboBox& box);
  40520. virtual const Font getComboBoxFont (ComboBox& box);
  40521. virtual void drawLinearSlider (Graphics& g,
  40522. int x, int y,
  40523. int width, int height,
  40524. float sliderPos,
  40525. float minSliderPos,
  40526. float maxSliderPos,
  40527. const Slider::SliderStyle style,
  40528. Slider& slider);
  40529. virtual int getSliderThumbRadius (Slider& slider);
  40530. virtual Button* createSliderButton (bool isIncrement);
  40531. virtual ImageEffectFilter* getSliderEffect();
  40532. virtual void drawCornerResizer (Graphics& g,
  40533. int w, int h,
  40534. bool isMouseOver,
  40535. bool isMouseDragging);
  40536. virtual Button* createDocumentWindowButton (int buttonType);
  40537. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40538. int titleBarX, int titleBarY,
  40539. int titleBarW, int titleBarH,
  40540. Button* minimiseButton,
  40541. Button* maximiseButton,
  40542. Button* closeButton,
  40543. bool positionTitleBarButtonsOnLeft);
  40544. juce_UseDebuggingNewOperator
  40545. private:
  40546. DropShadowEffect scrollbarShadow;
  40547. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  40548. OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  40549. };
  40550. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40551. /*** End of inlined file: juce_OldSchoolLookAndFeel.h ***/
  40552. #endif
  40553. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  40554. #endif
  40555. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  40556. #endif
  40557. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  40558. #endif
  40559. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40560. /*** Start of inlined file: juce_PopupMenuCustomComponent.h ***/
  40561. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40562. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40563. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  40564. @see PopupMenu::addCustomItem
  40565. */
  40566. class JUCE_API PopupMenuCustomComponent : public Component,
  40567. public ReferenceCountedObject
  40568. {
  40569. public:
  40570. /** Destructor. */
  40571. ~PopupMenuCustomComponent();
  40572. /** Chooses the size that this component would like to have.
  40573. Note that the size which this method returns isn't necessarily the one that
  40574. the menu will give it, as it will be stretched to fit the other items in
  40575. the menu.
  40576. */
  40577. virtual void getIdealSize (int& idealWidth,
  40578. int& idealHeight) = 0;
  40579. /** Dismisses the menu indicating that this item has been chosen.
  40580. This will cause the menu to exit from its modal state, returning
  40581. this item's id as the result.
  40582. */
  40583. void triggerMenuItem();
  40584. /** Returns true if this item should be highlighted because the mouse is
  40585. over it.
  40586. You can call this method in your paint() method to find out whether
  40587. to draw a highlight.
  40588. */
  40589. bool isItemHighlighted() const throw() { return isHighlighted; }
  40590. protected:
  40591. /** Constructor.
  40592. If isTriggeredAutomatically is true, then the menu will automatically detect
  40593. a click on this component and use that to trigger it. If it's false, then it's
  40594. up to your class to manually trigger the item if it wants to.
  40595. */
  40596. PopupMenuCustomComponent (bool isTriggeredAutomatically = true);
  40597. private:
  40598. friend class PopupMenu;
  40599. friend class PopupMenu::ItemComponent;
  40600. friend class PopupMenu::Window;
  40601. bool isHighlighted, isTriggeredAutomatically;
  40602. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  40603. PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  40604. };
  40605. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40606. /*** End of inlined file: juce_PopupMenuCustomComponent.h ***/
  40607. #endif
  40608. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  40609. #endif
  40610. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  40611. #endif
  40612. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  40613. #endif
  40614. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  40615. #endif
  40616. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  40617. /*** Start of inlined file: juce_LassoComponent.h ***/
  40618. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  40619. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  40620. /*** Start of inlined file: juce_SelectedItemSet.h ***/
  40621. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40622. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40623. /** Manages a list of selectable items.
  40624. Use one of these to keep a track of things that the user has highlighted, like
  40625. icons or things in a list.
  40626. The class is templated so that you can use it to hold either a set of pointers
  40627. to objects, or a set of ID numbers or handles, for cases where each item may
  40628. not always have a corresponding object.
  40629. To be informed when items are selected/deselected, register a ChangeListener with
  40630. this object.
  40631. @see SelectableObject
  40632. */
  40633. template <class SelectableItemType>
  40634. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  40635. {
  40636. public:
  40637. typedef SelectableItemType ItemType;
  40638. typedef PARAMETER_TYPE (SelectableItemType) ParameterType;
  40639. /** Creates an empty set. */
  40640. SelectedItemSet()
  40641. {
  40642. }
  40643. /** Creates a set based on an array of items. */
  40644. explicit SelectedItemSet (const Array <SelectableItemType>& items)
  40645. : selectedItems (items)
  40646. {
  40647. }
  40648. /** Creates a copy of another set. */
  40649. SelectedItemSet (const SelectedItemSet& other)
  40650. : selectedItems (other.selectedItems)
  40651. {
  40652. }
  40653. /** Creates a copy of another set. */
  40654. SelectedItemSet& operator= (const SelectedItemSet& other)
  40655. {
  40656. if (selectedItems != other.selectedItems)
  40657. {
  40658. selectedItems = other.selectedItems;
  40659. changed();
  40660. }
  40661. return *this;
  40662. }
  40663. /** Destructor. */
  40664. ~SelectedItemSet()
  40665. {
  40666. }
  40667. /** Clears any other currently selected items, and selects this item.
  40668. If this item is already the only thing selected, no change notification
  40669. will be sent out.
  40670. @see addToSelection, addToSelectionBasedOnModifiers
  40671. */
  40672. void selectOnly (ParameterType item)
  40673. {
  40674. if (isSelected (item))
  40675. {
  40676. for (int i = selectedItems.size(); --i >= 0;)
  40677. {
  40678. if (selectedItems.getUnchecked(i) != item)
  40679. {
  40680. deselect (selectedItems.getUnchecked(i));
  40681. i = jmin (i, selectedItems.size());
  40682. }
  40683. }
  40684. }
  40685. else
  40686. {
  40687. deselectAll();
  40688. changed();
  40689. selectedItems.add (item);
  40690. itemSelected (item);
  40691. }
  40692. }
  40693. /** Selects an item.
  40694. If the item is already selected, no change notification will be sent out.
  40695. @see selectOnly, addToSelectionBasedOnModifiers
  40696. */
  40697. void addToSelection (ParameterType item)
  40698. {
  40699. if (! isSelected (item))
  40700. {
  40701. changed();
  40702. selectedItems.add (item);
  40703. itemSelected (item);
  40704. }
  40705. }
  40706. /** Selects or deselects an item.
  40707. This will use the modifier keys to decide whether to deselect other items
  40708. first.
  40709. So if the shift key is held down, the item will be added without deselecting
  40710. anything (same as calling addToSelection() )
  40711. If no modifiers are down, the current selection will be cleared first (same
  40712. as calling selectOnly() )
  40713. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  40714. so it'll be added to the set unless it's already there, in which case it'll be
  40715. deselected.
  40716. If the items that you're selecting can also be dragged, you may need to use the
  40717. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  40718. subtleties of this kind of usage.
  40719. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  40720. */
  40721. void addToSelectionBasedOnModifiers (ParameterType item,
  40722. const ModifierKeys& modifiers)
  40723. {
  40724. if (modifiers.isShiftDown())
  40725. {
  40726. addToSelection (item);
  40727. }
  40728. else if (modifiers.isCommandDown())
  40729. {
  40730. if (isSelected (item))
  40731. deselect (item);
  40732. else
  40733. addToSelection (item);
  40734. }
  40735. else
  40736. {
  40737. selectOnly (item);
  40738. }
  40739. }
  40740. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  40741. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  40742. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  40743. makes it easy to handle multiple-selection of sets of objects that can also
  40744. be dragged.
  40745. For example, if you have several items already selected, and you click on
  40746. one of them (without dragging), then you'd expect this to deselect the other, and
  40747. just select the item you clicked on. But if you had clicked on this item and
  40748. dragged it, you'd have expected them all to stay selected.
  40749. When you call this method, you'll need to store the boolean result, because the
  40750. addToSelectionOnMouseUp() method will need to be know this value.
  40751. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  40752. */
  40753. bool addToSelectionOnMouseDown (ParameterType item,
  40754. const ModifierKeys& modifiers)
  40755. {
  40756. if (isSelected (item))
  40757. {
  40758. return ! modifiers.isPopupMenu();
  40759. }
  40760. else
  40761. {
  40762. addToSelectionBasedOnModifiers (item, modifiers);
  40763. return false;
  40764. }
  40765. }
  40766. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  40767. Call this during a mouseUp callback, when you have previously called the
  40768. addToSelectionOnMouseDown() method during your mouseDown event.
  40769. See addToSelectionOnMouseDown() for more info
  40770. @param item the item to select (or deselect)
  40771. @param modifiers the modifiers from the mouse-up event
  40772. @param wasItemDragged true if your item was dragged during the mouse click
  40773. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  40774. back from the addToSelectionOnMouseDown() call that you
  40775. should have made during the matching mouseDown event
  40776. */
  40777. void addToSelectionOnMouseUp (ParameterType item,
  40778. const ModifierKeys& modifiers,
  40779. const bool wasItemDragged,
  40780. const bool resultOfMouseDownSelectMethod)
  40781. {
  40782. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  40783. addToSelectionBasedOnModifiers (item, modifiers);
  40784. }
  40785. /** Deselects an item. */
  40786. void deselect (ParameterType item)
  40787. {
  40788. const int i = selectedItems.indexOf (item);
  40789. if (i >= 0)
  40790. {
  40791. changed();
  40792. itemDeselected (selectedItems.remove (i));
  40793. }
  40794. }
  40795. /** Deselects all items. */
  40796. void deselectAll()
  40797. {
  40798. if (selectedItems.size() > 0)
  40799. {
  40800. changed();
  40801. for (int i = selectedItems.size(); --i >= 0;)
  40802. {
  40803. itemDeselected (selectedItems.remove (i));
  40804. i = jmin (i, selectedItems.size());
  40805. }
  40806. }
  40807. }
  40808. /** Returns the number of currently selected items.
  40809. @see getSelectedItem
  40810. */
  40811. int getNumSelected() const throw()
  40812. {
  40813. return selectedItems.size();
  40814. }
  40815. /** Returns one of the currently selected items.
  40816. Returns 0 if the index is out-of-range.
  40817. @see getNumSelected
  40818. */
  40819. SelectableItemType getSelectedItem (const int index) const throw()
  40820. {
  40821. return selectedItems [index];
  40822. }
  40823. /** True if this item is currently selected. */
  40824. bool isSelected (ParameterType item) const throw()
  40825. {
  40826. return selectedItems.contains (item);
  40827. }
  40828. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  40829. /** Can be overridden to do special handling when an item is selected.
  40830. For example, if the item is an object, you might want to call it and tell
  40831. it that it's being selected.
  40832. */
  40833. virtual void itemSelected (SelectableItemType item) { (void) item; }
  40834. /** Can be overridden to do special handling when an item is deselected.
  40835. For example, if the item is an object, you might want to call it and tell
  40836. it that it's being deselected.
  40837. */
  40838. virtual void itemDeselected (SelectableItemType item) { (void) item; }
  40839. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  40840. */
  40841. void changed (const bool synchronous = false)
  40842. {
  40843. if (synchronous)
  40844. sendSynchronousChangeMessage (this);
  40845. else
  40846. sendChangeMessage (this);
  40847. }
  40848. juce_UseDebuggingNewOperator
  40849. private:
  40850. Array <SelectableItemType> selectedItems;
  40851. };
  40852. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40853. /*** End of inlined file: juce_SelectedItemSet.h ***/
  40854. /**
  40855. A class used by the LassoComponent to manage the things that it selects.
  40856. This allows the LassoComponent to find out which items are within the lasso,
  40857. and to change the list of selected items.
  40858. @see LassoComponent, SelectedItemSet
  40859. */
  40860. template <class SelectableItemType>
  40861. class LassoSource
  40862. {
  40863. public:
  40864. /** Destructor. */
  40865. virtual ~LassoSource() {}
  40866. /** Returns the set of items that lie within a given lassoable region.
  40867. Your implementation of this method must find all the relevent items that lie
  40868. within the given rectangle. and add them to the itemsFound array.
  40869. The co-ordinates are relative to the top-left of the lasso component's parent
  40870. component. (i.e. they are the same as the size and position of the lasso
  40871. component itself).
  40872. */
  40873. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  40874. const Rectangle<int>& area) = 0;
  40875. /** Returns the SelectedItemSet that the lasso should update.
  40876. This set will be continuously updated by the LassoComponent as it gets
  40877. dragged around, so make sure that you've got a ChangeListener attached to
  40878. the set so that your UI objects will know when the selection changes and
  40879. be able to update themselves appropriately.
  40880. */
  40881. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  40882. };
  40883. /**
  40884. A component that acts as a rectangular selection region, which you drag with
  40885. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  40886. To use one of these:
  40887. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  40888. component, and call its beginLasso() method, giving it a
  40889. suitable LassoSource object that it can use to find out which items are in
  40890. the active area.
  40891. - Each time your parent component gets a mouseDrag event, call dragLasso()
  40892. to update the lasso's position - it will use its LassoSource to calculate and
  40893. update the current selection.
  40894. - After the drag has finished and you get a mouseUp callback, you should call
  40895. endLasso() to clean up. This will make the lasso component invisible, and you
  40896. can remove it from the parent component, or delete it.
  40897. The class takes into account the modifier keys that are being held down while
  40898. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  40899. be added to the original selection; if ctrl or command is pressed, they will be
  40900. xor'ed with any previously selected items.
  40901. @see LassoSource, SelectedItemSet
  40902. */
  40903. template <class SelectableItemType>
  40904. class LassoComponent : public Component
  40905. {
  40906. public:
  40907. /** Creates a Lasso component.
  40908. The fill colour is used to fill the lasso'ed rectangle, and the outline
  40909. colour is used to draw a line around its edge.
  40910. */
  40911. explicit LassoComponent (const int outlineThickness_ = 1)
  40912. : source (0),
  40913. outlineThickness (outlineThickness_)
  40914. {
  40915. }
  40916. /** Destructor. */
  40917. ~LassoComponent()
  40918. {
  40919. }
  40920. /** Call this in your mouseDown event, to initialise a drag.
  40921. Pass in a suitable LassoSource object which the lasso will use to find
  40922. the items and change the selection.
  40923. After using this method to initialise the lasso, repeatedly call dragLasso()
  40924. in your component's mouseDrag callback.
  40925. @see dragLasso, endLasso, LassoSource
  40926. */
  40927. void beginLasso (const MouseEvent& e,
  40928. LassoSource <SelectableItemType>* const lassoSource)
  40929. {
  40930. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  40931. jassert (lassoSource != 0); // the source can't be null!
  40932. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  40933. source = lassoSource;
  40934. if (lassoSource != 0)
  40935. originalSelection = lassoSource->getLassoSelection().getItemArray();
  40936. setSize (0, 0);
  40937. dragStartPos = e.getMouseDownPosition();
  40938. }
  40939. /** Call this in your mouseDrag event, to update the lasso's position.
  40940. This must be repeatedly calling when the mouse is dragged, after you've
  40941. first initialised the lasso with beginLasso().
  40942. This method takes into account the modifier keys that are being held down, so
  40943. if shift is pressed, then the lassoed items will be added to any that were
  40944. previously selected; if ctrl or command is pressed, then they will be xor'ed
  40945. with previously selected items.
  40946. @see beginLasso, endLasso
  40947. */
  40948. void dragLasso (const MouseEvent& e)
  40949. {
  40950. if (source != 0)
  40951. {
  40952. setBounds (Rectangle<int> (dragStartPos, e.getPosition()));
  40953. setVisible (true);
  40954. Array <SelectableItemType> itemsInLasso;
  40955. source->findLassoItemsInArea (itemsInLasso, getBounds());
  40956. if (e.mods.isShiftDown())
  40957. {
  40958. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  40959. itemsInLasso.addArray (originalSelection);
  40960. }
  40961. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  40962. {
  40963. Array <SelectableItemType> originalMinusNew (originalSelection);
  40964. originalMinusNew.removeValuesIn (itemsInLasso);
  40965. itemsInLasso.removeValuesIn (originalSelection);
  40966. itemsInLasso.addArray (originalMinusNew);
  40967. }
  40968. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  40969. }
  40970. }
  40971. /** Call this in your mouseUp event, after the lasso has been dragged.
  40972. @see beginLasso, dragLasso
  40973. */
  40974. void endLasso()
  40975. {
  40976. source = 0;
  40977. originalSelection.clear();
  40978. setVisible (false);
  40979. }
  40980. /** A set of colour IDs to use to change the colour of various aspects of the label.
  40981. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40982. methods.
  40983. Note that you can also use the constants from TextEditor::ColourIds to change the
  40984. colour of the text editor that is opened when a label is editable.
  40985. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40986. */
  40987. enum ColourIds
  40988. {
  40989. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  40990. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  40991. };
  40992. /** @internal */
  40993. void paint (Graphics& g)
  40994. {
  40995. g.fillAll (findColour (lassoFillColourId));
  40996. g.setColour (findColour (lassoOutlineColourId));
  40997. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  40998. // this suggests that you've left a lasso comp lying around after the
  40999. // mouse drag has finished.. Be careful to call endLasso() when you get a
  41000. // mouse-up event.
  41001. jassert (isMouseButtonDownAnywhere());
  41002. }
  41003. /** @internal */
  41004. bool hitTest (int, int) { return false; }
  41005. juce_UseDebuggingNewOperator
  41006. private:
  41007. Array <SelectableItemType> originalSelection;
  41008. LassoSource <SelectableItemType>* source;
  41009. int outlineThickness;
  41010. Point<int> dragStartPos;
  41011. };
  41012. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  41013. /*** End of inlined file: juce_LassoComponent.h ***/
  41014. #endif
  41015. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  41016. #endif
  41017. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  41018. #endif
  41019. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41020. /*** Start of inlined file: juce_MouseHoverDetector.h ***/
  41021. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41022. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41023. /**
  41024. Monitors a component for mouse activity, and triggers a callback
  41025. when the mouse hovers in one place for a specified length of time.
  41026. To use a hover-detector, just create one and call its setHoverComponent()
  41027. method to start it watching a component. You can call setHoverComponent (0)
  41028. to make it inactive.
  41029. (Be careful not to delete a component that's being monitored without first
  41030. stopping or deleting the hover detector).
  41031. */
  41032. class JUCE_API MouseHoverDetector
  41033. {
  41034. public:
  41035. /** Creates a hover detector.
  41036. Initially the object is inactive, and you need to tell it which component
  41037. to monitor, using the setHoverComponent() method.
  41038. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  41039. needs to stay still before the mouseHovered() method
  41040. is invoked. You can change this setting later with
  41041. the setHoverTimeMillisecs() method
  41042. */
  41043. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  41044. /** Destructor. */
  41045. virtual ~MouseHoverDetector();
  41046. /** Changes the time for which the mouse has to stay still before it's considered
  41047. to be hovering.
  41048. */
  41049. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  41050. /** Changes the component that's being monitored for hovering.
  41051. Be careful not to delete a component that's being monitored without first
  41052. stopping or deleting the hover detector.
  41053. */
  41054. void setHoverComponent (Component* const newSourceComponent);
  41055. protected:
  41056. /** Called back when the mouse hovers.
  41057. After the mouse has stayed still over the component for the length of time
  41058. specified by setHoverTimeMillisecs(), this method will be invoked.
  41059. When the mouse is first moved after this callback has occurred, the
  41060. mouseMovedAfterHover() method will be called.
  41061. @param mouseX the mouse's X position relative to the component being monitored
  41062. @param mouseY the mouse's Y position relative to the component being monitored
  41063. */
  41064. virtual void mouseHovered (int mouseX,
  41065. int mouseY) = 0;
  41066. /** Called when the mouse is moved away after just having hovered. */
  41067. virtual void mouseMovedAfterHover() = 0;
  41068. private:
  41069. class JUCE_API HoverDetectorInternal : public MouseListener,
  41070. public Timer
  41071. {
  41072. public:
  41073. MouseHoverDetector* owner;
  41074. int lastX, lastY;
  41075. void timerCallback();
  41076. void mouseEnter (const MouseEvent&);
  41077. void mouseExit (const MouseEvent&);
  41078. void mouseDown (const MouseEvent&);
  41079. void mouseUp (const MouseEvent&);
  41080. void mouseMove (const MouseEvent&);
  41081. void mouseWheelMove (const MouseEvent&, float, float);
  41082. } internalTimer;
  41083. friend class HoverDetectorInternal;
  41084. Component* source;
  41085. int hoverTimeMillisecs;
  41086. bool hasJustHovered;
  41087. void hoverTimerCallback();
  41088. void checkJustHoveredCallback();
  41089. MouseHoverDetector (const MouseHoverDetector&);
  41090. MouseHoverDetector& operator= (const MouseHoverDetector&);
  41091. };
  41092. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41093. /*** End of inlined file: juce_MouseHoverDetector.h ***/
  41094. #endif
  41095. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41096. /*** Start of inlined file: juce_MouseInputSource.h ***/
  41097. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41098. #define __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41099. class Component;
  41100. class ComponentPeer;
  41101. class MouseInputSourceInternal;
  41102. /**
  41103. Represents a linear source of mouse events from a mouse device or individual finger
  41104. in a multi-touch environment.
  41105. Each MouseEvent object contains a reference to the MouseInputSource that generated
  41106. it. In an environment with a single mouse for input, all events will come from the
  41107. same source, but in a multi-touch system, there may be multiple MouseInputSource
  41108. obects active, each representing a stream of events coming from a particular finger.
  41109. Events coming from a single MouseInputSource are always sent in a fixed and predictable
  41110. order: a mouseMove will never be called without a mouseEnter having been sent beforehand,
  41111. the only events that can happen between a mouseDown and its corresponding mouseUp are
  41112. mouseDrags, etc.
  41113. When there are multiple touches arriving from multiple MouseInputSources, their
  41114. event streams may arrive in an interleaved order, so you should use the getIndex()
  41115. method to find out which finger each event came from.
  41116. @see MouseEvent
  41117. */
  41118. class JUCE_API MouseInputSource
  41119. {
  41120. public:
  41121. /** Creates a MouseInputSource.
  41122. You should never actually create a MouseInputSource in your own code - the
  41123. library takes care of managing these objects.
  41124. */
  41125. MouseInputSource (int index, bool isMouseDevice);
  41126. /** Destructor. */
  41127. ~MouseInputSource();
  41128. /** Returns true if this object represents a normal desk-based mouse device. */
  41129. bool isMouse() const;
  41130. /** Returns true if this object represents a source of touch events - i.e. a finger or stylus. */
  41131. bool isTouch() const;
  41132. /** Returns true if this source has an on-screen pointer that can hover over
  41133. items without clicking them.
  41134. */
  41135. bool canHover() const;
  41136. /** Returns true if this source may have a scroll wheel. */
  41137. bool hasMouseWheel() const;
  41138. /** Returns this source's index in the global list of possible sources.
  41139. If the system only has a single mouse, there will only be a single MouseInputSource
  41140. with an index of 0.
  41141. If the system supports multi-touch input, then the index will represent a finger
  41142. number, starting from 0. When the first touch event begins, it will have finger
  41143. number 0, and then if a second touch happens while the first is still down, it
  41144. will have index 1, etc.
  41145. */
  41146. int getIndex() const;
  41147. /** Returns true if this device is currently being pressed. */
  41148. bool isDragging() const;
  41149. /** Returns the last-known screen position of this source. */
  41150. const Point<int> getScreenPosition() const;
  41151. /** Returns a set of modifiers that indicate which buttons are currently
  41152. held down on this device.
  41153. */
  41154. const ModifierKeys getCurrentModifiers() const;
  41155. /** Returns the component that was last known to be under this pointer. */
  41156. Component* getComponentUnderMouse() const;
  41157. /** Tells the device to dispatch a mouse-move event.
  41158. This is asynchronous - the event will occur on the message thread.
  41159. */
  41160. void triggerFakeMove() const;
  41161. /** Returns the number of clicks that should be counted as belonging to the
  41162. current mouse event.
  41163. So the mouse is currently down and it's the second click of a double-click, this
  41164. will return 2.
  41165. */
  41166. int getNumberOfMultipleClicks() const throw();
  41167. /** Returns the time at which the last mouse-down occurred. */
  41168. const Time getLastMouseDownTime() const throw();
  41169. /** Returns the screen position at which the last mouse-down occurred. */
  41170. const Point<int> getLastMouseDownPosition() const throw();
  41171. /** Returns true if this mouse is currently down, and if it has been dragged more
  41172. than a couple of pixels from the place it was pressed.
  41173. */
  41174. bool hasMouseMovedSignificantlySincePressed() const throw();
  41175. bool hasMouseCursor() const throw();
  41176. void showMouseCursor (const MouseCursor& cursor);
  41177. void hideCursor();
  41178. void revealCursor();
  41179. void forceMouseCursorUpdate();
  41180. bool canDoUnboundedMovement() const throw();
  41181. /** Allows the mouse to move beyond the edges of the screen.
  41182. Calling this method when the mouse button is currently pressed will remove the cursor
  41183. from the screen and allow the mouse to (seem to) move beyond the edges of the screen.
  41184. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  41185. can be used for things like custom slider controls or dragging objects around, where
  41186. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  41187. The unbounded mode is automatically turned off when the mouse button is released, or
  41188. it can be turned off explicitly by calling this method again.
  41189. @param isEnabled whether to turn this mode on or off
  41190. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  41191. hidden; if true, it will only be hidden when it
  41192. is moved beyond the edge of the screen
  41193. */
  41194. void enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen = false);
  41195. juce_UseDebuggingNewOperator
  41196. /** @internal */
  41197. void handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, const ModifierKeys& mods);
  41198. /** @internal */
  41199. void handleWheel (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  41200. private:
  41201. friend class Desktop;
  41202. friend class ComponentPeer;
  41203. friend class MouseInputSourceInternal;
  41204. ScopedPointer<MouseInputSourceInternal> pimpl;
  41205. MouseInputSource (const MouseInputSource&);
  41206. MouseInputSource& operator= (const MouseInputSource&);
  41207. };
  41208. #endif // __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41209. /*** End of inlined file: juce_MouseInputSource.h ***/
  41210. #endif
  41211. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  41212. #endif
  41213. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  41214. #endif
  41215. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41216. /*** Start of inlined file: juce_BooleanPropertyComponent.h ***/
  41217. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41218. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41219. /**
  41220. A PropertyComponent that contains an on/off toggle button.
  41221. This type of property component can be used if you have a boolean value to
  41222. toggle on/off.
  41223. @see PropertyComponent
  41224. */
  41225. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  41226. private ButtonListener
  41227. {
  41228. protected:
  41229. /** Creates a button component.
  41230. If you use this constructor, you must override the getState() and setState()
  41231. methods.
  41232. @param propertyName the property name to be passed to the PropertyComponent
  41233. @param buttonTextWhenTrue the text shown in the button when the value is true
  41234. @param buttonTextWhenFalse the text shown in the button when the value is false
  41235. */
  41236. BooleanPropertyComponent (const String& propertyName,
  41237. const String& buttonTextWhenTrue,
  41238. const String& buttonTextWhenFalse);
  41239. public:
  41240. /** Creates a button component.
  41241. @param valueToControl a Value object that this property should refer to.
  41242. @param propertyName the property name to be passed to the PropertyComponent
  41243. @param buttonText the text shown in the ToggleButton component
  41244. */
  41245. BooleanPropertyComponent (const Value& valueToControl,
  41246. const String& propertyName,
  41247. const String& buttonText);
  41248. /** Destructor. */
  41249. ~BooleanPropertyComponent();
  41250. /** Called to change the state of the boolean value. */
  41251. virtual void setState (bool newState);
  41252. /** Must return the current value of the property. */
  41253. virtual bool getState() const;
  41254. /** @internal */
  41255. void paint (Graphics& g);
  41256. /** @internal */
  41257. void refresh();
  41258. /** @internal */
  41259. void buttonClicked (Button*);
  41260. juce_UseDebuggingNewOperator
  41261. private:
  41262. ToggleButton* button;
  41263. String onText, offText;
  41264. void createButton();
  41265. BooleanPropertyComponent (const BooleanPropertyComponent&);
  41266. BooleanPropertyComponent& operator= (const BooleanPropertyComponent&);
  41267. };
  41268. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41269. /*** End of inlined file: juce_BooleanPropertyComponent.h ***/
  41270. #endif
  41271. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41272. /*** Start of inlined file: juce_ButtonPropertyComponent.h ***/
  41273. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41274. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41275. /**
  41276. A PropertyComponent that contains a button.
  41277. This type of property component can be used if you need a button to trigger some
  41278. kind of action.
  41279. @see PropertyComponent
  41280. */
  41281. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  41282. private ButtonListener
  41283. {
  41284. public:
  41285. /** Creates a button component.
  41286. @param propertyName the property name to be passed to the PropertyComponent
  41287. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  41288. */
  41289. ButtonPropertyComponent (const String& propertyName,
  41290. bool triggerOnMouseDown);
  41291. /** Destructor. */
  41292. ~ButtonPropertyComponent();
  41293. /** Called when the user clicks the button.
  41294. */
  41295. virtual void buttonClicked() = 0;
  41296. /** Returns the string that should be displayed in the button.
  41297. If you need to change this string, call refresh() to update the component.
  41298. */
  41299. virtual const String getButtonText() const = 0;
  41300. /** @internal */
  41301. void refresh();
  41302. /** @internal */
  41303. void buttonClicked (Button*);
  41304. juce_UseDebuggingNewOperator
  41305. private:
  41306. TextButton* button;
  41307. ButtonPropertyComponent (const ButtonPropertyComponent&);
  41308. ButtonPropertyComponent& operator= (const ButtonPropertyComponent&);
  41309. };
  41310. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41311. /*** End of inlined file: juce_ButtonPropertyComponent.h ***/
  41312. #endif
  41313. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41314. /*** Start of inlined file: juce_ChoicePropertyComponent.h ***/
  41315. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41316. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41317. /**
  41318. A PropertyComponent that shows its value as a combo box.
  41319. This type of property component contains a list of options and has a
  41320. combo box to choose one.
  41321. Your subclass's constructor must add some strings to the choices StringArray
  41322. and these are shown in the list.
  41323. The getIndex() method will be called to find out which option is the currently
  41324. selected one. If you call refresh() it will call getIndex() to check whether
  41325. the value has changed, and will update the combo box if needed.
  41326. If the user selects a different item from the list, setIndex() will be
  41327. called to let your class process this.
  41328. @see PropertyComponent, PropertyPanel
  41329. */
  41330. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  41331. private ComboBoxListener
  41332. {
  41333. protected:
  41334. /** Creates the component.
  41335. Your subclass's constructor must add a list of options to the choices
  41336. member variable.
  41337. */
  41338. ChoicePropertyComponent (const String& propertyName);
  41339. public:
  41340. /** Creates the component.
  41341. @param valueToControl the value that the combo box will read and control
  41342. @param propertyName the name of the property
  41343. @param choices the list of possible values that the drop-down list will contain
  41344. @param correspondingValues a list of values corresponding to each item in the 'choices' StringArray.
  41345. These are the values that will be read and written to the
  41346. valueToControl value. This array must contain the same number of items
  41347. as the choices array
  41348. */
  41349. ChoicePropertyComponent (const Value& valueToControl,
  41350. const String& propertyName,
  41351. const StringArray& choices,
  41352. const Array <var>& correspondingValues);
  41353. /** Destructor. */
  41354. ~ChoicePropertyComponent();
  41355. /** Called when the user selects an item from the combo box.
  41356. Your subclass must use this callback to update the value that this component
  41357. represents. The index is the index of the chosen item in the choices
  41358. StringArray.
  41359. */
  41360. virtual void setIndex (int newIndex);
  41361. /** Returns the index of the item that should currently be shown.
  41362. This is the index of the item in the choices StringArray that will be
  41363. shown.
  41364. */
  41365. virtual int getIndex() const;
  41366. /** Returns the list of options. */
  41367. const StringArray& getChoices() const;
  41368. /** @internal */
  41369. void refresh();
  41370. /** @internal */
  41371. void comboBoxChanged (ComboBox*);
  41372. juce_UseDebuggingNewOperator
  41373. protected:
  41374. /** The list of options that will be shown in the combo box.
  41375. Your subclass must populate this array in its constructor. If any empty
  41376. strings are added, these will be replaced with horizontal separators (see
  41377. ComboBox::addSeparator() for more info).
  41378. */
  41379. StringArray choices;
  41380. private:
  41381. ComboBox* comboBox;
  41382. bool isCustomClass;
  41383. class RemapperValueSource;
  41384. void createComboBox();
  41385. ChoicePropertyComponent (const ChoicePropertyComponent&);
  41386. ChoicePropertyComponent& operator= (const ChoicePropertyComponent&);
  41387. };
  41388. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41389. /*** End of inlined file: juce_ChoicePropertyComponent.h ***/
  41390. #endif
  41391. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  41392. #endif
  41393. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  41394. #endif
  41395. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41396. /*** Start of inlined file: juce_SliderPropertyComponent.h ***/
  41397. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41398. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41399. /**
  41400. A PropertyComponent that shows its value as a slider.
  41401. @see PropertyComponent, Slider
  41402. */
  41403. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  41404. private SliderListener
  41405. {
  41406. protected:
  41407. /** Creates the property component.
  41408. The ranges, interval and skew factor are passed to the Slider component.
  41409. If you need to customise the slider in other ways, your constructor can
  41410. access the slider member variable and change it directly.
  41411. */
  41412. SliderPropertyComponent (const String& propertyName,
  41413. double rangeMin,
  41414. double rangeMax,
  41415. double interval,
  41416. double skewFactor = 1.0);
  41417. public:
  41418. /** Creates the property component.
  41419. The ranges, interval and skew factor are passed to the Slider component.
  41420. If you need to customise the slider in other ways, your constructor can
  41421. access the slider member variable and change it directly.
  41422. */
  41423. SliderPropertyComponent (const Value& valueToControl,
  41424. const String& propertyName,
  41425. double rangeMin,
  41426. double rangeMax,
  41427. double interval,
  41428. double skewFactor = 1.0);
  41429. /** Destructor. */
  41430. ~SliderPropertyComponent();
  41431. /** Called when the user moves the slider to change its value.
  41432. Your subclass must use this method to update whatever item this property
  41433. represents.
  41434. */
  41435. virtual void setValue (double newValue);
  41436. /** Returns the value that the slider should show. */
  41437. virtual double getValue() const;
  41438. /** @internal */
  41439. void refresh();
  41440. /** @internal */
  41441. void changeListenerCallback (void*);
  41442. /** @internal */
  41443. void sliderValueChanged (Slider*);
  41444. juce_UseDebuggingNewOperator
  41445. protected:
  41446. /** The slider component being used in this component.
  41447. Your subclass has access to this in case it needs to customise it in some way.
  41448. */
  41449. Slider* slider;
  41450. SliderPropertyComponent (const SliderPropertyComponent&);
  41451. SliderPropertyComponent& operator= (const SliderPropertyComponent&);
  41452. };
  41453. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41454. /*** End of inlined file: juce_SliderPropertyComponent.h ***/
  41455. #endif
  41456. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41457. /*** Start of inlined file: juce_TextPropertyComponent.h ***/
  41458. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41459. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41460. /**
  41461. A PropertyComponent that shows its value as editable text.
  41462. @see PropertyComponent
  41463. */
  41464. class JUCE_API TextPropertyComponent : public PropertyComponent
  41465. {
  41466. protected:
  41467. /** Creates a text property component.
  41468. The maxNumChars is used to set the length of string allowable, and isMultiLine
  41469. sets whether the text editor allows carriage returns.
  41470. @see TextEditor
  41471. */
  41472. TextPropertyComponent (const String& propertyName,
  41473. int maxNumChars,
  41474. bool isMultiLine);
  41475. public:
  41476. /** Creates a text property component.
  41477. The maxNumChars is used to set the length of string allowable, and isMultiLine
  41478. sets whether the text editor allows carriage returns.
  41479. @see TextEditor
  41480. */
  41481. TextPropertyComponent (const Value& valueToControl,
  41482. const String& propertyName,
  41483. int maxNumChars,
  41484. bool isMultiLine);
  41485. /** Destructor. */
  41486. ~TextPropertyComponent();
  41487. /** Called when the user edits the text.
  41488. Your subclass must use this callback to change the value of whatever item
  41489. this property component represents.
  41490. */
  41491. virtual void setText (const String& newText);
  41492. /** Returns the text that should be shown in the text editor.
  41493. */
  41494. virtual const String getText() const;
  41495. /** @internal */
  41496. void refresh();
  41497. /** @internal */
  41498. void textWasEdited();
  41499. juce_UseDebuggingNewOperator
  41500. private:
  41501. Label* textEditor;
  41502. void createEditor (int maxNumChars, bool isMultiLine);
  41503. TextPropertyComponent (const TextPropertyComponent&);
  41504. TextPropertyComponent& operator= (const TextPropertyComponent&);
  41505. };
  41506. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41507. /*** End of inlined file: juce_TextPropertyComponent.h ***/
  41508. #endif
  41509. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41510. /*** Start of inlined file: juce_ActiveXControlComponent.h ***/
  41511. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41512. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41513. #if JUCE_WINDOWS || DOXYGEN
  41514. /**
  41515. A Windows-specific class that can create and embed an ActiveX control inside
  41516. itself.
  41517. To use it, create one of these, put it in place and make sure it's visible in a
  41518. window, then use createControl() to instantiate an ActiveX control. The control
  41519. will then be moved and resized to follow the movements of this component.
  41520. Of course, since the control is a heavyweight window, it'll obliterate any
  41521. juce components that may overlap this component, but that's life.
  41522. */
  41523. class JUCE_API ActiveXControlComponent : public Component
  41524. {
  41525. public:
  41526. /** Create an initially-empty container. */
  41527. ActiveXControlComponent();
  41528. /** Destructor. */
  41529. ~ActiveXControlComponent();
  41530. /** Tries to create an ActiveX control and embed it in this peer.
  41531. The peer controlIID is a pointer to an IID structure - it's treated
  41532. as a void* because when including the Juce headers, you might not always
  41533. have included windows.h first, in which case IID wouldn't be defined.
  41534. e.g. @code
  41535. const IID myIID = __uuidof (QTControl);
  41536. myControlComp->createControl (&myIID);
  41537. @endcode
  41538. */
  41539. bool createControl (const void* controlIID);
  41540. /** Deletes the ActiveX control, if one has been created.
  41541. */
  41542. void deleteControl();
  41543. /** Returns true if a control is currently in use. */
  41544. bool isControlOpen() const throw() { return control != 0; }
  41545. /** Does a QueryInterface call on the embedded control object.
  41546. This allows you to cast the control to whatever type of COM object you need.
  41547. The iid parameter is a pointer to an IID structure - it's treated
  41548. as a void* because when including the Juce headers, you might not always
  41549. have included windows.h first, in which case IID wouldn't be defined, but
  41550. you should just pass a pointer to an IID.
  41551. e.g. @code
  41552. const IID iid = __uuidof (IOleWindow);
  41553. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  41554. if (oleWindow != 0)
  41555. {
  41556. HWND hwnd;
  41557. oleWindow->GetWindow (&hwnd);
  41558. ...
  41559. oleWindow->Release();
  41560. }
  41561. @endcode
  41562. */
  41563. void* queryInterface (const void* iid) const;
  41564. /** Set this to false to stop mouse events being allowed through to the control.
  41565. */
  41566. void setMouseEventsAllowed (bool eventsCanReachControl);
  41567. /** Returns true if mouse events are allowed to get through to the control.
  41568. */
  41569. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  41570. /** @internal */
  41571. void paint (Graphics& g);
  41572. /** @internal */
  41573. void* originalWndProc;
  41574. juce_UseDebuggingNewOperator
  41575. private:
  41576. class Pimpl;
  41577. friend class Pimpl;
  41578. friend class ScopedPointer <Pimpl>;
  41579. ScopedPointer <Pimpl> control;
  41580. bool mouseEventsAllowed;
  41581. void setControlBounds (const Rectangle<int>& bounds) const;
  41582. void setControlVisible (bool b) const;
  41583. ActiveXControlComponent (const ActiveXControlComponent&);
  41584. ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  41585. };
  41586. #endif
  41587. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41588. /*** End of inlined file: juce_ActiveXControlComponent.h ***/
  41589. #endif
  41590. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41591. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  41592. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41593. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41594. /**
  41595. A component containing controls to let the user change the audio settings of
  41596. an AudioDeviceManager object.
  41597. Very easy to use - just create one of these and show it to the user.
  41598. @see AudioDeviceManager
  41599. */
  41600. class JUCE_API AudioDeviceSelectorComponent : public Component,
  41601. public ComboBoxListener,
  41602. public ButtonListener,
  41603. public ChangeListener
  41604. {
  41605. public:
  41606. /** Creates the component.
  41607. If your app needs only output channels, you might ask for a maximum of 0 input
  41608. channels, and the component won't display any options for choosing the input
  41609. channels. And likewise if you're doing an input-only app.
  41610. @param deviceManager the device manager that this component should control
  41611. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  41612. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  41613. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  41614. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  41615. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  41616. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  41617. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  41618. treated as a set of separate mono channels.
  41619. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  41620. are shown, with an "advanced" button that shows the rest of them
  41621. */
  41622. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  41623. const int minAudioInputChannels,
  41624. const int maxAudioInputChannels,
  41625. const int minAudioOutputChannels,
  41626. const int maxAudioOutputChannels,
  41627. const bool showMidiInputOptions,
  41628. const bool showMidiOutputSelector,
  41629. const bool showChannelsAsStereoPairs,
  41630. const bool hideAdvancedOptionsWithButton);
  41631. /** Destructor */
  41632. ~AudioDeviceSelectorComponent();
  41633. /** @internal */
  41634. void resized();
  41635. /** @internal */
  41636. void comboBoxChanged (ComboBox*);
  41637. /** @internal */
  41638. void buttonClicked (Button*);
  41639. /** @internal */
  41640. void changeListenerCallback (void*);
  41641. /** @internal */
  41642. void childBoundsChanged (Component*);
  41643. juce_UseDebuggingNewOperator
  41644. private:
  41645. AudioDeviceManager& deviceManager;
  41646. ComboBox* deviceTypeDropDown;
  41647. Label* deviceTypeDropDownLabel;
  41648. Component* audioDeviceSettingsComp;
  41649. String audioDeviceSettingsCompType;
  41650. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  41651. const bool showChannelsAsStereoPairs;
  41652. const bool hideAdvancedOptionsWithButton;
  41653. class MidiInputSelectorComponentListBox;
  41654. MidiInputSelectorComponentListBox* midiInputsList;
  41655. Label* midiInputsLabel;
  41656. ComboBox* midiOutputSelector;
  41657. Label* midiOutputLabel;
  41658. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  41659. AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  41660. };
  41661. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41662. /*** End of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  41663. #endif
  41664. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  41665. /*** Start of inlined file: juce_BubbleComponent.h ***/
  41666. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  41667. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  41668. /**
  41669. A component for showing a message or other graphics inside a speech-bubble-shaped
  41670. outline, pointing at a location on the screen.
  41671. This is a base class that just draws and positions the bubble shape, but leaves
  41672. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  41673. that draws a text message.
  41674. To use it, create your subclass, then either add it to a parent component or
  41675. put it on the desktop with addToDesktop (0), use setPosition() to
  41676. resize and position it, then make it visible.
  41677. @see BubbleMessageComponent
  41678. */
  41679. class JUCE_API BubbleComponent : public Component
  41680. {
  41681. protected:
  41682. /** Creates a BubbleComponent.
  41683. Your subclass will need to implement the getContentSize() and paintContent()
  41684. methods to draw the bubble's contents.
  41685. */
  41686. BubbleComponent();
  41687. public:
  41688. /** Destructor. */
  41689. ~BubbleComponent();
  41690. /** A list of permitted placements for the bubble, relative to the co-ordinates
  41691. at which it should be pointing.
  41692. @see setAllowedPlacement
  41693. */
  41694. enum BubblePlacement
  41695. {
  41696. above = 1,
  41697. below = 2,
  41698. left = 4,
  41699. right = 8
  41700. };
  41701. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  41702. point at which it's pointing.
  41703. By default when setPosition() is called, the bubble will place itself either
  41704. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  41705. the values in BubblePlacement to restrict this choice.
  41706. E.g. if you only want your bubble to appear above or below the target area,
  41707. use setAllowedPlacement (above | below);
  41708. @see BubblePlacement
  41709. */
  41710. void setAllowedPlacement (int newPlacement);
  41711. /** Moves and resizes the bubble to point at a given component.
  41712. This will resize the bubble to fit its content, then find a position for it
  41713. so that it's next to, but doesn't overlap the given component.
  41714. It'll put itself either above, below, or to the side of the component depending
  41715. on where there's the most space, honouring any restrictions that were set
  41716. with setAllowedPlacement().
  41717. */
  41718. void setPosition (Component* componentToPointTo);
  41719. /** Moves and resizes the bubble to point at a given point.
  41720. This will resize the bubble to fit its content, then position it
  41721. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  41722. are relative to either the bubble component's parent component if it has one, or
  41723. they are screen co-ordinates if not.
  41724. It'll put itself either above, below, or to the side of this point, depending
  41725. on where there's the most space, honouring any restrictions that were set
  41726. with setAllowedPlacement().
  41727. */
  41728. void setPosition (int arrowTipX,
  41729. int arrowTipY);
  41730. /** Moves and resizes the bubble to point at a given rectangle.
  41731. This will resize the bubble to fit its content, then find a position for it
  41732. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  41733. co-ordinates are relative to either the bubble component's parent component
  41734. if it has one, or they are screen co-ordinates if not.
  41735. It'll put itself either above, below, or to the side of the component depending
  41736. on where there's the most space, honouring any restrictions that were set
  41737. with setAllowedPlacement().
  41738. */
  41739. void setPosition (const Rectangle<int>& rectangleToPointTo);
  41740. protected:
  41741. /** Subclasses should override this to return the size of the content they
  41742. want to draw inside the bubble.
  41743. */
  41744. virtual void getContentSize (int& width, int& height) = 0;
  41745. /** Subclasses should override this to draw their bubble's contents.
  41746. The graphics object's clip region and the dimensions passed in here are
  41747. set up to paint just the rectangle inside the bubble.
  41748. */
  41749. virtual void paintContent (Graphics& g, int width, int height) = 0;
  41750. public:
  41751. /** @internal */
  41752. void paint (Graphics& g);
  41753. juce_UseDebuggingNewOperator
  41754. private:
  41755. Rectangle<int> content;
  41756. int side, allowablePlacements;
  41757. float arrowTipX, arrowTipY;
  41758. DropShadowEffect shadow;
  41759. BubbleComponent (const BubbleComponent&);
  41760. BubbleComponent& operator= (const BubbleComponent&);
  41761. };
  41762. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  41763. /*** End of inlined file: juce_BubbleComponent.h ***/
  41764. #endif
  41765. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  41766. /*** Start of inlined file: juce_BubbleMessageComponent.h ***/
  41767. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  41768. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  41769. /**
  41770. A speech-bubble component that displays a short message.
  41771. This can be used to show a message with the tail of the speech bubble
  41772. pointing to a particular component or location on the screen.
  41773. @see BubbleComponent
  41774. */
  41775. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  41776. private Timer
  41777. {
  41778. public:
  41779. /** Creates a bubble component.
  41780. After creating one a BubbleComponent, do the following:
  41781. - add it to an appropriate parent component, or put it on the
  41782. desktop with Component::addToDesktop (0).
  41783. - use the showAt() method to show a message.
  41784. - it will make itself invisible after it times-out (and can optionally
  41785. also delete itself), or you can reuse it somewhere else by calling
  41786. showAt() again.
  41787. */
  41788. BubbleMessageComponent (int fadeOutLengthMs = 150);
  41789. /** Destructor. */
  41790. ~BubbleMessageComponent();
  41791. /** Shows a message bubble at a particular position.
  41792. This shows the bubble with its stem pointing to the given location
  41793. (co-ordinates being relative to its parent component).
  41794. For details about exactly how it decides where to position itself, see
  41795. BubbleComponent::updatePosition().
  41796. @param x the x co-ordinate of end of the bubble's tail
  41797. @param y the y co-ordinate of end of the bubble's tail
  41798. @param message the text to display
  41799. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  41800. from its parent compnent. If this is 0 or less, it
  41801. will stay there until manually removed.
  41802. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  41803. mouse button is pressed (anywhere on the screen)
  41804. @param deleteSelfAfterUse if true, then the component will delete itself after
  41805. it becomes invisible
  41806. */
  41807. void showAt (int x, int y,
  41808. const String& message,
  41809. int numMillisecondsBeforeRemoving,
  41810. bool removeWhenMouseClicked = true,
  41811. bool deleteSelfAfterUse = false);
  41812. /** Shows a message bubble next to a particular component.
  41813. This shows the bubble with its stem pointing at the given component.
  41814. For details about exactly how it decides where to position itself, see
  41815. BubbleComponent::updatePosition().
  41816. @param component the component that you want to point at
  41817. @param message the text to display
  41818. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  41819. from its parent compnent. If this is 0 or less, it
  41820. will stay there until manually removed.
  41821. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  41822. mouse button is pressed (anywhere on the screen)
  41823. @param deleteSelfAfterUse if true, then the component will delete itself after
  41824. it becomes invisible
  41825. */
  41826. void showAt (Component* component,
  41827. const String& message,
  41828. int numMillisecondsBeforeRemoving,
  41829. bool removeWhenMouseClicked = true,
  41830. bool deleteSelfAfterUse = false);
  41831. /** @internal */
  41832. void getContentSize (int& w, int& h);
  41833. /** @internal */
  41834. void paintContent (Graphics& g, int w, int h);
  41835. /** @internal */
  41836. void timerCallback();
  41837. juce_UseDebuggingNewOperator
  41838. private:
  41839. int fadeOutLength, mouseClickCounter;
  41840. TextLayout textLayout;
  41841. int64 expiryTime;
  41842. bool deleteAfterUse;
  41843. void init (int numMillisecondsBeforeRemoving,
  41844. bool removeWhenMouseClicked,
  41845. bool deleteSelfAfterUse);
  41846. BubbleMessageComponent (const BubbleMessageComponent&);
  41847. BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  41848. };
  41849. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  41850. /*** End of inlined file: juce_BubbleMessageComponent.h ***/
  41851. #endif
  41852. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  41853. /*** Start of inlined file: juce_ColourSelector.h ***/
  41854. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  41855. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  41856. /**
  41857. A component that lets the user choose a colour.
  41858. This shows RGB sliders and a colourspace that the user can pick colours from.
  41859. This class is also a ChangeBroadcaster, so listeners can register to be told
  41860. when the colour changes.
  41861. */
  41862. class JUCE_API ColourSelector : public Component,
  41863. public ChangeBroadcaster,
  41864. protected SliderListener
  41865. {
  41866. public:
  41867. /** Options for the type of selector to show. These are passed into the constructor. */
  41868. enum ColourSelectorOptions
  41869. {
  41870. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  41871. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  41872. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  41873. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  41874. };
  41875. /** Creates a ColourSelector object.
  41876. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  41877. which of the selector's features should be visible.
  41878. The edgeGap value specifies the amount of space to leave around the edge.
  41879. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  41880. colourspace and hue selector components.
  41881. */
  41882. ColourSelector (int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  41883. int edgeGap = 4,
  41884. int gapAroundColourSpaceComponent = 7);
  41885. /** Destructor. */
  41886. ~ColourSelector();
  41887. /** Returns the colour that the user has currently selected.
  41888. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  41889. register to be told when the colour changes.
  41890. @see setCurrentColour
  41891. */
  41892. const Colour getCurrentColour() const;
  41893. /** Changes the colour that is currently being shown.
  41894. */
  41895. void setCurrentColour (const Colour& newColour);
  41896. /** Tells the selector how many preset colour swatches you want to have on the component.
  41897. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  41898. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  41899. their values.
  41900. */
  41901. virtual int getNumSwatches() const;
  41902. /** Called by the selector to find out the colour of one of the swatches.
  41903. Your subclass should return the colour of the swatch with the given index.
  41904. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  41905. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  41906. their values.
  41907. */
  41908. virtual const Colour getSwatchColour (int index) const;
  41909. /** Called by the selector when the user puts a new colour into one of the swatches.
  41910. Your subclass should change the colour of the swatch with the given index.
  41911. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  41912. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  41913. their values.
  41914. */
  41915. virtual void setSwatchColour (int index, const Colour& newColour) const;
  41916. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  41917. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41918. methods.
  41919. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41920. */
  41921. enum ColourIds
  41922. {
  41923. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  41924. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  41925. };
  41926. juce_UseDebuggingNewOperator
  41927. private:
  41928. class ColourSpaceView;
  41929. class HueSelectorComp;
  41930. class SwatchComponent;
  41931. friend class ColourSpaceView;
  41932. friend class HueSelectorComp;
  41933. Colour colour;
  41934. float h, s, v;
  41935. Slider* sliders[4];
  41936. ColourSpaceView* colourSpace;
  41937. HueSelectorComp* hueSelector;
  41938. OwnedArray <SwatchComponent> swatchComponents;
  41939. const int flags;
  41940. int topSpace, edgeGap;
  41941. void setHue (float newH);
  41942. void setSV (float newS, float newV);
  41943. void updateHSV();
  41944. void update();
  41945. void sliderValueChanged (Slider*);
  41946. void paint (Graphics& g);
  41947. void resized();
  41948. ColourSelector (const ColourSelector&);
  41949. ColourSelector& operator= (const ColourSelector&);
  41950. // this constructor is here temporarily to prevent old code compiling, because the parameters
  41951. // have changed - if you get an error here, update your code to use the new constructor instead..
  41952. // (xxx - note to self: remember to remove this at some point in the future)
  41953. ColourSelector (bool);
  41954. };
  41955. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  41956. /*** End of inlined file: juce_ColourSelector.h ***/
  41957. #endif
  41958. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  41959. #endif
  41960. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  41961. /*** Start of inlined file: juce_MagnifierComponent.h ***/
  41962. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  41963. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  41964. /**
  41965. A component that contains another component, and can magnify or shrink it.
  41966. This component will continually update its size so that it fits the zoomed
  41967. version of the content component that you put inside it, so don't try to
  41968. change the size of this component directly - instead change that of the
  41969. content component.
  41970. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  41971. to remap mouse events correctly. This means that the content component won't
  41972. appear to be a direct child of this component, and instead will think its
  41973. on the desktop.
  41974. */
  41975. class JUCE_API MagnifierComponent : public Component
  41976. {
  41977. public:
  41978. /** Creates a MagnifierComponent.
  41979. This component will continually update its size so that it fits the zoomed
  41980. version of the content component that you put inside it, so don't try to
  41981. change the size of this component directly - instead change that of the
  41982. content component.
  41983. @param contentComponent the component to add as the magnified one
  41984. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  41985. be deleted when this component is deleted. If false,
  41986. it's the caller's responsibility to delete it later.
  41987. */
  41988. MagnifierComponent (Component* contentComponent,
  41989. bool deleteContentCompWhenNoLongerNeeded);
  41990. /** Destructor. */
  41991. ~MagnifierComponent();
  41992. /** Returns the current content component. */
  41993. Component* getContentComponent() const { return content; }
  41994. /** Changes the zoom level.
  41995. The scale factor must be greater than zero. Values less than 1 will shrink the
  41996. image; values greater than 1 will multiply its size by this amount.
  41997. When this is called, this component will change its size to fit the full extent
  41998. of the newly zoomed content.
  41999. */
  42000. void setScaleFactor (double newScaleFactor);
  42001. /** Returns the current zoom factor. */
  42002. double getScaleFactor() const { return scaleFactor; }
  42003. /** Changes the quality setting used to rescale the graphics.
  42004. */
  42005. void setResamplingQuality (Graphics::ResamplingQuality newQuality);
  42006. juce_UseDebuggingNewOperator
  42007. /** @internal */
  42008. void childBoundsChanged (Component*);
  42009. private:
  42010. Component* content;
  42011. Component* holderComp;
  42012. double scaleFactor;
  42013. ComponentPeer* peer;
  42014. bool deleteContent;
  42015. Graphics::ResamplingQuality quality;
  42016. MouseInputSource mouseSource;
  42017. void paint (Graphics& g);
  42018. void mouseDown (const MouseEvent& e);
  42019. void mouseUp (const MouseEvent& e);
  42020. void mouseDrag (const MouseEvent& e);
  42021. void mouseMove (const MouseEvent& e);
  42022. void mouseEnter (const MouseEvent& e);
  42023. void mouseExit (const MouseEvent& e);
  42024. void mouseWheelMove (const MouseEvent& e, float, float);
  42025. void passOnMouseEventToPeer (const MouseEvent& e);
  42026. int scaleInt (int n) const;
  42027. MagnifierComponent (const MagnifierComponent&);
  42028. MagnifierComponent& operator= (const MagnifierComponent&);
  42029. };
  42030. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  42031. /*** End of inlined file: juce_MagnifierComponent.h ***/
  42032. #endif
  42033. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42034. /*** Start of inlined file: juce_MidiKeyboardComponent.h ***/
  42035. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42036. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42037. /**
  42038. A component that displays a piano keyboard, whose notes can be clicked on.
  42039. This component will mimic a physical midi keyboard, showing the current state of
  42040. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  42041. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  42042. Another feature is that the computer keyboard can also be used to play notes. By
  42043. default it maps the top two rows of a standard querty keyboard to the notes, but
  42044. these can be remapped if needed. It will only respond to keypresses when it has
  42045. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  42046. The component is also a ChangeBroadcaster, so if you want to be informed when the
  42047. keyboard is scrolled, you can register a ChangeListener for callbacks.
  42048. @see MidiKeyboardState
  42049. */
  42050. class JUCE_API MidiKeyboardComponent : public Component,
  42051. public MidiKeyboardStateListener,
  42052. public ChangeBroadcaster,
  42053. private Timer,
  42054. private AsyncUpdater
  42055. {
  42056. public:
  42057. /** The direction of the keyboard.
  42058. @see setOrientation
  42059. */
  42060. enum Orientation
  42061. {
  42062. horizontalKeyboard,
  42063. verticalKeyboardFacingLeft,
  42064. verticalKeyboardFacingRight,
  42065. };
  42066. /** Creates a MidiKeyboardComponent.
  42067. @param state the midi keyboard model that this component will represent
  42068. @param orientation whether the keyboard is horizonal or vertical
  42069. */
  42070. MidiKeyboardComponent (MidiKeyboardState& state,
  42071. Orientation orientation);
  42072. /** Destructor. */
  42073. ~MidiKeyboardComponent();
  42074. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  42075. on the component.
  42076. Values are 0 to 1.0, where 1.0 is the heaviest.
  42077. @see setMidiChannel
  42078. */
  42079. void setVelocity (float velocity, bool useMousePositionForVelocity);
  42080. /** Changes the midi channel number that will be used for events triggered by clicking
  42081. on the component.
  42082. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  42083. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  42084. Although this is the channel used for outgoing events, the component can display
  42085. incoming events from more than one channel - see setMidiChannelsToDisplay()
  42086. @see setVelocity
  42087. */
  42088. void setMidiChannel (int midiChannelNumber);
  42089. /** Returns the midi channel that the keyboard is using for midi messages.
  42090. @see setMidiChannel
  42091. */
  42092. int getMidiChannel() const throw() { return midiChannel; }
  42093. /** Sets a mask to indicate which incoming midi channels should be represented by
  42094. key movements.
  42095. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  42096. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  42097. in this mask, the on-screen keys will also go down.
  42098. By default, this mask is set to 0xffff (all channels displayed).
  42099. @see setMidiChannel
  42100. */
  42101. void setMidiChannelsToDisplay (int midiChannelMask);
  42102. /** Returns the current set of midi channels represented by the component.
  42103. This is the value that was set with setMidiChannelsToDisplay().
  42104. */
  42105. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  42106. /** Changes the width used to draw the white keys. */
  42107. void setKeyWidth (float widthInPixels);
  42108. /** Returns the width that was set by setKeyWidth(). */
  42109. float getKeyWidth() const throw() { return keyWidth; }
  42110. /** Changes the keyboard's current direction. */
  42111. void setOrientation (Orientation newOrientation);
  42112. /** Returns the keyboard's current direction. */
  42113. const Orientation getOrientation() const throw() { return orientation; }
  42114. /** Sets the range of midi notes that the keyboard will be limited to.
  42115. By default the range is 0 to 127 (inclusive), but you can limit this if you
  42116. only want a restricted set of the keys to be shown.
  42117. Note that the values here are inclusive and must be between 0 and 127.
  42118. */
  42119. void setAvailableRange (int lowestNote,
  42120. int highestNote);
  42121. /** Returns the first note in the available range.
  42122. @see setAvailableRange
  42123. */
  42124. int getRangeStart() const throw() { return rangeStart; }
  42125. /** Returns the last note in the available range.
  42126. @see setAvailableRange
  42127. */
  42128. int getRangeEnd() const throw() { return rangeEnd; }
  42129. /** If the keyboard extends beyond the size of the component, this will scroll
  42130. it to show the given key at the start.
  42131. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  42132. base class to send a callback to any ChangeListeners that have been registered.
  42133. */
  42134. void setLowestVisibleKey (int noteNumber);
  42135. /** Returns the number of the first key shown in the component.
  42136. @see setLowestVisibleKey
  42137. */
  42138. int getLowestVisibleKey() const throw() { return firstKey; }
  42139. /** Returns the length of the black notes.
  42140. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  42141. */
  42142. int getBlackNoteLength() const throw() { return blackNoteLength; }
  42143. /** If set to true, then scroll buttons will appear at either end of the keyboard
  42144. if there are too many notes to fit them all in the component at once.
  42145. */
  42146. void setScrollButtonsVisible (bool canScroll);
  42147. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  42148. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42149. methods.
  42150. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42151. */
  42152. enum ColourIds
  42153. {
  42154. whiteNoteColourId = 0x1005000,
  42155. blackNoteColourId = 0x1005001,
  42156. keySeparatorLineColourId = 0x1005002,
  42157. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  42158. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  42159. textLabelColourId = 0x1005005,
  42160. upDownButtonBackgroundColourId = 0x1005006,
  42161. upDownButtonArrowColourId = 0x1005007
  42162. };
  42163. /** Returns the position within the component of the left-hand edge of a key.
  42164. Depending on the keyboard's orientation, this may be a horizontal or vertical
  42165. distance, in either direction.
  42166. */
  42167. int getKeyStartPosition (const int midiNoteNumber) const;
  42168. /** Deletes all key-mappings.
  42169. @see setKeyPressForNote
  42170. */
  42171. void clearKeyMappings();
  42172. /** Maps a key-press to a given note.
  42173. @param key the key that should trigger the note
  42174. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  42175. be. The actual midi note that gets played will be
  42176. this value + (12 * the current base octave). To change
  42177. the base octave, see setKeyPressBaseOctave()
  42178. */
  42179. void setKeyPressForNote (const KeyPress& key,
  42180. int midiNoteOffsetFromC);
  42181. /** Removes any key-mappings for a given note.
  42182. For a description of what the note number means, see setKeyPressForNote().
  42183. */
  42184. void removeKeyPressForNote (int midiNoteOffsetFromC);
  42185. /** Changes the base note above which key-press-triggered notes are played.
  42186. The set of key-mappings that trigger notes can be moved up and down to cover
  42187. the entire scale using this method.
  42188. The value passed in is an octave number between 0 and 10 (inclusive), and
  42189. indicates which C is the base note to which the key-mapped notes are
  42190. relative.
  42191. */
  42192. void setKeyPressBaseOctave (int newOctaveNumber);
  42193. /** This sets the octave number which is shown as the octave number for middle C.
  42194. This affects only the default implementation of getWhiteNoteText(), which
  42195. passes this octave number to MidiMessage::getMidiNoteName() in order to
  42196. get the note text. See MidiMessage::getMidiNoteName() for more info about
  42197. the parameter.
  42198. By default this value is set to 3.
  42199. @see getOctaveForMiddleC
  42200. */
  42201. void setOctaveForMiddleC (int octaveNumForMiddleC);
  42202. /** This returns the value set by setOctaveForMiddleC().
  42203. @see setOctaveForMiddleC
  42204. */
  42205. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  42206. /** @internal */
  42207. void paint (Graphics& g);
  42208. /** @internal */
  42209. void resized();
  42210. /** @internal */
  42211. void mouseMove (const MouseEvent& e);
  42212. /** @internal */
  42213. void mouseDrag (const MouseEvent& e);
  42214. /** @internal */
  42215. void mouseDown (const MouseEvent& e);
  42216. /** @internal */
  42217. void mouseUp (const MouseEvent& e);
  42218. /** @internal */
  42219. void mouseEnter (const MouseEvent& e);
  42220. /** @internal */
  42221. void mouseExit (const MouseEvent& e);
  42222. /** @internal */
  42223. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  42224. /** @internal */
  42225. void timerCallback();
  42226. /** @internal */
  42227. bool keyStateChanged (bool isKeyDown);
  42228. /** @internal */
  42229. void focusLost (FocusChangeType cause);
  42230. /** @internal */
  42231. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  42232. /** @internal */
  42233. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  42234. /** @internal */
  42235. void handleAsyncUpdate();
  42236. /** @internal */
  42237. void colourChanged();
  42238. juce_UseDebuggingNewOperator
  42239. protected:
  42240. friend class MidiKeyboardUpDownButton;
  42241. /** Draws a white note in the given rectangle.
  42242. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  42243. currently pressed down.
  42244. When doing this, be sure to note the keyboard's orientation.
  42245. */
  42246. virtual void drawWhiteNote (int midiNoteNumber,
  42247. Graphics& g,
  42248. int x, int y, int w, int h,
  42249. bool isDown, bool isOver,
  42250. const Colour& lineColour,
  42251. const Colour& textColour);
  42252. /** Draws a black note in the given rectangle.
  42253. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  42254. currently pressed down.
  42255. When doing this, be sure to note the keyboard's orientation.
  42256. */
  42257. virtual void drawBlackNote (int midiNoteNumber,
  42258. Graphics& g,
  42259. int x, int y, int w, int h,
  42260. bool isDown, bool isOver,
  42261. const Colour& noteFillColour);
  42262. /** Allows text to be drawn on the white notes.
  42263. By default this is used to label the C in each octave, but could be used for other things.
  42264. @see setOctaveForMiddleC
  42265. */
  42266. virtual const String getWhiteNoteText (const int midiNoteNumber);
  42267. /** Draws the up and down buttons that change the base note. */
  42268. virtual void drawUpDownButton (Graphics& g, int w, int h,
  42269. const bool isMouseOver,
  42270. const bool isButtonPressed,
  42271. const bool movesOctavesUp);
  42272. /** Callback when the mouse is clicked on a key.
  42273. You could use this to do things like handle right-clicks on keys, etc.
  42274. Return true if you want the click to trigger the note, or false if you
  42275. want to handle it yourself and not have the note played.
  42276. @see mouseDraggedToKey
  42277. */
  42278. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  42279. /** Callback when the mouse is dragged from one key onto another.
  42280. @see mouseDownOnKey
  42281. */
  42282. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  42283. /** Calculates the positon of a given midi-note.
  42284. This can be overridden to create layouts with custom key-widths.
  42285. @param midiNoteNumber the note to find
  42286. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  42287. @param x the x position of the left-hand edge of the key (this method
  42288. always works in terms of a horizontal keyboard)
  42289. @param w the width of the key
  42290. */
  42291. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  42292. int& x, int& w) const;
  42293. private:
  42294. MidiKeyboardState& state;
  42295. int xOffset, blackNoteLength;
  42296. float keyWidth;
  42297. Orientation orientation;
  42298. int midiChannel, midiInChannelMask;
  42299. float velocity;
  42300. int noteUnderMouse, mouseDownNote;
  42301. BigInteger keysPressed, keysCurrentlyDrawnDown;
  42302. int rangeStart, rangeEnd, firstKey;
  42303. bool canScroll, mouseDragging, useMousePositionForVelocity;
  42304. Button* scrollDown;
  42305. Button* scrollUp;
  42306. Array <KeyPress> keyPresses;
  42307. Array <int> keyPressNotes;
  42308. int keyMappingOctave;
  42309. int octaveNumForMiddleC;
  42310. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  42311. int xyToNote (const Point<int>& pos, float& mousePositionVelocity);
  42312. int remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const;
  42313. void resetAnyKeysInUse();
  42314. void updateNoteUnderMouse (const Point<int>& pos);
  42315. void repaintNote (const int midiNoteNumber);
  42316. MidiKeyboardComponent (const MidiKeyboardComponent&);
  42317. MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  42318. };
  42319. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42320. /*** End of inlined file: juce_MidiKeyboardComponent.h ***/
  42321. #endif
  42322. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42323. /*** Start of inlined file: juce_NSViewComponent.h ***/
  42324. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42325. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42326. #if ! DOXYGEN
  42327. class NSViewComponentInternal;
  42328. #endif
  42329. #if JUCE_MAC || DOXYGEN
  42330. /**
  42331. A Mac-specific class that can create and embed an NSView inside itself.
  42332. To use it, create one of these, put it in place and make sure it's visible in a
  42333. window, then use setView() to assign an NSView to it. The view will then be
  42334. moved and resized to follow the movements of this component.
  42335. Of course, since the view is a native object, it'll obliterate any
  42336. juce components that may overlap this component, but that's life.
  42337. */
  42338. class JUCE_API NSViewComponent : public Component
  42339. {
  42340. public:
  42341. /** Create an initially-empty container. */
  42342. NSViewComponent();
  42343. /** Destructor. */
  42344. ~NSViewComponent();
  42345. /** Assigns an NSView to this peer.
  42346. The view will be retained and released by this component for as long as
  42347. it is needed. To remove the current view, just call setView (0).
  42348. Note: a void* is used here to avoid including the cocoa headers as
  42349. part of the juce.h, but the method expects an NSView*.
  42350. */
  42351. void setView (void* nsView);
  42352. /** Returns the current NSView.
  42353. Note: a void* is returned here to avoid including the cocoa headers as
  42354. a requirement of juce.h, so you should just cast the object to an NSView*.
  42355. */
  42356. void* getView() const;
  42357. /** @internal */
  42358. void paint (Graphics& g);
  42359. juce_UseDebuggingNewOperator
  42360. private:
  42361. friend class NSViewComponentInternal;
  42362. ScopedPointer <NSViewComponentInternal> info;
  42363. NSViewComponent (const NSViewComponent&);
  42364. NSViewComponent& operator= (const NSViewComponent&);
  42365. };
  42366. #endif
  42367. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42368. /*** End of inlined file: juce_NSViewComponent.h ***/
  42369. #endif
  42370. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42371. /*** Start of inlined file: juce_OpenGLComponent.h ***/
  42372. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42373. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42374. // this is used to disable OpenGL, and is defined in juce_Config.h
  42375. #if JUCE_OPENGL || DOXYGEN
  42376. /**
  42377. Represents the various properties of an OpenGL bitmap format.
  42378. @see OpenGLComponent::setPixelFormat
  42379. */
  42380. class JUCE_API OpenGLPixelFormat
  42381. {
  42382. public:
  42383. /** Creates an OpenGLPixelFormat.
  42384. The default constructor just initialises the object as a simple 8-bit
  42385. RGBA format.
  42386. */
  42387. OpenGLPixelFormat (int bitsPerRGBComponent = 8,
  42388. int alphaBits = 8,
  42389. int depthBufferBits = 16,
  42390. int stencilBufferBits = 0);
  42391. OpenGLPixelFormat (const OpenGLPixelFormat&);
  42392. OpenGLPixelFormat& operator= (const OpenGLPixelFormat&);
  42393. bool operator== (const OpenGLPixelFormat&) const;
  42394. int redBits; /**< The number of bits per pixel to use for the red channel. */
  42395. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  42396. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  42397. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  42398. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  42399. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  42400. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  42401. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  42402. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  42403. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  42404. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  42405. /** Returns a list of all the pixel formats that can be used in this system.
  42406. A reference component is needed in case there are multiple screens with different
  42407. capabilities - in which case, the one that the component is on will be used.
  42408. */
  42409. static void getAvailablePixelFormats (Component* component,
  42410. OwnedArray <OpenGLPixelFormat>& results);
  42411. juce_UseDebuggingNewOperator
  42412. };
  42413. /**
  42414. A base class for types of OpenGL context.
  42415. An OpenGLComponent will supply its own context for drawing in its window.
  42416. */
  42417. class JUCE_API OpenGLContext
  42418. {
  42419. public:
  42420. /** Destructor. */
  42421. virtual ~OpenGLContext();
  42422. /** Makes this context the currently active one. */
  42423. virtual bool makeActive() const throw() = 0;
  42424. /** If this context is currently active, it is disactivated. */
  42425. virtual bool makeInactive() const throw() = 0;
  42426. /** Returns true if this context is currently active. */
  42427. virtual bool isActive() const throw() = 0;
  42428. /** Swaps the buffers (if the context can do this). */
  42429. virtual void swapBuffers() = 0;
  42430. /** Sets whether the context checks the vertical sync before swapping.
  42431. The value is the number of frames to allow between buffer-swapping. This is
  42432. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  42433. and greater numbers indicate that it should swap less often.
  42434. Returns true if it sets the value successfully.
  42435. */
  42436. virtual bool setSwapInterval (int numFramesPerSwap) = 0;
  42437. /** Returns the current swap-sync interval.
  42438. See setSwapInterval() for info about the value returned.
  42439. */
  42440. virtual int getSwapInterval() const = 0;
  42441. /** Returns the pixel format being used by this context. */
  42442. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  42443. /** For windowed contexts, this moves the context within the bounds of
  42444. its parent window.
  42445. */
  42446. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  42447. /** For windowed contexts, this triggers a repaint of the window.
  42448. (Not relevent on all platforms).
  42449. */
  42450. virtual void repaint() = 0;
  42451. /** Returns an OS-dependent handle to the raw GL context.
  42452. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  42453. a GLXContext.
  42454. */
  42455. virtual void* getRawContext() const throw() = 0;
  42456. /** Returns the context that's currently in active use by the calling thread.
  42457. Returns 0 if there isn't an active context.
  42458. */
  42459. static OpenGLContext* getCurrentContext();
  42460. juce_UseDebuggingNewOperator
  42461. protected:
  42462. OpenGLContext() throw();
  42463. };
  42464. /**
  42465. A component that contains an OpenGL canvas.
  42466. Override this, add it to whatever component you want to, and use the renderOpenGL()
  42467. method to draw its contents.
  42468. */
  42469. class JUCE_API OpenGLComponent : public Component
  42470. {
  42471. public:
  42472. /** Used to select the type of openGL API to use, if more than one choice is available
  42473. on a particular platform.
  42474. */
  42475. enum OpenGLType
  42476. {
  42477. openGLDefault = 0,
  42478. #if JUCE_IPHONE
  42479. openGLES1, /**< On the iPhone, this selects openGL ES 1.0 */
  42480. openGLES2 /**< On the iPhone, this selects openGL ES 2.0 */
  42481. #endif
  42482. };
  42483. /** Creates an OpenGLComponent. */
  42484. OpenGLComponent (OpenGLType type = openGLDefault);
  42485. /** Destructor. */
  42486. ~OpenGLComponent();
  42487. /** Changes the pixel format used by this component.
  42488. @see OpenGLPixelFormat::getAvailablePixelFormats()
  42489. */
  42490. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  42491. /** Returns the pixel format that this component is currently using. */
  42492. const OpenGLPixelFormat getPixelFormat() const;
  42493. /** Specifies an OpenGL context which should be shared with the one that this
  42494. component is using.
  42495. This is an OpenGL feature that lets two contexts share their texture data.
  42496. Note that this pointer is stored by the component, and when the component
  42497. needs to recreate its internal context for some reason, the same context
  42498. will be used again to share lists. So if you pass a context in here,
  42499. don't delete the context while this component is still using it! You can
  42500. call shareWith (0) to stop this component from sharing with it.
  42501. */
  42502. void shareWith (OpenGLContext* contextToShareListsWith);
  42503. /** Returns the context that this component is sharing with.
  42504. @see shareWith
  42505. */
  42506. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  42507. /** Flips the openGL buffers over. */
  42508. void swapBuffers();
  42509. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  42510. When this is called, makeCurrentContextActive() will already have been called
  42511. for you, so you just need to draw.
  42512. */
  42513. virtual void renderOpenGL() = 0;
  42514. /** This method is called when the component creates a new OpenGL context.
  42515. A new context may be created when the component is first used, or when it
  42516. is moved to a different window, or when the window is hidden and re-shown,
  42517. etc.
  42518. You can use this callback as an opportunity to set up things like textures
  42519. that your context needs.
  42520. New contexts are created on-demand by the makeCurrentContextActive() method - so
  42521. if the context is deleted, e.g. by changing the pixel format or window, no context
  42522. will be created until the next call to makeCurrentContextActive(), which will
  42523. synchronously create one and call this method. This means that if you're using
  42524. a non-GUI thread for rendering, you can make sure this method is be called by
  42525. your renderer thread.
  42526. When this callback happens, the context will already have been made current
  42527. using the makeCurrentContextActive() method, so there's no need to call it
  42528. again in your code.
  42529. */
  42530. virtual void newOpenGLContextCreated() = 0;
  42531. /** Returns the context that will draw into this component.
  42532. This may return 0 if the component is currently invisible or hasn't currently
  42533. got a context. The context object can be deleted and a new one created during
  42534. the lifetime of this component, and there may be times when it doesn't have one.
  42535. @see newOpenGLContextCreated()
  42536. */
  42537. OpenGLContext* getCurrentContext() const throw() { return context; }
  42538. /** Makes this component the current openGL context.
  42539. You might want to use this in things like your resize() method, before calling
  42540. GL commands.
  42541. If this returns false, then the context isn't active, so you should avoid
  42542. making any calls.
  42543. This call may actually create a context if one isn't currently initialised. If
  42544. it does this, it will also synchronously call the newOpenGLContextCreated()
  42545. method to let you initialise it as necessary.
  42546. @see OpenGLContext::makeActive
  42547. */
  42548. bool makeCurrentContextActive();
  42549. /** Stops the current component being the active OpenGL context.
  42550. This is the opposite of makeCurrentContextActive()
  42551. @see OpenGLContext::makeInactive
  42552. */
  42553. void makeCurrentContextInactive();
  42554. /** Returns true if this component is the active openGL context for the
  42555. current thread.
  42556. @see OpenGLContext::isActive
  42557. */
  42558. bool isActiveContext() const throw();
  42559. /** Calls the rendering callback, and swaps the buffers afterwards.
  42560. This is called automatically by paint() when the component needs to be rendered.
  42561. It can be overridden if you need to decouple the rendering from the paint callback
  42562. and render with a custom thread.
  42563. Returns true if the operation succeeded.
  42564. */
  42565. virtual bool renderAndSwapBuffers();
  42566. /** This returns a critical section that can be used to lock the current context.
  42567. Because the context that is used by this component can change, e.g. when the
  42568. component is shown or hidden, then if you're rendering to it on a background
  42569. thread, this allows you to lock the context for the duration of your rendering
  42570. routine.
  42571. */
  42572. CriticalSection& getContextLock() throw() { return contextLock; }
  42573. /** @internal */
  42574. void paint (Graphics& g);
  42575. /** Returns the native handle of an embedded heavyweight window, if there is one.
  42576. E.g. On windows, this will return the HWND of the sub-window containing
  42577. the opengl context, on the mac it'll be the NSOpenGLView.
  42578. */
  42579. void* getNativeWindowHandle() const;
  42580. /** Call this to manually delete the current GL context, if there is one.
  42581. This can be useful to cause a clear-out of the context, which will be automatically
  42582. re-created when it's needed.
  42583. */
  42584. void deleteContext();
  42585. juce_UseDebuggingNewOperator
  42586. private:
  42587. const OpenGLType type;
  42588. class OpenGLComponentWatcher;
  42589. friend class OpenGLComponentWatcher;
  42590. friend class ScopedPointer <OpenGLComponentWatcher>;
  42591. ScopedPointer <OpenGLComponentWatcher> componentWatcher;
  42592. ScopedPointer <OpenGLContext> context;
  42593. OpenGLContext* contextToShareListsWith;
  42594. CriticalSection contextLock;
  42595. OpenGLPixelFormat preferredPixelFormat;
  42596. bool needToUpdateViewport;
  42597. OpenGLContext* createContext();
  42598. void updateContextPosition();
  42599. void internalRepaint (int x, int y, int w, int h);
  42600. OpenGLComponent (const OpenGLComponent&);
  42601. OpenGLComponent& operator= (const OpenGLComponent&);
  42602. };
  42603. #endif
  42604. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42605. /*** End of inlined file: juce_OpenGLComponent.h ***/
  42606. #endif
  42607. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  42608. /*** Start of inlined file: juce_PreferencesPanel.h ***/
  42609. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  42610. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  42611. /**
  42612. A component with a set of buttons at the top for changing between pages of
  42613. preferences.
  42614. This is just a handy way of writing a Mac-style preferences panel where you
  42615. have a row of buttons along the top for the different preference categories,
  42616. each button having an icon above its name. Clicking these will show an
  42617. appropriate prefs page below it.
  42618. You can either put one of these inside your own component, or just use the
  42619. showInDialogBox() method to show it in a window and run it modally.
  42620. To use it, just add a set of named pages with the addSettingsPage() method,
  42621. and implement the createComponentForPage() method to create suitable components
  42622. for each of these pages.
  42623. */
  42624. class JUCE_API PreferencesPanel : public Component,
  42625. private ButtonListener
  42626. {
  42627. public:
  42628. /** Creates an empty panel.
  42629. Use addSettingsPage() to add some pages to it in your constructor.
  42630. */
  42631. PreferencesPanel();
  42632. /** Destructor. */
  42633. ~PreferencesPanel();
  42634. /** Creates a page using a set of drawables to define the page's icon.
  42635. Note that the other version of this method is much easier if you're using
  42636. an image instead of a custom drawable.
  42637. @param pageTitle the name of this preferences page - you'll need to
  42638. make sure your createComponentForPage() method creates
  42639. a suitable component when it is passed this name
  42640. @param normalIcon the drawable to display in the page's button normally
  42641. @param overIcon the drawable to display in the page's button when the mouse is over
  42642. @param downIcon the drawable to display in the page's button when the button is down
  42643. @see DrawableButton
  42644. */
  42645. void addSettingsPage (const String& pageTitle,
  42646. const Drawable* normalIcon,
  42647. const Drawable* overIcon,
  42648. const Drawable* downIcon);
  42649. /** Creates a page using a set of drawables to define the page's icon.
  42650. The other version of this method gives you more control over the icon, but this
  42651. one is much easier if you're just loading it from a file.
  42652. @param pageTitle the name of this preferences page - you'll need to
  42653. make sure your createComponentForPage() method creates
  42654. a suitable component when it is passed this name
  42655. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  42656. For this to look good, you'll probably want to use a nice
  42657. transparent png file.
  42658. @param imageDataSize the size of the image data, in bytes
  42659. */
  42660. void addSettingsPage (const String& pageTitle,
  42661. const void* imageData,
  42662. int imageDataSize);
  42663. /** Utility method to display this panel in a DialogWindow.
  42664. Calling this will create a DialogWindow containing this panel with the
  42665. given size and title, and will run it modally, returning when the user
  42666. closes the dialog box.
  42667. */
  42668. void showInDialogBox (const String& dialogtitle,
  42669. int dialogWidth,
  42670. int dialogHeight,
  42671. const Colour& backgroundColour = Colours::white);
  42672. /** Subclasses must override this to return a component for each preferences page.
  42673. The subclass should return a pointer to a new component representing the named
  42674. page, which the panel will then display.
  42675. The panel will delete the component later when the user goes to another page
  42676. or deletes the panel.
  42677. */
  42678. virtual Component* createComponentForPage (const String& pageName) = 0;
  42679. /** Changes the current page being displayed. */
  42680. void setCurrentPage (const String& pageName);
  42681. /** @internal */
  42682. void resized();
  42683. /** @internal */
  42684. void paint (Graphics& g);
  42685. /** @internal */
  42686. void buttonClicked (Button* button);
  42687. juce_UseDebuggingNewOperator
  42688. private:
  42689. String currentPageName;
  42690. ScopedPointer <Component> currentPage;
  42691. int buttonSize;
  42692. PreferencesPanel (const PreferencesPanel&);
  42693. PreferencesPanel& operator= (const PreferencesPanel&);
  42694. };
  42695. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  42696. /*** End of inlined file: juce_PreferencesPanel.h ***/
  42697. #endif
  42698. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  42699. /*** Start of inlined file: juce_QuickTimeMovieComponent.h ***/
  42700. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  42701. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  42702. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  42703. // amalgamated build)
  42704. #if JUCE_WINDOWS
  42705. typedef ActiveXControlComponent QTCompBaseClass;
  42706. #elif JUCE_MAC
  42707. typedef NSViewComponent QTCompBaseClass;
  42708. #endif
  42709. // this is used to disable QuickTime, and is defined in juce_Config.h
  42710. #if JUCE_QUICKTIME || DOXYGEN
  42711. /**
  42712. A window that can play back a QuickTime movie.
  42713. */
  42714. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  42715. {
  42716. public:
  42717. /** Creates a QuickTimeMovieComponent, initially blank.
  42718. Use the loadMovie() method to load a movie once you've added the
  42719. component to a window, (or put it on the desktop as a heavyweight window).
  42720. Loading a movie when the component isn't visible can cause problems, as
  42721. QuickTime needs a window handle to initialise properly.
  42722. */
  42723. QuickTimeMovieComponent();
  42724. /** Destructor. */
  42725. ~QuickTimeMovieComponent();
  42726. /** Returns true if QT is installed and working on this machine.
  42727. */
  42728. static bool isQuickTimeAvailable() throw();
  42729. /** Tries to load a QuickTime movie from a file into the player.
  42730. It's best to call this function once you've added the component to a window,
  42731. (or put it on the desktop as a heavyweight window). Loading a movie when the
  42732. component isn't visible can cause problems, because QuickTime needs a window
  42733. handle to do its stuff.
  42734. @param movieFile the .mov file to open
  42735. @param isControllerVisible whether to show a controller bar at the bottom
  42736. @returns true if the movie opens successfully
  42737. */
  42738. bool loadMovie (const File& movieFile,
  42739. bool isControllerVisible);
  42740. /** Tries to load a QuickTime movie from a URL into the player.
  42741. It's best to call this function once you've added the component to a window,
  42742. (or put it on the desktop as a heavyweight window). Loading a movie when the
  42743. component isn't visible can cause problems, because QuickTime needs a window
  42744. handle to do its stuff.
  42745. @param movieURL the .mov file to open
  42746. @param isControllerVisible whether to show a controller bar at the bottom
  42747. @returns true if the movie opens successfully
  42748. */
  42749. bool loadMovie (const URL& movieURL,
  42750. bool isControllerVisible);
  42751. /** Tries to load a QuickTime movie from a stream 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 movieStream a stream containing a .mov file. The component may try
  42757. to read the whole stream before playing, rather than
  42758. streaming from it.
  42759. @param isControllerVisible whether to show a controller bar at the bottom
  42760. @returns true if the movie opens successfully
  42761. */
  42762. bool loadMovie (InputStream* movieStream,
  42763. bool isControllerVisible);
  42764. /** Closes the movie, if one is open. */
  42765. void closeMovie();
  42766. /** Returns the movie file that is currently open.
  42767. If there isn't one, this returns File::nonexistent
  42768. */
  42769. const File getCurrentMovieFile() const;
  42770. /** Returns true if there's currently a movie open. */
  42771. bool isMovieOpen() const;
  42772. /** Returns the length of the movie, in seconds. */
  42773. double getMovieDuration() const;
  42774. /** Returns the movie's natural size, in pixels.
  42775. You can use this to resize the component to show the movie at its preferred
  42776. scale.
  42777. If no movie is loaded, the size returned will be 0 x 0.
  42778. */
  42779. void getMovieNormalSize (int& width, int& height) const;
  42780. /** This will position the component within a given area, keeping its aspect
  42781. ratio correct according to the movie's normal size.
  42782. The component will be made as large as it can go within the space, and will
  42783. be aligned according to the justification value if this means there are gaps at
  42784. the top or sides.
  42785. */
  42786. void setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  42787. const RectanglePlacement& placement);
  42788. /** Starts the movie playing. */
  42789. void play();
  42790. /** Stops the movie playing. */
  42791. void stop();
  42792. /** Returns true if the movie is currently playing. */
  42793. bool isPlaying() const;
  42794. /** Moves the movie's position back to the start. */
  42795. void goToStart();
  42796. /** Sets the movie's position to a given time. */
  42797. void setPosition (double seconds);
  42798. /** Returns the current play position of the movie. */
  42799. double getPosition() const;
  42800. /** Changes the movie playback rate.
  42801. A value of 1 is normal speed, greater values play it proportionately faster,
  42802. smaller values play it slower.
  42803. */
  42804. void setSpeed (float newSpeed);
  42805. /** Changes the movie's playback volume.
  42806. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  42807. */
  42808. void setMovieVolume (float newVolume);
  42809. /** Returns the movie's playback volume.
  42810. @returns the volume in the range 0 (silent) to 1.0 (full)
  42811. */
  42812. float getMovieVolume() const;
  42813. /** Tells the movie whether it should loop. */
  42814. void setLooping (bool shouldLoop);
  42815. /** Returns true if the movie is currently looping.
  42816. @see setLooping
  42817. */
  42818. bool isLooping() const;
  42819. /** True if the native QuickTime controller bar is shown in the window.
  42820. @see loadMovie
  42821. */
  42822. bool isControllerVisible() const;
  42823. /** @internal */
  42824. void paint (Graphics& g);
  42825. juce_UseDebuggingNewOperator
  42826. private:
  42827. File movieFile;
  42828. bool movieLoaded, controllerVisible, looping;
  42829. #if JUCE_WINDOWS
  42830. void parentHierarchyChanged();
  42831. void visibilityChanged();
  42832. void createControlIfNeeded();
  42833. bool isControlCreated() const;
  42834. class Pimpl;
  42835. friend class ScopedPointer <Pimpl>;
  42836. ScopedPointer <Pimpl> pimpl;
  42837. #else
  42838. void* movie;
  42839. #endif
  42840. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  42841. QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  42842. };
  42843. #endif
  42844. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  42845. /*** End of inlined file: juce_QuickTimeMovieComponent.h ***/
  42846. #endif
  42847. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  42848. /*** Start of inlined file: juce_SystemTrayIconComponent.h ***/
  42849. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  42850. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  42851. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  42852. /**
  42853. On Windows only, this component sits in the taskbar tray as a small icon.
  42854. To use it, just create one of these components, but don't attempt to make it
  42855. visible, add it to a parent, or put it on the desktop.
  42856. You can then call setIconImage() to create an icon for it in the taskbar.
  42857. To change the icon's tooltip, you can use setIconTooltip().
  42858. To respond to mouse-events, you can override the normal mouseDown(),
  42859. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  42860. position will not be valid, you can use this to respond to clicks. Traditionally
  42861. you'd use a left-click to show your application's window, and a right-click
  42862. to show a pop-up menu.
  42863. */
  42864. class JUCE_API SystemTrayIconComponent : public Component
  42865. {
  42866. public:
  42867. SystemTrayIconComponent();
  42868. /** Destructor. */
  42869. ~SystemTrayIconComponent();
  42870. /** Changes the image shown in the taskbar.
  42871. */
  42872. void setIconImage (const Image& newImage);
  42873. /** Changes the tooltip that Windows shows above the icon. */
  42874. void setIconTooltip (const String& tooltip);
  42875. #if JUCE_LINUX
  42876. /** @internal */
  42877. void paint (Graphics& g);
  42878. #endif
  42879. juce_UseDebuggingNewOperator
  42880. private:
  42881. SystemTrayIconComponent (const SystemTrayIconComponent&);
  42882. SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  42883. };
  42884. #endif
  42885. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  42886. /*** End of inlined file: juce_SystemTrayIconComponent.h ***/
  42887. #endif
  42888. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  42889. /*** Start of inlined file: juce_WebBrowserComponent.h ***/
  42890. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  42891. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  42892. #if JUCE_WEB_BROWSER || DOXYGEN
  42893. #if ! DOXYGEN
  42894. class WebBrowserComponentInternal;
  42895. #endif
  42896. /**
  42897. A component that displays an embedded web browser.
  42898. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  42899. Windows, probably IE.
  42900. */
  42901. class JUCE_API WebBrowserComponent : public Component
  42902. {
  42903. public:
  42904. /** Creates a WebBrowserComponent.
  42905. Once it's created and visible, send the browser to a URL using goToURL().
  42906. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  42907. component is taken offscreen, it'll clear the current page
  42908. and replace it with a blank page - this can be handy to stop
  42909. the browser using resources in the background when it's not
  42910. actually being used.
  42911. */
  42912. explicit WebBrowserComponent (bool unloadPageWhenBrowserIsHidden = true);
  42913. /** Destructor. */
  42914. ~WebBrowserComponent();
  42915. /** Sends the browser to a particular URL.
  42916. @param url the URL to go to.
  42917. @param headers an optional set of parameters to put in the HTTP header. If
  42918. you supply this, it should be a set of string in the form
  42919. "HeaderKey: HeaderValue"
  42920. @param postData an optional block of data that will be attached to the HTTP
  42921. POST request
  42922. */
  42923. void goToURL (const String& url,
  42924. const StringArray* headers = 0,
  42925. const MemoryBlock* postData = 0);
  42926. /** Stops the current page loading.
  42927. */
  42928. void stop();
  42929. /** Sends the browser back one page.
  42930. */
  42931. void goBack();
  42932. /** Sends the browser forward one page.
  42933. */
  42934. void goForward();
  42935. /** Refreshes the browser.
  42936. */
  42937. void refresh();
  42938. /** This callback is called when the browser is about to navigate
  42939. to a new location.
  42940. You can override this method to perform some action when the user
  42941. tries to go to a particular URL. To allow the operation to carry on,
  42942. return true, or return false to stop the navigation happening.
  42943. */
  42944. virtual bool pageAboutToLoad (const String& newURL);
  42945. /** @internal */
  42946. void paint (Graphics& g);
  42947. /** @internal */
  42948. void resized();
  42949. /** @internal */
  42950. void parentHierarchyChanged();
  42951. /** @internal */
  42952. void visibilityChanged();
  42953. juce_UseDebuggingNewOperator
  42954. private:
  42955. WebBrowserComponentInternal* browser;
  42956. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  42957. String lastURL;
  42958. StringArray lastHeaders;
  42959. MemoryBlock lastPostData;
  42960. void reloadLastURL();
  42961. void checkWindowAssociation();
  42962. WebBrowserComponent (const WebBrowserComponent&);
  42963. WebBrowserComponent& operator= (const WebBrowserComponent&);
  42964. };
  42965. #endif
  42966. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  42967. /*** End of inlined file: juce_WebBrowserComponent.h ***/
  42968. #endif
  42969. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  42970. #endif
  42971. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  42972. /*** Start of inlined file: juce_ComponentPeer.h ***/
  42973. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  42974. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  42975. class ComponentBoundsConstrainer;
  42976. /**
  42977. The base class for window objects that wrap a component as a real operating
  42978. system object.
  42979. This is an abstract base class - the platform specific code contains default
  42980. implementations of it that create and manage windows.
  42981. @see Component::createNewPeer
  42982. */
  42983. class JUCE_API ComponentPeer
  42984. {
  42985. public:
  42986. /** A combination of these flags is passed to the ComponentPeer constructor. */
  42987. enum StyleFlags
  42988. {
  42989. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  42990. entry on the taskbar (ignored on MacOSX) */
  42991. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  42992. tooltip, etc. */
  42993. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  42994. through it (may not be possible on some platforms). */
  42995. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  42996. title bar and frame\. if not specified, the window will be
  42997. borderless. */
  42998. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  42999. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  43000. minimise button on it. */
  43001. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  43002. maximise button on it. */
  43003. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  43004. close button on it. */
  43005. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  43006. not be possible on all platforms). */
  43007. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  43008. do its own repainting, but only to repaint when the
  43009. performAnyPendingRepaintsNow() method is called. */
  43010. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  43011. be used for things like plugin windows, to stop them interfering
  43012. with the host's shortcut keys */
  43013. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  43014. };
  43015. /** Creates a peer.
  43016. The component is the one that we intend to represent, and the style flags are
  43017. a combination of the values in the StyleFlags enum
  43018. */
  43019. ComponentPeer (Component* component, int styleFlags);
  43020. /** Destructor. */
  43021. virtual ~ComponentPeer();
  43022. /** Returns the component being represented by this peer. */
  43023. Component* getComponent() const throw() { return component; }
  43024. /** Returns the set of style flags that were set when the window was created.
  43025. @see Component::addToDesktop
  43026. */
  43027. int getStyleFlags() const throw() { return styleFlags; }
  43028. /** Returns the raw handle to whatever kind of window is being used.
  43029. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  43030. but rememeber there's no guarantees what you'll get back.
  43031. */
  43032. virtual void* getNativeHandle() const = 0;
  43033. /** Shows or hides the window. */
  43034. virtual void setVisible (bool shouldBeVisible) = 0;
  43035. /** Changes the title of the window. */
  43036. virtual void setTitle (const String& title) = 0;
  43037. /** Moves the window without changing its size.
  43038. If the native window is contained in another window, then the co-ordinates are
  43039. relative to the parent window's origin, not the screen origin.
  43040. This should result in a callback to handleMovedOrResized().
  43041. */
  43042. virtual void setPosition (int x, int y) = 0;
  43043. /** Resizes the window without changing its position.
  43044. This should result in a callback to handleMovedOrResized().
  43045. */
  43046. virtual void setSize (int w, int h) = 0;
  43047. /** Moves and resizes the window.
  43048. If the native window is contained in another window, then the co-ordinates are
  43049. relative to the parent window's origin, not the screen origin.
  43050. This should result in a callback to handleMovedOrResized().
  43051. */
  43052. virtual void setBounds (int x, int y, int w, int h, bool isNowFullScreen) = 0;
  43053. /** Returns the current position and size of the window.
  43054. If the native window is contained in another window, then the co-ordinates are
  43055. relative to the parent window's origin, not the screen origin.
  43056. */
  43057. virtual const Rectangle<int> getBounds() const = 0;
  43058. /** Returns the x-position of this window, relative to the screen's origin. */
  43059. virtual const Point<int> getScreenPosition() const = 0;
  43060. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  43061. virtual const Point<int> relativePositionToGlobal (const Point<int>& relativePosition) = 0;
  43062. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  43063. virtual const Point<int> globalPositionToRelative (const Point<int>& screenPosition) = 0;
  43064. /** Minimises the window. */
  43065. virtual void setMinimised (bool shouldBeMinimised) = 0;
  43066. /** True if the window is currently minimised. */
  43067. virtual bool isMinimised() const = 0;
  43068. /** Enable/disable fullscreen mode for the window. */
  43069. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  43070. /** True if the window is currently full-screen. */
  43071. virtual bool isFullScreen() const = 0;
  43072. /** Sets the size to restore to if fullscreen mode is turned off. */
  43073. void setNonFullScreenBounds (const Rectangle<int>& newBounds) throw();
  43074. /** Returns the size to restore to if fullscreen mode is turned off. */
  43075. const Rectangle<int>& getNonFullScreenBounds() const throw();
  43076. /** Attempts to change the icon associated with this window.
  43077. */
  43078. virtual void setIcon (const Image& newIcon) = 0;
  43079. /** Sets a constrainer to use if the peer can resize itself.
  43080. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  43081. */
  43082. void setConstrainer (ComponentBoundsConstrainer* newConstrainer) throw();
  43083. /** Returns the current constrainer, if one has been set. */
  43084. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  43085. /** Checks if a point is in the window.
  43086. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  43087. is false, then this returns false if the point is actually inside a child of this
  43088. window.
  43089. */
  43090. virtual bool contains (const Point<int>& position, bool trueIfInAChildWindow) const = 0;
  43091. /** Returns the size of the window frame that's around this window.
  43092. Whether or not the window has a normal window frame depends on the flags
  43093. that were set when the window was created by Component::addToDesktop()
  43094. */
  43095. virtual const BorderSize getFrameSize() const = 0;
  43096. /** This is called when the window's bounds change.
  43097. A peer implementation must call this when the window is moved and resized, so that
  43098. this method can pass the message on to the component.
  43099. */
  43100. void handleMovedOrResized();
  43101. /** This is called if the screen resolution changes.
  43102. A peer implementation must call this if the monitor arrangement changes or the available
  43103. screen size changes.
  43104. */
  43105. void handleScreenSizeChange();
  43106. /** This is called to repaint the component into the given context. */
  43107. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  43108. /** Sets this window to either be always-on-top or normal.
  43109. Some kinds of window might not be able to do this, so should return false.
  43110. */
  43111. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  43112. /** Brings the window to the top, optionally also giving it focus. */
  43113. virtual void toFront (bool makeActive) = 0;
  43114. /** Moves the window to be just behind another one. */
  43115. virtual void toBehind (ComponentPeer* other) = 0;
  43116. /** Called when the window is brought to the front, either by the OS or by a call
  43117. to toFront().
  43118. */
  43119. void handleBroughtToFront();
  43120. /** True if the window has the keyboard focus. */
  43121. virtual bool isFocused() const = 0;
  43122. /** Tries to give the window keyboard focus. */
  43123. virtual void grabFocus() = 0;
  43124. /** Tells the window that text input may be required at the given position.
  43125. This may cause things like a virtual on-screen keyboard to appear, depending
  43126. on the OS.
  43127. */
  43128. virtual void textInputRequired (const Point<int>& position) = 0;
  43129. /** Called when the window gains keyboard focus. */
  43130. void handleFocusGain();
  43131. /** Called when the window loses keyboard focus. */
  43132. void handleFocusLoss();
  43133. Component* getLastFocusedSubcomponent() const throw();
  43134. /** Called when a key is pressed.
  43135. For keycode info, see the KeyPress class.
  43136. Returns true if the keystroke was used.
  43137. */
  43138. bool handleKeyPress (int keyCode,
  43139. juce_wchar textCharacter);
  43140. /** Called whenever a key is pressed or released.
  43141. Returns true if the keystroke was used.
  43142. */
  43143. bool handleKeyUpOrDown (bool isKeyDown);
  43144. /** Called whenever a modifier key is pressed or released. */
  43145. void handleModifierKeysChange();
  43146. /** Returns the currently focused TextInputTarget, or null if none is found. */
  43147. TextInputTarget* findCurrentTextInputTarget();
  43148. /** Invalidates a region of the window to be repainted asynchronously. */
  43149. virtual void repaint (const Rectangle<int>& area) = 0;
  43150. /** This can be called (from the message thread) to cause the immediate redrawing
  43151. of any areas of this window that need repainting.
  43152. You shouldn't ever really need to use this, it's mainly for special purposes
  43153. like supporting audio plugins where the host's event loop is out of our control.
  43154. */
  43155. virtual void performAnyPendingRepaintsNow() = 0;
  43156. void handleMouseEvent (int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, int64 time);
  43157. void handleMouseWheel (int touchIndex, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  43158. void handleUserClosingWindow();
  43159. void handleFileDragMove (const StringArray& files, const Point<int>& position);
  43160. void handleFileDragExit (const StringArray& files);
  43161. void handleFileDragDrop (const StringArray& files, const Point<int>& position);
  43162. /** Resets the masking region.
  43163. The subclass should call this every time it's about to call the handlePaint
  43164. method.
  43165. @see addMaskedRegion
  43166. */
  43167. void clearMaskedRegion();
  43168. /** Adds a rectangle to the set of areas not to paint over.
  43169. A component can call this on its peer during its paint() method, to signal
  43170. that the painting code should ignore a given region. The reason
  43171. for this is to stop embedded windows (such as OpenGL) getting painted over.
  43172. The masked region is cleared each time before a paint happens, so a component
  43173. will have to make sure it calls this every time it's painted.
  43174. */
  43175. void addMaskedRegion (int x, int y, int w, int h);
  43176. /** Returns the number of currently-active peers.
  43177. @see getPeer
  43178. */
  43179. static int getNumPeers() throw();
  43180. /** Returns one of the currently-active peers.
  43181. @see getNumPeers
  43182. */
  43183. static ComponentPeer* getPeer (int index) throw();
  43184. /** Checks if this peer object is valid.
  43185. @see getNumPeers
  43186. */
  43187. static bool isValidPeer (const ComponentPeer* peer) throw();
  43188. static void bringModalComponentToFront();
  43189. virtual const StringArray getAvailableRenderingEngines() throw();
  43190. virtual int getCurrentRenderingEngine() throw();
  43191. virtual void setCurrentRenderingEngine (int index) throw();
  43192. juce_UseDebuggingNewOperator
  43193. protected:
  43194. Component* const component;
  43195. const int styleFlags;
  43196. RectangleList maskedRegion;
  43197. Rectangle<int> lastNonFullscreenBounds;
  43198. uint32 lastPaintTime;
  43199. ComponentBoundsConstrainer* constrainer;
  43200. static void updateCurrentModifiers() throw();
  43201. private:
  43202. Component::SafePointer<Component> lastFocusedComponent, dragAndDropTargetComponent;
  43203. Component* lastDragAndDropCompUnderMouse;
  43204. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  43205. friend class Component;
  43206. static ComponentPeer* getPeerFor (const Component* component) throw();
  43207. void setLastDragDropTarget (Component* comp);
  43208. ComponentPeer (const ComponentPeer&);
  43209. ComponentPeer& operator= (const ComponentPeer&);
  43210. };
  43211. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  43212. /*** End of inlined file: juce_ComponentPeer.h ***/
  43213. #endif
  43214. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  43215. /*** Start of inlined file: juce_DialogWindow.h ***/
  43216. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  43217. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  43218. /**
  43219. A dialog-box style window.
  43220. This class is a convenient way of creating a DocumentWindow with a close button
  43221. that can be triggered by pressing the escape key.
  43222. Any of the methods available to a DocumentWindow or ResizableWindow are also
  43223. available to this, so it can be made resizable, have a menu bar, etc.
  43224. To add items to the box, see the ResizableWindow::setContentComponent() method.
  43225. Don't add components directly to this class - always put them in a content component!
  43226. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  43227. the user clicking the close button - for more info, see the DocumentWindow
  43228. help.
  43229. @see DocumentWindow, ResizableWindow
  43230. */
  43231. class JUCE_API DialogWindow : public DocumentWindow
  43232. {
  43233. public:
  43234. /** Creates a DialogWindow.
  43235. @param name the name to give the component - this is also
  43236. the title shown at the top of the window. To change
  43237. this later, use setName()
  43238. @param backgroundColour the colour to use for filling the window's background.
  43239. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  43240. close button to be triggered
  43241. @param addToDesktop if true, the window will be automatically added to the
  43242. desktop; if false, you can use it as a child component
  43243. */
  43244. DialogWindow (const String& name,
  43245. const Colour& backgroundColour,
  43246. bool escapeKeyTriggersCloseButton,
  43247. bool addToDesktop = true);
  43248. /** Destructor.
  43249. If a content component has been set with setContentComponent(), it
  43250. will be deleted.
  43251. */
  43252. ~DialogWindow();
  43253. /** Easy way of quickly showing a dialog box containing a given component.
  43254. This will open and display a DialogWindow containing a given component, returning
  43255. when the user clicks its close button.
  43256. It returns the value that was returned by the dialog box's runModalLoop() call.
  43257. To close the dialog programatically, you should call exitModalState (returnValue) on
  43258. the DialogWindow that is created. To find a pointer to this window from your
  43259. contentComponent, you can do something like this:
  43260. @code
  43261. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  43262. if (dw != 0)
  43263. dw->exitModalState (1234);
  43264. @endcode
  43265. @param dialogTitle the dialog box's title
  43266. @param contentComponent the content component for the dialog box. Make sure
  43267. that this has been set to the size you want it to
  43268. be before calling this method. The component won't
  43269. be deleted by this call, so you can re-use it or delete
  43270. it afterwards
  43271. @param componentToCentreAround if this is non-zero, it indicates a component that
  43272. you'd like to show this dialog box in front of. See the
  43273. DocumentWindow::centreAroundComponent() method for more
  43274. info on this parameter
  43275. @param backgroundColour a colour to use for the dialog box's background colour
  43276. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  43277. close button to be triggered
  43278. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  43279. a corner resizer
  43280. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  43281. to use a border or corner resizer component. See ResizableWindow::setResizable()
  43282. */
  43283. static int showModalDialog (const String& dialogTitle,
  43284. Component* contentComponent,
  43285. Component* componentToCentreAround,
  43286. const Colour& backgroundColour,
  43287. bool escapeKeyTriggersCloseButton,
  43288. bool shouldBeResizable = false,
  43289. bool useBottomRightCornerResizer = false);
  43290. juce_UseDebuggingNewOperator
  43291. protected:
  43292. /** @internal */
  43293. void resized();
  43294. private:
  43295. bool escapeKeyTriggersCloseButton;
  43296. DialogWindow (const DialogWindow&);
  43297. DialogWindow& operator= (const DialogWindow&);
  43298. };
  43299. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  43300. /*** End of inlined file: juce_DialogWindow.h ***/
  43301. #endif
  43302. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  43303. #endif
  43304. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  43305. #endif
  43306. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  43307. /*** Start of inlined file: juce_SplashScreen.h ***/
  43308. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  43309. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  43310. /** A component for showing a splash screen while your app starts up.
  43311. This will automatically position itself, and delete itself when the app has
  43312. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  43313. this).
  43314. To use it, just create one of these in your JUCEApplication::initialise() method,
  43315. call its show() method and let the object delete itself later.
  43316. E.g. @code
  43317. void MyApp::initialise (const String& commandLine)
  43318. {
  43319. SplashScreen* splash = new SplashScreen();
  43320. splash->show ("welcome to my app",
  43321. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  43322. 4000, false);
  43323. .. no need to delete the splash screen - it'll do that itself.
  43324. }
  43325. @endcode
  43326. */
  43327. class JUCE_API SplashScreen : public Component,
  43328. public Timer,
  43329. private DeletedAtShutdown
  43330. {
  43331. public:
  43332. /** Creates a SplashScreen object.
  43333. After creating one of these (or your subclass of it), call one of the show()
  43334. methods to display it.
  43335. */
  43336. SplashScreen();
  43337. /** Destructor. */
  43338. ~SplashScreen();
  43339. /** Creates a SplashScreen object that will display an image.
  43340. As soon as this is called, the SplashScreen will be displayed in the centre of the
  43341. screen. This method will also dispatch any pending messages to make sure that when
  43342. it returns, the splash screen has been completely drawn, and your initialisation
  43343. code can carry on.
  43344. @param title the name to give the component
  43345. @param backgroundImage an image to draw on the component. The component's size
  43346. will be set to the size of this image, and if the image is
  43347. semi-transparent, the component will be made semi-transparent
  43348. too. This image will be deleted (or released from the ImageCache
  43349. if that's how it was created) by the splash screen object when
  43350. it is itself deleted.
  43351. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  43352. should stay visible for. If the initialisation takes longer than
  43353. this time, the splash screen will wait for it to finish before
  43354. disappearing, but if initialisation is very quick, this lets
  43355. you make sure that people get a good look at your splash.
  43356. @param useDropShadow if true, the window will have a drop shadow
  43357. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  43358. the mouse (anywhere)
  43359. */
  43360. void show (const String& title,
  43361. const Image& backgroundImage,
  43362. int minimumTimeToDisplayFor,
  43363. bool useDropShadow,
  43364. bool removeOnMouseClick = true);
  43365. /** Creates a SplashScreen object with a specified size.
  43366. For a custom splash screen, you can use this method to display it at a certain size
  43367. and then override the paint() method yourself to do whatever's necessary.
  43368. As soon as this is called, the SplashScreen will be displayed in the centre of the
  43369. screen. This method will also dispatch any pending messages to make sure that when
  43370. it returns, the splash screen has been completely drawn, and your initialisation
  43371. code can carry on.
  43372. @param title the name to give the component
  43373. @param width the width to use
  43374. @param height the height to use
  43375. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  43376. should stay visible for. If the initialisation takes longer than
  43377. this time, the splash screen will wait for it to finish before
  43378. disappearing, but if initialisation is very quick, this lets
  43379. you make sure that people get a good look at your splash.
  43380. @param useDropShadow if true, the window will have a drop shadow
  43381. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  43382. the mouse (anywhere)
  43383. */
  43384. void show (const String& title,
  43385. int width,
  43386. int height,
  43387. int minimumTimeToDisplayFor,
  43388. bool useDropShadow,
  43389. bool removeOnMouseClick = true);
  43390. /** @internal */
  43391. void paint (Graphics& g);
  43392. /** @internal */
  43393. void timerCallback();
  43394. juce_UseDebuggingNewOperator
  43395. private:
  43396. Image backgroundImage;
  43397. Time earliestTimeToDelete;
  43398. int originalClickCounter;
  43399. SplashScreen (const SplashScreen&);
  43400. SplashScreen& operator= (const SplashScreen&);
  43401. };
  43402. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  43403. /*** End of inlined file: juce_SplashScreen.h ***/
  43404. #endif
  43405. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43406. /*** Start of inlined file: juce_ThreadWithProgressWindow.h ***/
  43407. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43408. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43409. /**
  43410. A thread that automatically pops up a modal dialog box with a progress bar
  43411. and cancel button while it's busy running.
  43412. These are handy for performing some sort of task while giving the user feedback
  43413. about how long there is to go, etc.
  43414. E.g. @code
  43415. class MyTask : public ThreadWithProgressWindow
  43416. {
  43417. public:
  43418. MyTask() : ThreadWithProgressWindow ("busy...", true, true)
  43419. {
  43420. }
  43421. ~MyTask()
  43422. {
  43423. }
  43424. void run()
  43425. {
  43426. for (int i = 0; i < thingsToDo; ++i)
  43427. {
  43428. // must check this as often as possible, because this is
  43429. // how we know if the user's pressed 'cancel'
  43430. if (threadShouldExit())
  43431. break;
  43432. // this will update the progress bar on the dialog box
  43433. setProgress (i / (double) thingsToDo);
  43434. // ... do the business here...
  43435. }
  43436. }
  43437. };
  43438. void doTheTask()
  43439. {
  43440. MyTask m;
  43441. if (m.runThread())
  43442. {
  43443. // thread finished normally..
  43444. }
  43445. else
  43446. {
  43447. // user pressed the cancel button..
  43448. }
  43449. }
  43450. @endcode
  43451. @see Thread, AlertWindow
  43452. */
  43453. class JUCE_API ThreadWithProgressWindow : public Thread,
  43454. private Timer
  43455. {
  43456. public:
  43457. /** Creates the thread.
  43458. Initially, the dialog box won't be visible, it'll only appear when the
  43459. runThread() method is called.
  43460. @param windowTitle the title to go at the top of the dialog box
  43461. @param hasProgressBar whether the dialog box should have a progress bar (see
  43462. setProgress() )
  43463. @param hasCancelButton whether the dialog box should have a cancel button
  43464. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  43465. the thread to stop before killing it forcibly (see
  43466. Thread::stopThread() )
  43467. @param cancelButtonText the text that should be shown in the cancel button
  43468. (if it has one)
  43469. */
  43470. ThreadWithProgressWindow (const String& windowTitle,
  43471. bool hasProgressBar,
  43472. bool hasCancelButton,
  43473. int timeOutMsWhenCancelling = 10000,
  43474. const String& cancelButtonText = "Cancel");
  43475. /** Destructor. */
  43476. ~ThreadWithProgressWindow();
  43477. /** Starts the thread and waits for it to finish.
  43478. This will start the thread, make the dialog box appear, and wait until either
  43479. the thread finishes normally, or until the cancel button is pressed.
  43480. Before returning, the dialog box will be hidden.
  43481. @param threadPriority the priority to use when starting the thread - see
  43482. Thread::startThread() for values
  43483. @returns true if the thread finished normally; false if the user pressed cancel
  43484. */
  43485. bool runThread (int threadPriority = 5);
  43486. /** The thread should call this periodically to update the position of the progress bar.
  43487. @param newProgress the progress, from 0.0 to 1.0
  43488. @see setStatusMessage
  43489. */
  43490. void setProgress (double newProgress);
  43491. /** The thread can call this to change the message that's displayed in the dialog box.
  43492. */
  43493. void setStatusMessage (const String& newStatusMessage);
  43494. /** Returns the AlertWindow that is being used.
  43495. */
  43496. AlertWindow* getAlertWindow() const throw() { return alertWindow; }
  43497. juce_UseDebuggingNewOperator
  43498. private:
  43499. void timerCallback();
  43500. double progress;
  43501. ScopedPointer <AlertWindow> alertWindow;
  43502. String message;
  43503. CriticalSection messageLock;
  43504. const int timeOutMsWhenCancelling;
  43505. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  43506. ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  43507. };
  43508. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43509. /*** End of inlined file: juce_ThreadWithProgressWindow.h ***/
  43510. #endif
  43511. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  43512. #endif
  43513. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  43514. #endif
  43515. #ifndef __JUCE_COLOUR_JUCEHEADER__
  43516. #endif
  43517. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  43518. #endif
  43519. #ifndef __JUCE_COLOURS_JUCEHEADER__
  43520. #endif
  43521. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  43522. #endif
  43523. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  43524. /*** Start of inlined file: juce_EdgeTable.h ***/
  43525. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  43526. #define __JUCE_EDGETABLE_JUCEHEADER__
  43527. class Path;
  43528. class Image;
  43529. /**
  43530. A table of horizontal scan-line segments - used for rasterising Paths.
  43531. @see Path, Graphics
  43532. */
  43533. class JUCE_API EdgeTable
  43534. {
  43535. public:
  43536. /** Creates an edge table containing a path.
  43537. A table is created with a fixed vertical range, and only sections of the path
  43538. which lie within this range will be added to the table.
  43539. @param clipLimits only the region of the path that lies within this area will be added
  43540. @param pathToAdd the path to add to the table
  43541. @param transform a transform to apply to the path being added
  43542. */
  43543. EdgeTable (const Rectangle<int>& clipLimits,
  43544. const Path& pathToAdd,
  43545. const AffineTransform& transform);
  43546. /** Creates an edge table containing a rectangle.
  43547. */
  43548. EdgeTable (const Rectangle<int>& rectangleToAdd);
  43549. /** Creates an edge table containing a rectangle list.
  43550. */
  43551. EdgeTable (const RectangleList& rectanglesToAdd);
  43552. /** Creates an edge table containing a rectangle.
  43553. */
  43554. EdgeTable (const Rectangle<float>& rectangleToAdd);
  43555. /** Creates a copy of another edge table. */
  43556. EdgeTable (const EdgeTable& other);
  43557. /** Copies from another edge table. */
  43558. EdgeTable& operator= (const EdgeTable& other);
  43559. /** Destructor. */
  43560. ~EdgeTable();
  43561. void clipToRectangle (const Rectangle<int>& r) throw();
  43562. void excludeRectangle (const Rectangle<int>& r) throw();
  43563. void clipToEdgeTable (const EdgeTable& other);
  43564. void clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw();
  43565. bool isEmpty() throw();
  43566. const Rectangle<int>& getMaximumBounds() const throw() { return bounds; }
  43567. void translate (float dx, int dy) throw();
  43568. /** Reduces the amount of space the table has allocated.
  43569. This will shrink the table down to use as little memory as possible - useful for
  43570. read-only tables that get stored and re-used for rendering.
  43571. */
  43572. void optimiseTable() throw();
  43573. /** Iterates the lines in the table, for rendering.
  43574. This function will iterate each line in the table, and call a user-defined class
  43575. to render each pixel or continuous line of pixels that the table contains.
  43576. @param iterationCallback this templated class must contain the following methods:
  43577. @code
  43578. inline void setEdgeTableYPos (int y);
  43579. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  43580. inline void handleEdgeTablePixelFull (int x) const;
  43581. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  43582. inline void handleEdgeTableLineFull (int x, int width) const;
  43583. @endcode
  43584. (these don't necessarily have to be 'const', but it might help it go faster)
  43585. */
  43586. template <class EdgeTableIterationCallback>
  43587. void iterate (EdgeTableIterationCallback& iterationCallback) const throw()
  43588. {
  43589. const int* lineStart = table;
  43590. for (int y = 0; y < bounds.getHeight(); ++y)
  43591. {
  43592. const int* line = lineStart;
  43593. lineStart += lineStrideElements;
  43594. int numPoints = line[0];
  43595. if (--numPoints > 0)
  43596. {
  43597. int x = *++line;
  43598. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  43599. int levelAccumulator = 0;
  43600. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  43601. while (--numPoints >= 0)
  43602. {
  43603. const int level = *++line;
  43604. jassert (((unsigned int) level) < (unsigned int) 256);
  43605. const int endX = *++line;
  43606. jassert (endX >= x);
  43607. const int endOfRun = (endX >> 8);
  43608. if (endOfRun == (x >> 8))
  43609. {
  43610. // small segment within the same pixel, so just save it for the next
  43611. // time round..
  43612. levelAccumulator += (endX - x) * level;
  43613. }
  43614. else
  43615. {
  43616. // plot the fist pixel of this segment, including any accumulated
  43617. // levels from smaller segments that haven't been drawn yet
  43618. levelAccumulator += (0xff - (x & 0xff)) * level;
  43619. levelAccumulator >>= 8;
  43620. x >>= 8;
  43621. if (levelAccumulator > 0)
  43622. {
  43623. if (levelAccumulator >> 8)
  43624. iterationCallback.handleEdgeTablePixelFull (x);
  43625. else
  43626. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  43627. }
  43628. // if there's a run of similar pixels, do it all in one go..
  43629. if (level > 0)
  43630. {
  43631. jassert (endOfRun <= bounds.getRight());
  43632. const int numPix = endOfRun - ++x;
  43633. if (numPix > 0)
  43634. iterationCallback.handleEdgeTableLine (x, numPix, level);
  43635. }
  43636. // save the bit at the end to be drawn next time round the loop.
  43637. levelAccumulator = (endX & 0xff) * level;
  43638. }
  43639. x = endX;
  43640. }
  43641. levelAccumulator >>= 8;
  43642. if (levelAccumulator > 0)
  43643. {
  43644. x >>= 8;
  43645. jassert (x >= bounds.getX() && x < bounds.getRight());
  43646. if (levelAccumulator >> 8)
  43647. iterationCallback.handleEdgeTablePixelFull (x);
  43648. else
  43649. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  43650. }
  43651. }
  43652. }
  43653. }
  43654. juce_UseDebuggingNewOperator
  43655. private:
  43656. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  43657. HeapBlock<int> table;
  43658. Rectangle<int> bounds;
  43659. int maxEdgesPerLine, lineStrideElements;
  43660. bool needToCheckEmptinesss;
  43661. void addEdgePoint (int x, int y, int winding) throw();
  43662. void remapTableForNumEdges (int newNumEdgesPerLine) throw();
  43663. void intersectWithEdgeTableLine (int y, const int* otherLine) throw();
  43664. void clipEdgeTableLineToRange (int* line, int x1, int x2) throw();
  43665. void sanitiseLevels (bool useNonZeroWinding) throw();
  43666. static void copyEdgeTableData (int* dest, int destLineStride, const int* src, int srcLineStride, int numLines) throw();
  43667. };
  43668. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  43669. /*** End of inlined file: juce_EdgeTable.h ***/
  43670. #endif
  43671. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  43672. /*** Start of inlined file: juce_FillType.h ***/
  43673. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  43674. #define __JUCE_FILLTYPE_JUCEHEADER__
  43675. /**
  43676. Represents a colour or fill pattern to use for rendering paths.
  43677. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  43678. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  43679. @see Graphics::setFillType, DrawablePath::setFill
  43680. */
  43681. class JUCE_API FillType
  43682. {
  43683. public:
  43684. /** Creates a default fill type, of solid black. */
  43685. FillType() throw();
  43686. /** Creates a fill type of a solid colour.
  43687. @see setColour
  43688. */
  43689. FillType (const Colour& colour) throw();
  43690. /** Creates a gradient fill type.
  43691. @see setGradient
  43692. */
  43693. FillType (const ColourGradient& gradient);
  43694. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  43695. and rotation of the pattern.
  43696. @see setTiledImage
  43697. */
  43698. FillType (const Image& image, const AffineTransform& transform) throw();
  43699. /** Creates a copy of another FillType. */
  43700. FillType (const FillType& other);
  43701. /** Makes a copy of another FillType. */
  43702. FillType& operator= (const FillType& other);
  43703. /** Destructor. */
  43704. ~FillType() throw();
  43705. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  43706. bool isColour() const throw() { return gradient == 0 && image.isNull(); }
  43707. /** Returns true if this is a gradient fill. */
  43708. bool isGradient() const throw() { return gradient != 0; }
  43709. /** Returns true if this is a tiled image pattern fill. */
  43710. bool isTiledImage() const throw() { return image.isValid(); }
  43711. /** Turns this object into a solid colour fill.
  43712. If the object was an image or gradient, those fields will no longer be valid. */
  43713. void setColour (const Colour& newColour) throw();
  43714. /** Turns this object into a gradient fill. */
  43715. void setGradient (const ColourGradient& newGradient);
  43716. /** Turns this object into a tiled image fill type. The transform allows you to set
  43717. the scaling, offset and rotation of the pattern.
  43718. */
  43719. void setTiledImage (const Image& image, const AffineTransform& transform) throw();
  43720. /** Changes the opacity that should be used.
  43721. If the fill is a solid colour, this just changes the opacity of that colour. For
  43722. gradients and image tiles, it changes the opacity that will be used for them.
  43723. */
  43724. void setOpacity (float newOpacity) throw();
  43725. /** Returns the current opacity to be applied to the colour, gradient, or image.
  43726. @see setOpacity
  43727. */
  43728. float getOpacity() const throw() { return colour.getFloatAlpha(); }
  43729. /** Returns true if this fill type is completely transparent. */
  43730. bool isInvisible() const throw();
  43731. bool operator== (const FillType& other) const;
  43732. bool operator!= (const FillType& other) const;
  43733. /** The solid colour being used.
  43734. If the fill type is not a solid colour, the alpha channel of this colour indicates
  43735. the opacity that should be used for the fill, and the RGB channels are ignored.
  43736. */
  43737. Colour colour;
  43738. /** Returns the gradient that should be used for filling.
  43739. This will be zero if the object is some other type of fill.
  43740. If a gradient is active, the overall opacity with which it should be applied
  43741. is indicated by the alpha channel of the colour variable.
  43742. */
  43743. ScopedPointer <ColourGradient> gradient;
  43744. /** The image that should be used for tiling.
  43745. If an image fill is active, the overall opacity with which it should be applied
  43746. is indicated by the alpha channel of the colour variable.
  43747. */
  43748. Image image;
  43749. /** The transform that should be applied to the image or gradient that's being drawn.
  43750. */
  43751. AffineTransform transform;
  43752. juce_UseDebuggingNewOperator
  43753. };
  43754. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  43755. /*** End of inlined file: juce_FillType.h ***/
  43756. #endif
  43757. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  43758. #endif
  43759. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  43760. #endif
  43761. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  43762. /*** Start of inlined file: juce_LowLevelGraphicsContext.h ***/
  43763. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  43764. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  43765. /**
  43766. Interface class for graphics context objects, used internally by the Graphics class.
  43767. Users are not supposed to create instances of this class directly - do your drawing
  43768. via the Graphics object instead.
  43769. It's a base class for different types of graphics context, that may perform software-based
  43770. or OS-accelerated rendering.
  43771. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  43772. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  43773. context.
  43774. */
  43775. class JUCE_API LowLevelGraphicsContext
  43776. {
  43777. protected:
  43778. LowLevelGraphicsContext();
  43779. public:
  43780. virtual ~LowLevelGraphicsContext();
  43781. /** Returns true if this device is vector-based, e.g. a printer. */
  43782. virtual bool isVectorDevice() const = 0;
  43783. /** Moves the origin to a new position.
  43784. The co-ords are relative to the current origin, and indicate the new position
  43785. of (0, 0).
  43786. */
  43787. virtual void setOrigin (int x, int y) = 0;
  43788. virtual bool clipToRectangle (const Rectangle<int>& r) = 0;
  43789. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  43790. virtual void excludeClipRectangle (const Rectangle<int>& r) = 0;
  43791. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  43792. virtual void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform) = 0;
  43793. virtual bool clipRegionIntersects (const Rectangle<int>& r) = 0;
  43794. virtual const Rectangle<int> getClipBounds() const = 0;
  43795. virtual bool isClipEmpty() const = 0;
  43796. virtual void saveState() = 0;
  43797. virtual void restoreState() = 0;
  43798. virtual void setFill (const FillType& fillType) = 0;
  43799. virtual void setOpacity (float newOpacity) = 0;
  43800. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  43801. virtual void fillRect (const Rectangle<int>& r, bool replaceExistingContents) = 0;
  43802. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  43803. virtual void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  43804. const AffineTransform& transform, bool fillEntireClipAsTiles) = 0;
  43805. virtual void drawLine (const Line <float>& line) = 0;
  43806. virtual void drawVerticalLine (int x, float top, float bottom) = 0;
  43807. virtual void drawHorizontalLine (int y, float left, float right) = 0;
  43808. virtual void setFont (const Font& newFont) = 0;
  43809. virtual const Font getFont() = 0;
  43810. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  43811. };
  43812. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  43813. /*** End of inlined file: juce_LowLevelGraphicsContext.h ***/
  43814. #endif
  43815. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  43816. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  43817. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  43818. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  43819. /**
  43820. An implementation of LowLevelGraphicsContext that turns the drawing operations
  43821. into a PostScript document.
  43822. */
  43823. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  43824. {
  43825. public:
  43826. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  43827. const String& documentTitle,
  43828. int totalWidth,
  43829. int totalHeight);
  43830. ~LowLevelGraphicsPostScriptRenderer();
  43831. bool isVectorDevice() const;
  43832. void setOrigin (int x, int y);
  43833. bool clipToRectangle (const Rectangle<int>& r);
  43834. bool clipToRectangleList (const RectangleList& clipRegion);
  43835. void excludeClipRectangle (const Rectangle<int>& r);
  43836. void clipToPath (const Path& path, const AffineTransform& transform);
  43837. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform);
  43838. void saveState();
  43839. void restoreState();
  43840. bool clipRegionIntersects (const Rectangle<int>& r);
  43841. const Rectangle<int> getClipBounds() const;
  43842. bool isClipEmpty() const;
  43843. void setFill (const FillType& fillType);
  43844. void setOpacity (float opacity);
  43845. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  43846. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  43847. void fillPath (const Path& path, const AffineTransform& transform);
  43848. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  43849. const AffineTransform& transform, bool fillEntireClipAsTiles);
  43850. void drawLine (const Line <float>& line);
  43851. void drawVerticalLine (int x, float top, float bottom);
  43852. void drawHorizontalLine (int x, float top, float bottom);
  43853. const Font getFont();
  43854. void setFont (const Font& newFont);
  43855. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  43856. juce_UseDebuggingNewOperator
  43857. protected:
  43858. OutputStream& out;
  43859. int totalWidth, totalHeight;
  43860. bool needToClip;
  43861. Colour lastColour;
  43862. struct SavedState
  43863. {
  43864. SavedState();
  43865. ~SavedState();
  43866. RectangleList clip;
  43867. int xOffset, yOffset;
  43868. FillType fillType;
  43869. Font font;
  43870. private:
  43871. SavedState& operator= (const SavedState&);
  43872. };
  43873. OwnedArray <SavedState> stateStack;
  43874. void writeClip();
  43875. void writeColour (const Colour& colour);
  43876. void writePath (const Path& path) const;
  43877. void writeXY (float x, float y) const;
  43878. void writeTransform (const AffineTransform& trans) const;
  43879. void writeImage (const Image& im, int sx, int sy, int maxW, int maxH) const;
  43880. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  43881. LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  43882. };
  43883. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  43884. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  43885. #endif
  43886. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  43887. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  43888. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  43889. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  43890. /**
  43891. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  43892. its rendering in memory.
  43893. User code is not supposed to create instances of this class directly - do all your
  43894. rendering via the Graphics class instead.
  43895. */
  43896. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  43897. {
  43898. public:
  43899. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn);
  43900. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn, int xOffset, int yOffset, const RectangleList& initialClip);
  43901. ~LowLevelGraphicsSoftwareRenderer();
  43902. bool isVectorDevice() const;
  43903. void setOrigin (int x, int y);
  43904. bool clipToRectangle (const Rectangle<int>& r);
  43905. bool clipToRectangleList (const RectangleList& clipRegion);
  43906. void excludeClipRectangle (const Rectangle<int>& r);
  43907. void clipToPath (const Path& path, const AffineTransform& transform);
  43908. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform);
  43909. bool clipRegionIntersects (const Rectangle<int>& r);
  43910. const Rectangle<int> getClipBounds() const;
  43911. bool isClipEmpty() const;
  43912. void saveState();
  43913. void restoreState();
  43914. void setFill (const FillType& fillType);
  43915. void setOpacity (float opacity);
  43916. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  43917. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  43918. void fillPath (const Path& path, const AffineTransform& transform);
  43919. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  43920. const AffineTransform& transform, bool fillEntireClipAsTiles);
  43921. void drawLine (const Line <float>& line);
  43922. void drawVerticalLine (int x, float top, float bottom);
  43923. void drawHorizontalLine (int x, float top, float bottom);
  43924. void setFont (const Font& newFont);
  43925. const Font getFont();
  43926. void drawGlyph (int glyphNumber, float x, float y);
  43927. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  43928. juce_UseDebuggingNewOperator
  43929. protected:
  43930. Image image;
  43931. class GlyphCache;
  43932. class CachedGlyph;
  43933. class SavedState;
  43934. friend class ScopedPointer <SavedState>;
  43935. friend class OwnedArray <SavedState>;
  43936. friend class OwnedArray <CachedGlyph>;
  43937. ScopedPointer <SavedState> currentState;
  43938. OwnedArray <SavedState> stateStack;
  43939. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  43940. LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  43941. };
  43942. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  43943. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  43944. #endif
  43945. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  43946. #endif
  43947. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  43948. #endif
  43949. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  43950. /*** Start of inlined file: juce_DrawableComposite.h ***/
  43951. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  43952. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  43953. /**
  43954. A drawable object which acts as a container for a set of other Drawables.
  43955. @see Drawable
  43956. */
  43957. class JUCE_API DrawableComposite : public Drawable,
  43958. public RelativeCoordinate::NamedCoordinateFinder
  43959. {
  43960. public:
  43961. /** Creates a composite Drawable. */
  43962. DrawableComposite();
  43963. /** Creates a copy of a DrawableComposite. */
  43964. DrawableComposite (const DrawableComposite& other);
  43965. /** Destructor. */
  43966. ~DrawableComposite();
  43967. /** Adds a new sub-drawable to this one.
  43968. This passes in a Drawable pointer for this object to look after. To add a copy
  43969. of a drawable, use the form of this method that takes a Drawable reference instead.
  43970. @param drawable the object to add - this will be deleted automatically
  43971. when no longer needed, so the caller mustn't keep any
  43972. pointers to it.
  43973. @param index where to insert it in the list of drawables. 0 is the back,
  43974. -1 is the front, or any value from 0 and getNumDrawables()
  43975. can be used
  43976. @see removeDrawable
  43977. */
  43978. void insertDrawable (Drawable* drawable, int index = -1);
  43979. /** Adds a new sub-drawable to this one.
  43980. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  43981. for this object to look after, use the form of this method that takes a Drawable
  43982. pointer instead.
  43983. @param drawable the object to add - an internal copy will be made of this object
  43984. @param index where to insert it in the list of drawables. 0 is the back,
  43985. -1 is the front, or any value from 0 and getNumDrawables()
  43986. can be used
  43987. @see removeDrawable
  43988. */
  43989. void insertDrawable (const Drawable& drawable, int index = -1);
  43990. /** Deletes one of the Drawable objects.
  43991. @param index the index of the drawable to delete, between 0
  43992. and (getNumDrawables() - 1).
  43993. @param deleteDrawable if this is true, the drawable that is removed will also
  43994. be deleted. If false, it'll just be removed.
  43995. @see insertDrawable, getNumDrawables
  43996. */
  43997. void removeDrawable (int index, bool deleteDrawable = true);
  43998. /** Returns the number of drawables contained inside this one.
  43999. @see getDrawable
  44000. */
  44001. int getNumDrawables() const throw() { return drawables.size(); }
  44002. /** Returns one of the drawables that are contained in this one.
  44003. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  44004. to find it.
  44005. The pointer returned is managed by this object and will be deleted when no longer
  44006. needed, so be careful what you do with it.
  44007. @see getNumDrawables
  44008. */
  44009. Drawable* getDrawable (int index) const throw() { return drawables [index]; }
  44010. /** Looks for a child drawable with the specified name. */
  44011. Drawable* getDrawableWithName (const String& name) const throw();
  44012. /** Brings one of the Drawables to the front.
  44013. @param index the index of the drawable to move, between 0
  44014. and (getNumDrawables() - 1).
  44015. @see insertDrawable, getNumDrawables
  44016. */
  44017. void bringToFront (int index);
  44018. /** Changes the main content area.
  44019. The content area is actually defined by the markers named "left", "right", "top" and
  44020. "bottom", but this method is a shortcut that sets them all at once.
  44021. @see contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  44022. */
  44023. const RelativeRectangle getContentArea() const;
  44024. /** Returns the main content rectangle.
  44025. The content area is actually defined by the markers named "left", "right", "top" and
  44026. "bottom", but this method is a shortcut that returns them all at once.
  44027. @see setBoundingBox, contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  44028. */
  44029. void setContentArea (const RelativeRectangle& newArea);
  44030. /** Sets the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  44031. @see setContentArea
  44032. */
  44033. void setBoundingBox (const RelativeParallelogram& newBoundingBox);
  44034. /** Returns the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  44035. @see setBoundingBox
  44036. */
  44037. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  44038. /** Changes the bounding box transform to match the content area, so that any sub-items will
  44039. be drawn at their untransformed positions.
  44040. */
  44041. void resetBoundingBoxToContentArea();
  44042. /** Represents a named marker position.
  44043. @see DrawableComposite::getMarker
  44044. */
  44045. struct Marker
  44046. {
  44047. Marker (const Marker&);
  44048. Marker (const String& name, const RelativeCoordinate& position);
  44049. bool operator!= (const Marker&) const throw();
  44050. String name;
  44051. RelativeCoordinate position;
  44052. };
  44053. int getNumMarkers (bool xAxis) const throw();
  44054. const Marker* getMarker (bool xAxis, int index) const throw();
  44055. void setMarker (const String& name, bool xAxis, const RelativeCoordinate& position);
  44056. void removeMarker (bool xAxis, int index);
  44057. /** The name of the marker that defines the left edge of the content area. */
  44058. static const char* const contentLeftMarkerName;
  44059. /** The name of the marker that defines the right edge of the content area. */
  44060. static const char* const contentRightMarkerName;
  44061. /** The name of the marker that defines the top edge of the content area. */
  44062. static const char* const contentTopMarkerName;
  44063. /** The name of the marker that defines the bottom edge of the content area. */
  44064. static const char* const contentBottomMarkerName;
  44065. /** @internal */
  44066. void render (const Drawable::RenderingContext& context) const;
  44067. /** @internal */
  44068. const Rectangle<float> getBounds() const;
  44069. /** @internal */
  44070. bool hitTest (float x, float y) const;
  44071. /** @internal */
  44072. Drawable* createCopy() const;
  44073. /** @internal */
  44074. void invalidatePoints();
  44075. /** @internal */
  44076. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44077. /** @internal */
  44078. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44079. /** @internal */
  44080. static const Identifier valueTreeType;
  44081. /** @internal */
  44082. const Identifier getValueTreeType() const { return valueTreeType; }
  44083. /** @internal */
  44084. const RelativeCoordinate findNamedCoordinate (const String& objectName, const String& edge) const;
  44085. /** Internally-used class for wrapping a DrawableComposite's state into a ValueTree. */
  44086. class ValueTreeWrapper : public ValueTreeWrapperBase
  44087. {
  44088. public:
  44089. ValueTreeWrapper (const ValueTree& state);
  44090. int getNumDrawables() const;
  44091. ValueTree getDrawableState (int index) const;
  44092. ValueTree getDrawableWithId (const String& objectId, bool recursive) const;
  44093. int indexOfDrawable (const ValueTree& item) const;
  44094. void addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager);
  44095. void moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager);
  44096. void removeDrawable (const ValueTree& child, UndoManager* undoManager);
  44097. const RelativeParallelogram getBoundingBox() const;
  44098. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  44099. void resetBoundingBoxToContentArea (UndoManager* undoManager);
  44100. const RelativeRectangle getContentArea() const;
  44101. void setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager);
  44102. int getNumMarkers (bool xAxis) const;
  44103. const ValueTree getMarkerState (bool xAxis, int index) const;
  44104. const ValueTree getMarkerState (bool xAxis, const String& name) const;
  44105. bool containsMarker (bool xAxis, const ValueTree& state) const;
  44106. const Marker getMarker (bool xAxis, const ValueTree& state) const;
  44107. void setMarker (bool xAxis, const Marker& marker, UndoManager* undoManager);
  44108. void removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager);
  44109. static const Identifier nameProperty, posProperty;
  44110. private:
  44111. static const Identifier topLeft, topRight, bottomLeft, childGroupTag, markerGroupTagX,
  44112. markerGroupTagY, markerTag;
  44113. ValueTree getChildList() const;
  44114. ValueTree getChildListCreating (UndoManager* undoManager);
  44115. ValueTree getMarkerList (bool xAxis) const;
  44116. ValueTree getMarkerListCreating (bool xAxis, UndoManager* undoManager);
  44117. };
  44118. juce_UseDebuggingNewOperator
  44119. private:
  44120. OwnedArray <Drawable> drawables;
  44121. RelativeParallelogram bounds;
  44122. OwnedArray <Marker> markersX, markersY;
  44123. const Rectangle<float> getUntransformedBounds() const;
  44124. const AffineTransform calculateTransform() const;
  44125. DrawableComposite& operator= (const DrawableComposite&);
  44126. };
  44127. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  44128. /*** End of inlined file: juce_DrawableComposite.h ***/
  44129. #endif
  44130. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44131. /*** Start of inlined file: juce_DrawableImage.h ***/
  44132. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44133. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44134. /**
  44135. A drawable object which is a bitmap image.
  44136. @see Drawable
  44137. */
  44138. class JUCE_API DrawableImage : public Drawable
  44139. {
  44140. public:
  44141. DrawableImage();
  44142. DrawableImage (const DrawableImage& other);
  44143. /** Destructor. */
  44144. ~DrawableImage();
  44145. /** Sets the image that this drawable will render. */
  44146. void setImage (const Image& imageToUse);
  44147. /** Returns the current image. */
  44148. const Image getImage() const { return image; }
  44149. /** Sets the opacity to use when drawing the image. */
  44150. void setOpacity (float newOpacity);
  44151. /** Returns the image's opacity. */
  44152. float getOpacity() const throw() { return opacity; }
  44153. /** Sets a colour to draw over the image's alpha channel.
  44154. By default this is transparent so isn't drawn, but if you set a non-transparent
  44155. colour here, then it will be overlaid on the image, using the image's alpha
  44156. channel as a mask.
  44157. This is handy for doing things like darkening or lightening an image by overlaying
  44158. it with semi-transparent black or white.
  44159. */
  44160. void setOverlayColour (const Colour& newOverlayColour);
  44161. /** Returns the overlay colour. */
  44162. const Colour& getOverlayColour() const throw() { return overlayColour; }
  44163. /** Sets the bounding box within which the image should be displayed. */
  44164. void setBoundingBox (const RelativeParallelogram& newBounds);
  44165. /** Returns the position to which the image's top-left corner should be remapped in the target
  44166. coordinate space when rendering this object.
  44167. @see setTransform
  44168. */
  44169. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  44170. /** @internal */
  44171. void render (const Drawable::RenderingContext& context) const;
  44172. /** @internal */
  44173. const Rectangle<float> getBounds() const;
  44174. /** @internal */
  44175. bool hitTest (float x, float y) const;
  44176. /** @internal */
  44177. Drawable* createCopy() const;
  44178. /** @internal */
  44179. void invalidatePoints();
  44180. /** @internal */
  44181. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44182. /** @internal */
  44183. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44184. /** @internal */
  44185. static const Identifier valueTreeType;
  44186. /** @internal */
  44187. const Identifier getValueTreeType() const { return valueTreeType; }
  44188. /** Internally-used class for wrapping a DrawableImage's state into a ValueTree. */
  44189. class ValueTreeWrapper : public ValueTreeWrapperBase
  44190. {
  44191. public:
  44192. ValueTreeWrapper (const ValueTree& state);
  44193. const var getImageIdentifier() const;
  44194. void setImageIdentifier (const var& newIdentifier, UndoManager* undoManager);
  44195. Value getImageIdentifierValue (UndoManager* undoManager);
  44196. float getOpacity() const;
  44197. void setOpacity (float newOpacity, UndoManager* undoManager);
  44198. Value getOpacityValue (UndoManager* undoManager);
  44199. const Colour getOverlayColour() const;
  44200. void setOverlayColour (const Colour& newColour, UndoManager* undoManager);
  44201. Value getOverlayColourValue (UndoManager* undoManager);
  44202. const RelativeParallelogram getBoundingBox() const;
  44203. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  44204. static const Identifier opacity, overlay, image, topLeft, topRight, bottomLeft;
  44205. };
  44206. juce_UseDebuggingNewOperator
  44207. private:
  44208. Image image;
  44209. float opacity;
  44210. Colour overlayColour;
  44211. RelativeParallelogram bounds;
  44212. const AffineTransform calculateTransform() const;
  44213. DrawableImage& operator= (const DrawableImage&);
  44214. };
  44215. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44216. /*** End of inlined file: juce_DrawableImage.h ***/
  44217. #endif
  44218. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  44219. /*** Start of inlined file: juce_DrawablePath.h ***/
  44220. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  44221. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  44222. /**
  44223. A drawable object which renders a filled or outlined shape.
  44224. @see Drawable
  44225. */
  44226. class JUCE_API DrawablePath : public Drawable
  44227. {
  44228. public:
  44229. /** Creates a DrawablePath. */
  44230. DrawablePath();
  44231. DrawablePath (const DrawablePath& other);
  44232. /** Destructor. */
  44233. ~DrawablePath();
  44234. /** Changes the path that will be drawn.
  44235. @see setFillColour, setStrokeType
  44236. */
  44237. void setPath (const Path& newPath);
  44238. /** Sets a fill type for the path.
  44239. This colour is used to fill the path - if you don't want the path to be
  44240. filled (e.g. if you're just drawing an outline), set this to a transparent
  44241. colour.
  44242. @see setPath, setStrokeFill
  44243. */
  44244. void setFill (const FillType& newFill);
  44245. /** Returns the current fill type.
  44246. @see setFill
  44247. */
  44248. const FillType& getFill() const throw() { return mainFill; }
  44249. /** Sets the fill type with which the outline will be drawn.
  44250. @see setFill
  44251. */
  44252. void setStrokeFill (const FillType& newStrokeFill);
  44253. /** Returns the current stroke fill.
  44254. @see setStrokeFill
  44255. */
  44256. const FillType& getStrokeFill() const throw() { return strokeFill; }
  44257. /** Changes the properties of the outline that will be drawn around the path.
  44258. If the stroke has 0 thickness, no stroke will be drawn.
  44259. @see setStrokeThickness, setStrokeColour
  44260. */
  44261. void setStrokeType (const PathStrokeType& newStrokeType);
  44262. /** Changes the stroke thickness.
  44263. This is a shortcut for calling setStrokeType.
  44264. */
  44265. void setStrokeThickness (float newThickness);
  44266. /** Returns the current outline style. */
  44267. const PathStrokeType& getStrokeType() const throw() { return strokeType; }
  44268. /** Returns the current path. */
  44269. const Path& getPath() const;
  44270. /** Returns the current path for the outline. */
  44271. const Path& getStrokePath() const;
  44272. /** @internal */
  44273. void render (const Drawable::RenderingContext& context) const;
  44274. /** @internal */
  44275. const Rectangle<float> getBounds() const;
  44276. /** @internal */
  44277. bool hitTest (float x, float y) const;
  44278. /** @internal */
  44279. Drawable* createCopy() const;
  44280. /** @internal */
  44281. void invalidatePoints();
  44282. /** @internal */
  44283. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44284. /** @internal */
  44285. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44286. /** @internal */
  44287. static const Identifier valueTreeType;
  44288. /** @internal */
  44289. const Identifier getValueTreeType() const { return valueTreeType; }
  44290. /** Internally-used class for wrapping a DrawablePath's state into a ValueTree. */
  44291. class ValueTreeWrapper : public ValueTreeWrapperBase
  44292. {
  44293. public:
  44294. ValueTreeWrapper (const ValueTree& state);
  44295. const FillType getMainFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  44296. ImageProvider* imageProvider) const;
  44297. ValueTree getMainFillState();
  44298. void setMainFill (const FillType& newFill, const RelativePoint* gradientPoint1, const RelativePoint* gradientPoint2,
  44299. ImageProvider* imageProvider, UndoManager* undoManager);
  44300. const FillType getStrokeFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  44301. ImageProvider* imageProvider) const;
  44302. ValueTree getStrokeFillState();
  44303. void setStrokeFill (const FillType& newFill, const RelativePoint* gradientPoint1, const RelativePoint* gradientPoint2,
  44304. ImageProvider* imageProvider, UndoManager* undoManager);
  44305. const PathStrokeType getStrokeType() const;
  44306. void setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager);
  44307. bool usesNonZeroWinding() const;
  44308. void setUsesNonZeroWinding (bool b, UndoManager* undoManager);
  44309. class Element
  44310. {
  44311. public:
  44312. explicit Element (const ValueTree& state);
  44313. ~Element();
  44314. const Identifier getType() const throw() { return state.getType(); }
  44315. int getNumControlPoints() const throw();
  44316. const RelativePoint getControlPoint (int index) const;
  44317. Value getControlPointValue (int index, UndoManager* undoManager) const;
  44318. const RelativePoint getEndPoint() const;
  44319. void setControlPoint (int index, const RelativePoint& point, UndoManager* undoManager);
  44320. ValueTreeWrapper getParent() const;
  44321. static const Identifier startSubPathElement, closeSubPathElement,
  44322. lineToElement, quadraticToElement, cubicToElement;
  44323. ValueTree state;
  44324. };
  44325. ValueTree getPathState();
  44326. static const Identifier fill, stroke, path, jointStyle, capStyle, strokeWidth,
  44327. nonZeroWinding, point1, point2, point3;
  44328. };
  44329. juce_UseDebuggingNewOperator
  44330. private:
  44331. FillType mainFill, strokeFill;
  44332. PathStrokeType strokeType;
  44333. ScopedPointer<RelativePointPath> relativePath;
  44334. mutable Path path, stroke;
  44335. mutable bool pathNeedsUpdating, strokeNeedsUpdating;
  44336. void updatePath() const;
  44337. void updateStroke() const;
  44338. bool isStrokeVisible() const throw();
  44339. DrawablePath& operator= (const DrawablePath&);
  44340. };
  44341. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  44342. /*** End of inlined file: juce_DrawablePath.h ***/
  44343. #endif
  44344. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  44345. /*** Start of inlined file: juce_DrawableText.h ***/
  44346. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  44347. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  44348. /**
  44349. A drawable object which renders a line of text.
  44350. @see Drawable
  44351. */
  44352. class JUCE_API DrawableText : public Drawable
  44353. {
  44354. public:
  44355. /** Creates a DrawableText object. */
  44356. DrawableText();
  44357. DrawableText (const DrawableText& other);
  44358. /** Destructor. */
  44359. ~DrawableText();
  44360. /** Sets the text to display.*/
  44361. void setText (const String& newText);
  44362. /** Sets the colour of the text. */
  44363. void setColour (const Colour& newColour);
  44364. /** Returns the current text colour. */
  44365. const Colour& getColour() const throw() { return colour; }
  44366. /** Sets the font to use.
  44367. Note that the font height and horizontal scale are actually based upon the position
  44368. of the fontSizeAndScaleAnchor parameter to setBounds(). If applySizeAndScale is true, then
  44369. the height and scale control point will be moved to match the dimensions of the font supplied;
  44370. if it is false, then the new font's height and scale are ignored.
  44371. */
  44372. void setFont (const Font& newFont, bool applySizeAndScale);
  44373. /** Changes the justification of the text within the bounding box. */
  44374. void setJustification (const Justification& newJustification);
  44375. /** Returns the parallelogram that defines the text bounding box. */
  44376. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  44377. /** Sets the bounding box that contains the text. */
  44378. void setBoundingBox (const RelativeParallelogram& newBounds);
  44379. /** Returns the point within the bounds that defines the font's size and scale. */
  44380. const RelativePoint& getFontSizeControlPoint() const throw() { return fontSizeControlPoint; }
  44381. /** Sets the control point that defines the font's height and horizontal scale.
  44382. This position is a point within the bounding box parallelogram, whose Y position (relative
  44383. to the parallelogram's origin and possibly distorted shape) specifies the font's height,
  44384. and its X defines the font's horizontal scale.
  44385. */
  44386. void setFontSizeControlPoint (const RelativePoint& newPoint);
  44387. /** @internal */
  44388. void render (const Drawable::RenderingContext& context) const;
  44389. /** @internal */
  44390. const Rectangle<float> getBounds() const;
  44391. /** @internal */
  44392. bool hitTest (float x, float y) const;
  44393. /** @internal */
  44394. Drawable* createCopy() const;
  44395. /** @internal */
  44396. void invalidatePoints();
  44397. /** @internal */
  44398. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44399. /** @internal */
  44400. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44401. /** @internal */
  44402. static const Identifier valueTreeType;
  44403. /** @internal */
  44404. const Identifier getValueTreeType() const { return valueTreeType; }
  44405. /** Internally-used class for wrapping a DrawableText's state into a ValueTree. */
  44406. class ValueTreeWrapper : public ValueTreeWrapperBase
  44407. {
  44408. public:
  44409. ValueTreeWrapper (const ValueTree& state);
  44410. const String getText() const;
  44411. void setText (const String& newText, UndoManager* undoManager);
  44412. Value getTextValue (UndoManager* undoManager);
  44413. const Colour getColour() const;
  44414. void setColour (const Colour& newColour, UndoManager* undoManager);
  44415. const Justification getJustification() const;
  44416. void setJustification (const Justification& newJustification, UndoManager* undoManager);
  44417. const Font getFont() const;
  44418. void setFont (const Font& newFont, UndoManager* undoManager);
  44419. Value getFontValue (UndoManager* undoManager);
  44420. const RelativeParallelogram getBoundingBox() const;
  44421. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  44422. const RelativePoint getFontSizeAndScaleAnchor() const;
  44423. void setFontSizeAndScaleAnchor (const RelativePoint& p, UndoManager* undoManager);
  44424. static const Identifier text, colour, font, justification, topLeft, topRight, bottomLeft, fontSizeAnchor;
  44425. };
  44426. juce_UseDebuggingNewOperator
  44427. private:
  44428. RelativeParallelogram bounds;
  44429. RelativePoint fontSizeControlPoint;
  44430. Font font;
  44431. String text;
  44432. Colour colour;
  44433. Justification justification;
  44434. DrawableText& operator= (const DrawableText&);
  44435. };
  44436. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  44437. /*** End of inlined file: juce_DrawableText.h ***/
  44438. #endif
  44439. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  44440. #endif
  44441. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  44442. /*** Start of inlined file: juce_GlowEffect.h ***/
  44443. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  44444. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  44445. /**
  44446. A component effect that adds a coloured blur around the component's contents.
  44447. (This will only work on non-opaque components).
  44448. @see Component::setComponentEffect, DropShadowEffect
  44449. */
  44450. class JUCE_API GlowEffect : public ImageEffectFilter
  44451. {
  44452. public:
  44453. /** Creates a default 'glow' effect.
  44454. To customise its appearance, use the setGlowProperties() method.
  44455. */
  44456. GlowEffect();
  44457. /** Destructor. */
  44458. ~GlowEffect();
  44459. /** Sets the glow's radius and colour.
  44460. The radius is how large the blur should be, and the colour is
  44461. used to render it (for a less intense glow, lower the colour's
  44462. opacity).
  44463. */
  44464. void setGlowProperties (float newRadius,
  44465. const Colour& newColour);
  44466. /** @internal */
  44467. void applyEffect (Image& sourceImage, Graphics& destContext);
  44468. juce_UseDebuggingNewOperator
  44469. private:
  44470. float radius;
  44471. Colour colour;
  44472. };
  44473. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  44474. /*** End of inlined file: juce_GlowEffect.h ***/
  44475. #endif
  44476. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  44477. #endif
  44478. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44479. /*** Start of inlined file: juce_ReduceOpacityEffect.h ***/
  44480. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44481. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44482. /**
  44483. An effect filter that reduces the image's opacity.
  44484. This can be used to make a component (and its child components) more
  44485. transparent.
  44486. @see Component::setComponentEffect
  44487. */
  44488. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  44489. {
  44490. public:
  44491. /** Creates the effect object.
  44492. The opacity of the component to which the effect is applied will be
  44493. scaled by the given factor (in the range 0 to 1.0f).
  44494. */
  44495. ReduceOpacityEffect (float opacity = 1.0f);
  44496. /** Destructor. */
  44497. ~ReduceOpacityEffect();
  44498. /** Sets how much to scale the component's opacity.
  44499. @param newOpacity should be between 0 and 1.0f
  44500. */
  44501. void setOpacity (float newOpacity);
  44502. /** @internal */
  44503. void applyEffect (Image& sourceImage, Graphics& destContext);
  44504. juce_UseDebuggingNewOperator
  44505. private:
  44506. float opacity;
  44507. };
  44508. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44509. /*** End of inlined file: juce_ReduceOpacityEffect.h ***/
  44510. #endif
  44511. #ifndef __JUCE_FONT_JUCEHEADER__
  44512. #endif
  44513. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  44514. #endif
  44515. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  44516. #endif
  44517. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  44518. #endif
  44519. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  44520. #endif
  44521. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  44522. #endif
  44523. #ifndef __JUCE_LINE_JUCEHEADER__
  44524. #endif
  44525. #ifndef __JUCE_PATH_JUCEHEADER__
  44526. #endif
  44527. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  44528. /*** Start of inlined file: juce_PathIterator.h ***/
  44529. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  44530. #define __JUCE_PATHITERATOR_JUCEHEADER__
  44531. /**
  44532. Flattens a Path object into a series of straight-line sections.
  44533. Use one of these to iterate through a Path object, and it will convert
  44534. all the curves into line sections so it's easy to render or perform
  44535. geometric operations on.
  44536. @see Path
  44537. */
  44538. class JUCE_API PathFlatteningIterator
  44539. {
  44540. public:
  44541. /** Creates a PathFlatteningIterator.
  44542. After creation, use the next() method to initialise the fields in the
  44543. object with the first line's position.
  44544. @param path the path to iterate along
  44545. @param transform a transform to apply to each point in the path being iterated
  44546. @param tolerence the amount by which the curves are allowed to deviate from the
  44547. lines into which they are being broken down - a higher tolerence
  44548. is a bit faster, but less smooth.
  44549. */
  44550. PathFlatteningIterator (const Path& path,
  44551. const AffineTransform& transform = AffineTransform::identity,
  44552. float tolerence = 6.0f);
  44553. /** Destructor. */
  44554. ~PathFlatteningIterator();
  44555. /** Fetches the next line segment from the path.
  44556. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  44557. so that they describe the new line segment.
  44558. @returns false when there are no more lines to fetch.
  44559. */
  44560. bool next();
  44561. float x1; /**< The x position of the start of the current line segment. */
  44562. float y1; /**< The y position of the start of the current line segment. */
  44563. float x2; /**< The x position of the end of the current line segment. */
  44564. float y2; /**< The y position of the end of the current line segment. */
  44565. /** Indicates whether the current line segment is closing a sub-path.
  44566. If the current line is the one that connects the end of a sub-path
  44567. back to the start again, this will be true.
  44568. */
  44569. bool closesSubPath;
  44570. /** The index of the current line within the current sub-path.
  44571. E.g. you can use this to see whether the line is the first one in the
  44572. subpath by seeing if it's 0.
  44573. */
  44574. int subPathIndex;
  44575. /** Returns true if the current segment is the last in the current sub-path. */
  44576. bool isLastInSubpath() const throw() { return stackPos == stackBase.getData()
  44577. && (index >= path.numElements || points [index] == Path::moveMarker); }
  44578. juce_UseDebuggingNewOperator
  44579. private:
  44580. const Path& path;
  44581. const AffineTransform transform;
  44582. float* points;
  44583. float tolerence, subPathCloseX, subPathCloseY;
  44584. const bool isIdentityTransform;
  44585. HeapBlock <float> stackBase;
  44586. float* stackPos;
  44587. size_t index, stackSize;
  44588. PathFlatteningIterator (const PathFlatteningIterator&);
  44589. PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  44590. };
  44591. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  44592. /*** End of inlined file: juce_PathIterator.h ***/
  44593. #endif
  44594. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  44595. #endif
  44596. #ifndef __JUCE_POINT_JUCEHEADER__
  44597. #endif
  44598. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  44599. /*** Start of inlined file: juce_PositionedRectangle.h ***/
  44600. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  44601. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  44602. /**
  44603. A rectangle whose co-ordinates can be defined in terms of absolute or
  44604. proportional distances.
  44605. Designed mainly for storing component positions, this gives you a lot of
  44606. control over how each co-ordinate is stored, either as an absolute position,
  44607. or as a proportion of the size of a parent rectangle.
  44608. It also allows you to define the anchor points by which the rectangle is
  44609. positioned, so for example you could specify that the top right of the
  44610. rectangle should be an absolute distance from its parent's bottom-right corner.
  44611. This object can be stored as a string, which takes the form "x y w h", including
  44612. symbols like '%' and letters to indicate the anchor point. See its toString()
  44613. method for more info.
  44614. Example usage:
  44615. @code
  44616. class MyComponent
  44617. {
  44618. void resized()
  44619. {
  44620. // this will set the child component's x to be 20% of our width, its y
  44621. // to be 30, its width to be 150, and its height to be 50% of our
  44622. // height..
  44623. const PositionedRectangle pos1 ("20% 30 150 50%");
  44624. pos1.applyToComponent (*myChildComponent1);
  44625. // this will inset the child component with a gap of 10 pixels
  44626. // around each of its edges..
  44627. const PositionedRectangle pos2 ("10 10 20M 20M");
  44628. pos2.applyToComponent (*myChildComponent2);
  44629. }
  44630. };
  44631. @endcode
  44632. */
  44633. class JUCE_API PositionedRectangle
  44634. {
  44635. public:
  44636. /** Creates an empty rectangle with all co-ordinates set to zero.
  44637. The default anchor point is top-left; the default
  44638. */
  44639. PositionedRectangle() throw();
  44640. /** Initialises a PositionedRectangle from a saved string version.
  44641. The string must be in the format generated by toString().
  44642. */
  44643. PositionedRectangle (const String& stringVersion) throw();
  44644. /** Creates a copy of another PositionedRectangle. */
  44645. PositionedRectangle (const PositionedRectangle& other) throw();
  44646. /** Copies another PositionedRectangle. */
  44647. PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  44648. /** Destructor. */
  44649. ~PositionedRectangle() throw();
  44650. /** Returns a string version of this position, from which it can later be
  44651. re-generated.
  44652. The format is four co-ordinates, "x y w h".
  44653. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  44654. - If a co-ordinate is proportional to its parent's width or height, it is stored
  44655. as a percentage, e.g. "80%".
  44656. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  44657. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  44658. the parent's right-hand edge.
  44659. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  44660. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  44661. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  44662. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  44663. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  44664. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  44665. has "c" appended to it. So "-50Rc" would mean that this component's
  44666. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  44667. this component's centre should be placed 40% across the parent's width.
  44668. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  44669. the number has "M" appended to it.
  44670. To reload a stored string, use the constructor that takes a string parameter.
  44671. */
  44672. const String toString() const throw();
  44673. /** Calculates the absolute position, given the size of the space that
  44674. it should go in.
  44675. This will work out any proportional distances and sizes relative to the
  44676. target rectangle, and will return the absolute position.
  44677. @see applyToComponent
  44678. */
  44679. const Rectangle<int> getRectangle (const Rectangle<int>& targetSpaceToBeRelativeTo) const throw();
  44680. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  44681. */
  44682. void getRectangleDouble (const Rectangle<int>& targetSpaceToBeRelativeTo,
  44683. double& x,
  44684. double& y,
  44685. double& width,
  44686. double& height) const throw();
  44687. /** This sets the bounds of the given component to this position.
  44688. This is equivalent to writing:
  44689. @code
  44690. comp.setBounds (getRectangle (Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  44691. @endcode
  44692. @see getRectangle, updateFromComponent
  44693. */
  44694. void applyToComponent (Component& comp) const throw();
  44695. /** Updates this object's co-ordinates to match the given rectangle.
  44696. This will set all co-ordinates based on the given rectangle, re-calculating
  44697. any proportional distances, and using the current anchor points.
  44698. So for example if the x co-ordinate mode is currently proportional, this will
  44699. re-calculate x based on the rectangle's relative position within the target
  44700. rectangle's width.
  44701. If the target rectangle's width or height are zero then it may not be possible
  44702. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  44703. will not be changed.
  44704. */
  44705. void updateFrom (const Rectangle<int>& newPosition,
  44706. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  44707. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  44708. */
  44709. void updateFromDouble (double x, double y, double width, double height,
  44710. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  44711. /** Updates this object's co-ordinates to match the bounds of this component.
  44712. This is equivalent to calling updateFrom() with the component's bounds and
  44713. it parent size.
  44714. If the component doesn't currently have a parent, then proportional co-ordinates
  44715. might not be updated because it would need to know the parent's size to do the
  44716. maths for this.
  44717. */
  44718. void updateFromComponent (const Component& comp) throw();
  44719. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  44720. enum AnchorPoint
  44721. {
  44722. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  44723. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  44724. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  44725. };
  44726. /** Specifies how an x or y co-ordinate should be interpreted. */
  44727. enum PositionMode
  44728. {
  44729. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  44730. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  44731. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  44732. 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. */
  44733. };
  44734. /** Specifies how the width or height should be interpreted. */
  44735. enum SizeMode
  44736. {
  44737. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  44738. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  44739. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  44740. };
  44741. /** Sets all options for all co-ordinates.
  44742. This requires a reference rectangle to be specified, because if you're changing any
  44743. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  44744. the co-ordinates, and will need to know the parent size so it can calculate this.
  44745. */
  44746. void setModes (const AnchorPoint xAnchorMode,
  44747. const PositionMode xPositionMode,
  44748. const AnchorPoint yAnchorMode,
  44749. const PositionMode yPositionMode,
  44750. const SizeMode widthMode,
  44751. const SizeMode heightMode,
  44752. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  44753. /** Returns the anchoring mode for the x co-ordinate.
  44754. To change any of the modes, use setModes().
  44755. */
  44756. AnchorPoint getAnchorPointX() const throw();
  44757. /** Returns the positioning mode for the x co-ordinate.
  44758. To change any of the modes, use setModes().
  44759. */
  44760. PositionMode getPositionModeX() const throw();
  44761. /** Returns the raw x co-ordinate.
  44762. If the x position mode is absolute, then this will be the absolute value. If it's
  44763. proportional, then this will be a fractional proportion, where 1.0 means the full
  44764. width of the parent space.
  44765. */
  44766. double getX() const throw() { return x; }
  44767. /** Sets the raw value of the x co-ordinate.
  44768. See getX() for the meaning of this value.
  44769. */
  44770. void setX (const double newX) throw() { x = newX; }
  44771. /** Returns the anchoring mode for the y co-ordinate.
  44772. To change any of the modes, use setModes().
  44773. */
  44774. AnchorPoint getAnchorPointY() const throw();
  44775. /** Returns the positioning mode for the y co-ordinate.
  44776. To change any of the modes, use setModes().
  44777. */
  44778. PositionMode getPositionModeY() const throw();
  44779. /** Returns the raw y co-ordinate.
  44780. If the y position mode is absolute, then this will be the absolute value. If it's
  44781. proportional, then this will be a fractional proportion, where 1.0 means the full
  44782. height of the parent space.
  44783. */
  44784. double getY() const throw() { return y; }
  44785. /** Sets the raw value of the y co-ordinate.
  44786. See getY() for the meaning of this value.
  44787. */
  44788. void setY (const double newY) throw() { y = newY; }
  44789. /** Returns the mode used to calculate the width.
  44790. To change any of the modes, use setModes().
  44791. */
  44792. SizeMode getWidthMode() const throw();
  44793. /** Returns the raw width value.
  44794. If the width mode is absolute, then this will be the absolute value. If the mode is
  44795. proportional, then this will be a fractional proportion, where 1.0 means the full
  44796. width of the parent space.
  44797. */
  44798. double getWidth() const throw() { return w; }
  44799. /** Sets the raw width value.
  44800. See getWidth() for the details about what this value means.
  44801. */
  44802. void setWidth (const double newWidth) throw() { w = newWidth; }
  44803. /** Returns the mode used to calculate the height.
  44804. To change any of the modes, use setModes().
  44805. */
  44806. SizeMode getHeightMode() const throw();
  44807. /** Returns the raw height value.
  44808. If the height mode is absolute, then this will be the absolute value. If the mode is
  44809. proportional, then this will be a fractional proportion, where 1.0 means the full
  44810. height of the parent space.
  44811. */
  44812. double getHeight() const throw() { return h; }
  44813. /** Sets the raw height value.
  44814. See getHeight() for the details about what this value means.
  44815. */
  44816. void setHeight (const double newHeight) throw() { h = newHeight; }
  44817. /** If the size and position are constance, and wouldn't be affected by changes
  44818. in the parent's size, then this will return true.
  44819. */
  44820. bool isPositionAbsolute() const throw();
  44821. /** Compares two objects. */
  44822. bool operator== (const PositionedRectangle& other) const throw();
  44823. /** Compares two objects. */
  44824. bool operator!= (const PositionedRectangle& other) const throw();
  44825. juce_UseDebuggingNewOperator
  44826. private:
  44827. double x, y, w, h;
  44828. uint8 xMode, yMode, wMode, hMode;
  44829. void addPosDescription (String& result, uint8 mode, double value) const throw();
  44830. void addSizeDescription (String& result, uint8 mode, double value) const throw();
  44831. void decodePosString (const String& s, uint8& mode, double& value) throw();
  44832. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  44833. void applyPosAndSize (double& xOut, double& wOut, double x, double w,
  44834. uint8 xMode, uint8 wMode,
  44835. int parentPos, int parentSize) const throw();
  44836. void updatePosAndSize (double& xOut, double& wOut, double x, double w,
  44837. uint8 xMode, uint8 wMode,
  44838. int parentPos, int parentSize) const throw();
  44839. };
  44840. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  44841. /*** End of inlined file: juce_PositionedRectangle.h ***/
  44842. #endif
  44843. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  44844. #endif
  44845. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  44846. #endif
  44847. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  44848. #endif
  44849. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  44850. /*** Start of inlined file: juce_CameraDevice.h ***/
  44851. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  44852. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  44853. #if JUCE_USE_CAMERA
  44854. /**
  44855. Receives callbacks with images from a CameraDevice.
  44856. @see CameraDevice::addListener
  44857. */
  44858. class CameraImageListener
  44859. {
  44860. public:
  44861. CameraImageListener() {}
  44862. virtual ~CameraImageListener() {}
  44863. /** This method is called when a new image arrives.
  44864. This may be called by any thread, so be careful about thread-safety,
  44865. and make sure that you process the data as quickly as possible to
  44866. avoid glitching!
  44867. */
  44868. virtual void imageReceived (const Image& image) = 0;
  44869. };
  44870. /**
  44871. Controls any camera capture devices that might be available.
  44872. Use getAvailableDevices() to list the devices that are attached to the
  44873. system, then call openDevice to open one for use. Once you have a CameraDevice
  44874. object, you can get a viewer component from it, and use its methods to
  44875. stream to a file or capture still-frames.
  44876. */
  44877. class JUCE_API CameraDevice
  44878. {
  44879. public:
  44880. /** Destructor. */
  44881. virtual ~CameraDevice();
  44882. /** Returns a list of the available cameras on this machine.
  44883. You can open one of these devices by calling openDevice().
  44884. */
  44885. static const StringArray getAvailableDevices();
  44886. /** Opens a camera device.
  44887. The index parameter indicates which of the items returned by getAvailableDevices()
  44888. to open.
  44889. The size constraints allow the method to choose between different resolutions if
  44890. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  44891. then these will be ignored.
  44892. */
  44893. static CameraDevice* openDevice (int deviceIndex,
  44894. int minWidth = 128, int minHeight = 64,
  44895. int maxWidth = 1024, int maxHeight = 768);
  44896. /** Returns the name of this device */
  44897. const String getName() const { return name; }
  44898. /** Creates a component that can be used to display a preview of the
  44899. video from this camera.
  44900. */
  44901. Component* createViewerComponent();
  44902. /** Starts recording video to the specified file.
  44903. You should use getFileExtension() to find out the correct extension to
  44904. use for your filename.
  44905. If the file exists, it will be deleted before the recording starts.
  44906. This method may not start recording instantly, so if you need to know the
  44907. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  44908. after the recording has finished.
  44909. The quality parameter can be 0, 1, or 2, to indicate low, medium, or high. It may
  44910. or may not be used, depending on the driver.
  44911. */
  44912. void startRecordingToFile (const File& file, int quality = 2);
  44913. /** Stops recording, after a call to startRecordingToFile().
  44914. */
  44915. void stopRecording();
  44916. /** Returns the file extension that should be used for the files
  44917. that you pass to startRecordingToFile().
  44918. This may be platform-specific, e.g. ".mov" or ".avi".
  44919. */
  44920. static const String getFileExtension();
  44921. /** After calling stopRecording(), this method can be called to return the timestamp
  44922. of the first frame that was written to the file.
  44923. */
  44924. const Time getTimeOfFirstRecordedFrame() const;
  44925. /** Adds a listener to receive images from the camera.
  44926. Be very careful not to delete the listener without first removing it by calling
  44927. removeListener().
  44928. */
  44929. void addListener (CameraImageListener* listenerToAdd);
  44930. /** Removes a listener that was previously added with addListener().
  44931. */
  44932. void removeListener (CameraImageListener* listenerToRemove);
  44933. juce_UseDebuggingNewOperator
  44934. protected:
  44935. /** @internal */
  44936. CameraDevice (const String& name, int index);
  44937. private:
  44938. void* internal;
  44939. bool isRecording;
  44940. String name;
  44941. CameraDevice (const CameraDevice&);
  44942. CameraDevice& operator= (const CameraDevice&);
  44943. };
  44944. #endif
  44945. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  44946. /*** End of inlined file: juce_CameraDevice.h ***/
  44947. #endif
  44948. #ifndef __JUCE_IMAGE_JUCEHEADER__
  44949. #endif
  44950. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  44951. /*** Start of inlined file: juce_ImageCache.h ***/
  44952. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  44953. #define __JUCE_IMAGECACHE_JUCEHEADER__
  44954. /**
  44955. A global cache of images that have been loaded from files or memory.
  44956. If you're loading an image and may need to use the image in more than one
  44957. place, this is used to allow the same image to be shared rather than loading
  44958. multiple copies into memory.
  44959. Another advantage is that after images are released, they will be kept in
  44960. memory for a few seconds before it is actually deleted, so if you're repeatedly
  44961. loading/deleting the same image, it'll reduce the chances of having to reload it
  44962. each time.
  44963. @see Image, ImageFileFormat
  44964. */
  44965. class JUCE_API ImageCache
  44966. {
  44967. public:
  44968. /** Loads an image from a file, (or just returns the image if it's already cached).
  44969. If the cache already contains an image that was loaded from this file,
  44970. that image will be returned. Otherwise, this method will try to load the
  44971. file, add it to the cache, and return it.
  44972. Remember that the image returned is shared, so drawing into it might
  44973. affect other things that are using it! If you want to draw on it, first
  44974. call Image::duplicateIfShared()
  44975. @param file the file to try to load
  44976. @returns the image, or null if it there was an error loading it
  44977. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  44978. */
  44979. static const Image getFromFile (const File& file);
  44980. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  44981. If the cache already contains an image that was loaded from this block of memory,
  44982. that image will be returned. Otherwise, this method will try to load the
  44983. file, add it to the cache, and return it.
  44984. Remember that the image returned is shared, so drawing into it might
  44985. affect other things that are using it! If you want to draw on it, first
  44986. call Image::duplicateIfShared()
  44987. @param imageData the block of memory containing the image data
  44988. @param dataSize the data size in bytes
  44989. @returns the image, or an invalid image if it there was an error loading it
  44990. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  44991. */
  44992. static const Image getFromMemory (const void* imageData, int dataSize);
  44993. /** Checks the cache for an image with a particular hashcode.
  44994. If there's an image in the cache with this hashcode, it will be returned,
  44995. otherwise it will return an invalid image.
  44996. @param hashCode the hash code that was associated with the image by addImageToCache()
  44997. @see addImageToCache
  44998. */
  44999. static const Image getFromHashCode (int64 hashCode);
  45000. /** Adds an image to the cache with a user-defined hash-code.
  45001. The image passed-in will be referenced (not copied) by the cache, so it's probably
  45002. a good idea not to draw into it after adding it, otherwise this will affect all
  45003. instances of it that may be in use.
  45004. @param image the image to add
  45005. @param hashCode the hash-code to associate with it
  45006. @see getFromHashCode
  45007. */
  45008. static void addImageToCache (const Image& image, int64 hashCode);
  45009. /** Changes the amount of time before an unused image will be removed from the cache.
  45010. By default this is about 5 seconds.
  45011. */
  45012. static void setCacheTimeout (int millisecs);
  45013. juce_UseDebuggingNewOperator
  45014. private:
  45015. class Pimpl;
  45016. ImageCache();
  45017. ImageCache (const ImageCache&);
  45018. ImageCache& operator= (const ImageCache&);
  45019. ~ImageCache();
  45020. };
  45021. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  45022. /*** End of inlined file: juce_ImageCache.h ***/
  45023. #endif
  45024. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45025. /*** Start of inlined file: juce_ImageConvolutionKernel.h ***/
  45026. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45027. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45028. /**
  45029. Represents a filter kernel to use in convoluting an image.
  45030. @see Image::applyConvolution
  45031. */
  45032. class JUCE_API ImageConvolutionKernel
  45033. {
  45034. public:
  45035. /** Creates an empty convulution kernel.
  45036. @param size the length of each dimension of the kernel, so e.g. if the size
  45037. is 5, it will create a 5x5 kernel
  45038. */
  45039. ImageConvolutionKernel (int size);
  45040. /** Destructor. */
  45041. ~ImageConvolutionKernel();
  45042. /** Resets all values in the kernel to zero. */
  45043. void clear();
  45044. /** Returns one of the kernel values. */
  45045. float getKernelValue (int x, int y) const throw();
  45046. /** Sets the value of a specific cell in the kernel.
  45047. The x and y parameters must be in the range 0 < x < getKernelSize().
  45048. @see setOverallSum
  45049. */
  45050. void setKernelValue (int x, int y, float value) throw();
  45051. /** Rescales all values in the kernel to make the total add up to a fixed value.
  45052. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  45053. */
  45054. void setOverallSum (float desiredTotalSum);
  45055. /** Multiplies all values in the kernel by a value. */
  45056. void rescaleAllValues (float multiplier);
  45057. /** Intialises the kernel for a gaussian blur.
  45058. @param blurRadius this may be larger or smaller than the kernel's actual
  45059. size but this will obviously be wasteful or clip at the
  45060. edges. Ideally the kernel should be just larger than
  45061. (blurRadius * 2).
  45062. */
  45063. void createGaussianBlur (float blurRadius);
  45064. /** Returns the size of the kernel.
  45065. E.g. if it's a 3x3 kernel, this returns 3.
  45066. */
  45067. int getKernelSize() const { return size; }
  45068. /** Applies the kernel to an image.
  45069. @param destImage the image that will receive the resultant convoluted pixels.
  45070. @param sourceImage the source image to read from - this can be the same image as
  45071. the destination, but if different, it must be exactly the same
  45072. size and format.
  45073. @param destinationArea the region of the image to apply the filter to
  45074. */
  45075. void applyToImage (Image& destImage,
  45076. const Image& sourceImage,
  45077. const Rectangle<int>& destinationArea) const;
  45078. juce_UseDebuggingNewOperator
  45079. private:
  45080. HeapBlock <float> values;
  45081. const int size;
  45082. // no reason not to implement these one day..
  45083. ImageConvolutionKernel (const ImageConvolutionKernel&);
  45084. ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  45085. };
  45086. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45087. /*** End of inlined file: juce_ImageConvolutionKernel.h ***/
  45088. #endif
  45089. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45090. /*** Start of inlined file: juce_ImageFileFormat.h ***/
  45091. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45092. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45093. /**
  45094. Base-class for codecs that can read and write image file formats such
  45095. as PNG, JPEG, etc.
  45096. This class also contains static methods to make it easy to load images
  45097. from files, streams or from memory.
  45098. @see Image, ImageCache
  45099. */
  45100. class JUCE_API ImageFileFormat
  45101. {
  45102. protected:
  45103. /** Creates an ImageFormat. */
  45104. ImageFileFormat() {}
  45105. public:
  45106. /** Destructor. */
  45107. virtual ~ImageFileFormat() {}
  45108. /** Returns a description of this file format.
  45109. E.g. "JPEG", "PNG"
  45110. */
  45111. virtual const String getFormatName() = 0;
  45112. /** Returns true if the given stream seems to contain data that this format
  45113. understands.
  45114. The format class should only read the first few bytes of the stream and sniff
  45115. for header bytes that it understands.
  45116. @see decodeImage
  45117. */
  45118. virtual bool canUnderstand (InputStream& input) = 0;
  45119. /** Tries to decode and return an image from the given stream.
  45120. This will be called for an image format after calling its canUnderStand() method
  45121. to see if it can handle the stream.
  45122. @param input the stream to read the data from. The stream will be positioned
  45123. at the start of the image data (but this may not necessarily
  45124. be position 0)
  45125. @returns the image that was decoded, or an invalid image if it fails.
  45126. @see loadFrom
  45127. */
  45128. virtual const Image decodeImage (InputStream& input) = 0;
  45129. /** Attempts to write an image to a stream.
  45130. To specify extra information like encoding quality, there will be appropriate parameters
  45131. in the subclasses of the specific file types.
  45132. @returns true if it nothing went wrong.
  45133. */
  45134. virtual bool writeImageToStream (const Image& sourceImage,
  45135. OutputStream& destStream) = 0;
  45136. /** Tries the built-in decoders to see if it can find one to read this stream.
  45137. There are currently built-in decoders for PNG, JPEG and GIF formats.
  45138. The object that is returned should not be deleted by the caller.
  45139. @see canUnderstand, decodeImage, loadFrom
  45140. */
  45141. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  45142. /** Tries to load an image from a stream.
  45143. This will use the findImageFormatForStream() method to locate a suitable
  45144. codec, and use that to load the image.
  45145. @returns the image that was decoded, or an invalid image if it fails.
  45146. */
  45147. static const Image loadFrom (InputStream& input);
  45148. /** Tries to load an image from a file.
  45149. This will use the findImageFormatForStream() method to locate a suitable
  45150. codec, and use that to load the image.
  45151. @returns the image that was decoded, or an invalid image if it fails.
  45152. */
  45153. static const Image loadFrom (const File& file);
  45154. /** Tries to load an image from a block of raw image data.
  45155. This will use the findImageFormatForStream() method to locate a suitable
  45156. codec, and use that to load the image.
  45157. @returns the image that was decoded, or an invalid image if it fails.
  45158. */
  45159. static const Image loadFrom (const void* rawData,
  45160. const int numBytesOfData);
  45161. };
  45162. /**
  45163. A type of ImageFileFormat for reading and writing PNG files.
  45164. @see ImageFileFormat, JPEGImageFormat
  45165. */
  45166. class JUCE_API PNGImageFormat : public ImageFileFormat
  45167. {
  45168. public:
  45169. PNGImageFormat();
  45170. ~PNGImageFormat();
  45171. const String getFormatName();
  45172. bool canUnderstand (InputStream& input);
  45173. const Image decodeImage (InputStream& input);
  45174. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  45175. };
  45176. /**
  45177. A type of ImageFileFormat for reading and writing JPEG files.
  45178. @see ImageFileFormat, PNGImageFormat
  45179. */
  45180. class JUCE_API JPEGImageFormat : public ImageFileFormat
  45181. {
  45182. public:
  45183. JPEGImageFormat();
  45184. ~JPEGImageFormat();
  45185. /** Specifies the quality to be used when writing a JPEG file.
  45186. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  45187. any negative value is "default" quality
  45188. */
  45189. void setQuality (const float newQuality);
  45190. const String getFormatName();
  45191. bool canUnderstand (InputStream& input);
  45192. const Image decodeImage (InputStream& input);
  45193. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  45194. private:
  45195. float quality;
  45196. };
  45197. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45198. /*** End of inlined file: juce_ImageFileFormat.h ***/
  45199. #endif
  45200. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  45201. #endif
  45202. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45203. /*** Start of inlined file: juce_FileBasedDocument.h ***/
  45204. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45205. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45206. /**
  45207. A class to take care of the logic involved with the loading/saving of some kind
  45208. of document.
  45209. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  45210. functions you need for documents that get saved to a file, so this class attempts
  45211. to abstract most of the boring stuff.
  45212. Your subclass should just implement all the pure virtual methods, and you can
  45213. then use the higher-level public methods to do the load/save dialogs, to warn the user
  45214. about overwriting files, etc.
  45215. The document object keeps track of whether it has changed since it was last saved or
  45216. loaded, so when you change something, call its changed() method. This will set a
  45217. flag so it knows it needs saving, and will also broadcast a change message using the
  45218. ChangeBroadcaster base class.
  45219. @see ChangeBroadcaster
  45220. */
  45221. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  45222. {
  45223. public:
  45224. /** Creates a FileBasedDocument.
  45225. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  45226. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  45227. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  45228. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  45229. */
  45230. FileBasedDocument (const String& fileExtension,
  45231. const String& fileWildCard,
  45232. const String& openFileDialogTitle,
  45233. const String& saveFileDialogTitle);
  45234. /** Destructor. */
  45235. virtual ~FileBasedDocument();
  45236. /** Returns true if the changed() method has been called since the file was
  45237. last saved or loaded.
  45238. @see resetChangedFlag, changed
  45239. */
  45240. bool hasChangedSinceSaved() const { return changedSinceSave; }
  45241. /** Called to indicate that the document has changed and needs saving.
  45242. This method will also trigger a change message to be sent out using the
  45243. ChangeBroadcaster base class.
  45244. After calling the method, the hasChangedSinceSaved() method will return true, until
  45245. it is reset either by saving to a file or using the resetChangedFlag() method.
  45246. @see hasChangedSinceSaved, resetChangedFlag
  45247. */
  45248. virtual void changed();
  45249. /** Sets the state of the 'changed' flag.
  45250. The 'changed' flag is set to true when the changed() method is called - use this method
  45251. to reset it or to set it without also broadcasting a change message.
  45252. @see changed, hasChangedSinceSaved
  45253. */
  45254. void setChangedFlag (bool hasChanged);
  45255. /** Tries to open a file.
  45256. If the file opens correctly, the document's file (see the getFile() method) is set
  45257. to this new one; if it fails, the document's file is left unchanged, and optionally
  45258. a message box is shown telling the user there was an error.
  45259. @returns true if the new file loaded successfully
  45260. @see loadDocument, loadFromUserSpecifiedFile
  45261. */
  45262. bool loadFrom (const File& fileToLoadFrom,
  45263. bool showMessageOnFailure);
  45264. /** Asks the user for a file and tries to load it.
  45265. This will pop up a dialog box using the title, file extension and
  45266. wildcard specified in the document's constructor, and asks the user
  45267. for a file. If they pick one, the loadFrom() method is used to
  45268. try to load it, optionally showing a message if it fails.
  45269. @returns true if a file was loaded; false if the user cancelled or if they
  45270. picked a file which failed to load correctly
  45271. @see loadFrom
  45272. */
  45273. bool loadFromUserSpecifiedFile (bool showMessageOnFailure);
  45274. /** A set of possible outcomes of one of the save() methods
  45275. */
  45276. enum SaveResult
  45277. {
  45278. savedOk = 0, /**< indicates that a file was saved successfully. */
  45279. userCancelledSave, /**< indicates that the user aborted the save operation. */
  45280. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  45281. };
  45282. /** Tries to save the document to the last file it was saved or loaded from.
  45283. This will always try to write to the file, even if the document isn't flagged as
  45284. having changed.
  45285. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  45286. true, it will prompt the user to pick a file, as if
  45287. saveAsInteractive() was called.
  45288. @param showMessageOnFailure if true it will show a warning message when if the
  45289. save operation fails
  45290. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  45291. */
  45292. SaveResult save (bool askUserForFileIfNotSpecified,
  45293. bool showMessageOnFailure);
  45294. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  45295. it if they say yes.
  45296. If you've got a document open and want to close it (e.g. to quit the app), this is the
  45297. method to call.
  45298. If the document doesn't need saving it'll return the value savedOk so
  45299. you can go ahead and delete the document.
  45300. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  45301. return savedOk, so again, you can safely delete the document.
  45302. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  45303. close-document operation.
  45304. And if they click "save changes", it'll try to save and either return savedOk, or
  45305. failedToWriteToFile if there was a problem.
  45306. @see save, saveAs, saveAsInteractive
  45307. */
  45308. SaveResult saveIfNeededAndUserAgrees();
  45309. /** Tries to save the document to a specified file.
  45310. If this succeeds, it'll also change the document's internal file (as returned by
  45311. the getFile() method). If it fails, the file will be left unchanged.
  45312. @param newFile the file to try to write to
  45313. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  45314. the user first if they want to overwrite it
  45315. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  45316. use the saveAsInteractive() method to ask the user for a
  45317. filename
  45318. @param showMessageOnFailure if true and the write operation fails, it'll show
  45319. a message box to warn the user
  45320. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  45321. */
  45322. SaveResult saveAs (const File& newFile,
  45323. bool warnAboutOverwritingExistingFiles,
  45324. bool askUserForFileIfNotSpecified,
  45325. bool showMessageOnFailure);
  45326. /** Prompts the user for a filename and tries to save to it.
  45327. This will pop up a dialog box using the title, file extension and
  45328. wildcard specified in the document's constructor, and asks the user
  45329. for a file. If they pick one, the saveAs() method is used to try to save
  45330. to this file.
  45331. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  45332. the user first if they want to overwrite it
  45333. @see saveIfNeededAndUserAgrees, save, saveAs
  45334. */
  45335. SaveResult saveAsInteractive (bool warnAboutOverwritingExistingFiles);
  45336. /** Returns the file that this document was last successfully saved or loaded from.
  45337. When the document object is created, this will be set to File::nonexistent.
  45338. It is changed when one of the load or save methods is used, or when setFile()
  45339. is used to explicitly set it.
  45340. */
  45341. const File getFile() const { return documentFile; }
  45342. /** Sets the file that this document thinks it was loaded from.
  45343. This won't actually load anything - it just changes the file stored internally.
  45344. @see getFile
  45345. */
  45346. void setFile (const File& newFile);
  45347. protected:
  45348. /** Overload this to return the title of the document.
  45349. This is used in message boxes, filenames and file choosers, so it should be
  45350. something sensible.
  45351. */
  45352. virtual const String getDocumentTitle() = 0;
  45353. /** This method should try to load your document from the given file.
  45354. If it fails, it should return an error message. If it succeeds, it should return
  45355. an empty string.
  45356. */
  45357. virtual const String loadDocument (const File& file) = 0;
  45358. /** This method should try to write your document to the given file.
  45359. If it fails, it should return an error message. If it succeeds, it should return
  45360. an empty string.
  45361. */
  45362. virtual const String saveDocument (const File& file) = 0;
  45363. /** This is used for dialog boxes to make them open at the last folder you
  45364. were using.
  45365. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  45366. the last document that was used - you might want to store this value
  45367. in a static variable, or even in your application's properties. It should
  45368. be a global setting rather than a property of this object.
  45369. This method works very well in conjunction with a RecentlyOpenedFilesList
  45370. object to manage your recent-files list.
  45371. As a default value, it's ok to return File::nonexistent, and the document
  45372. object will use a sensible one instead.
  45373. @see RecentlyOpenedFilesList
  45374. */
  45375. virtual const File getLastDocumentOpened() = 0;
  45376. /** This is used for dialog boxes to make them open at the last folder you
  45377. were using.
  45378. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  45379. the last document that was used - you might want to store this value
  45380. in a static variable, or even in your application's properties. It should
  45381. be a global setting rather than a property of this object.
  45382. This method works very well in conjunction with a RecentlyOpenedFilesList
  45383. object to manage your recent-files list.
  45384. @see RecentlyOpenedFilesList
  45385. */
  45386. virtual void setLastDocumentOpened (const File& file) = 0;
  45387. public:
  45388. juce_UseDebuggingNewOperator
  45389. private:
  45390. File documentFile;
  45391. bool changedSinceSave;
  45392. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  45393. FileBasedDocument (const FileBasedDocument&);
  45394. FileBasedDocument& operator= (const FileBasedDocument&);
  45395. };
  45396. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45397. /*** End of inlined file: juce_FileBasedDocument.h ***/
  45398. #endif
  45399. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  45400. #endif
  45401. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45402. /*** Start of inlined file: juce_RecentlyOpenedFilesList.h ***/
  45403. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45404. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45405. /**
  45406. Manages a set of files for use as a list of recently-opened documents.
  45407. This is a handy class for holding your list of recently-opened documents, with
  45408. helpful methods for things like purging any non-existent files, automatically
  45409. adding them to a menu, and making persistence easy.
  45410. @see File, FileBasedDocument
  45411. */
  45412. class JUCE_API RecentlyOpenedFilesList
  45413. {
  45414. public:
  45415. /** Creates an empty list.
  45416. */
  45417. RecentlyOpenedFilesList();
  45418. /** Destructor. */
  45419. ~RecentlyOpenedFilesList();
  45420. /** Sets a limit for the number of files that will be stored in the list.
  45421. When addFile() is called, then if there is no more space in the list, the
  45422. least-recently added file will be dropped.
  45423. @see getMaxNumberOfItems
  45424. */
  45425. void setMaxNumberOfItems (int newMaxNumber);
  45426. /** Returns the number of items that this list will store.
  45427. @see setMaxNumberOfItems
  45428. */
  45429. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  45430. /** Returns the number of files in the list.
  45431. The most recently added file is always at index 0.
  45432. */
  45433. int getNumFiles() const;
  45434. /** Returns one of the files in the list.
  45435. The most recently added file is always at index 0.
  45436. */
  45437. const File getFile (int index) const;
  45438. /** Returns an array of all the absolute pathnames in the list.
  45439. */
  45440. const StringArray& getAllFilenames() const throw() { return files; }
  45441. /** Clears all the files from the list. */
  45442. void clear();
  45443. /** Adds a file to the list.
  45444. The file will be added at index 0. If this file is already in the list, it will
  45445. be moved up to index 0, but a file can only appear once in the list.
  45446. If the list already contains the maximum number of items that is permitted, the
  45447. least-recently added file will be dropped from the end.
  45448. */
  45449. void addFile (const File& file);
  45450. /** Checks each of the files in the list, removing any that don't exist.
  45451. You might want to call this after reloading a list of files, or before putting them
  45452. on a menu.
  45453. */
  45454. void removeNonExistentFiles();
  45455. /** Adds entries to a menu, representing each of the files in the list.
  45456. This is handy for creating an "open recent file..." menu in your app. The
  45457. menu items are numbered consecutively starting with the baseItemId value,
  45458. and can either be added as complete pathnames, or just the last part of the
  45459. filename.
  45460. If dontAddNonExistentFiles is true, then each file will be checked and only those
  45461. that exist will be added.
  45462. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  45463. pointers to file objects. Any files that appear in this list will not be added to the
  45464. menu - the reason for this is that you might have a number of files already open, so
  45465. might not want these to be shown in the menu.
  45466. It returns the number of items that were added.
  45467. */
  45468. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  45469. int baseItemId,
  45470. bool showFullPaths,
  45471. bool dontAddNonExistentFiles,
  45472. const File** filesToAvoid = 0);
  45473. /** Returns a string that encapsulates all the files in the list.
  45474. The string that is returned can later be passed into restoreFromString() in
  45475. order to recreate the list. This is handy for persisting your list, e.g. in
  45476. a PropertiesFile object.
  45477. @see restoreFromString
  45478. */
  45479. const String toString() const;
  45480. /** Restores the list from a previously stringified version of the list.
  45481. Pass in a stringified version created with toString() in order to persist/restore
  45482. your list.
  45483. @see toString
  45484. */
  45485. void restoreFromString (const String& stringifiedVersion);
  45486. juce_UseDebuggingNewOperator
  45487. private:
  45488. StringArray files;
  45489. int maxNumberOfItems;
  45490. };
  45491. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45492. /*** End of inlined file: juce_RecentlyOpenedFilesList.h ***/
  45493. #endif
  45494. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  45495. #endif
  45496. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45497. /*** Start of inlined file: juce_SystemClipboard.h ***/
  45498. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45499. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45500. /**
  45501. Handles reading/writing to the system's clipboard.
  45502. */
  45503. class JUCE_API SystemClipboard
  45504. {
  45505. public:
  45506. /** Copies a string of text onto the clipboard */
  45507. static void copyTextToClipboard (const String& text);
  45508. /** Gets the current clipboard's contents.
  45509. Obviously this might have come from another app, so could contain
  45510. anything..
  45511. */
  45512. static const String getTextFromClipboard();
  45513. };
  45514. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45515. /*** End of inlined file: juce_SystemClipboard.h ***/
  45516. #endif
  45517. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  45518. #endif
  45519. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  45520. #endif
  45521. #endif
  45522. /*** End of inlined file: juce_app_includes.h ***/
  45523. #endif
  45524. #if JUCE_MSVC
  45525. #pragma warning (pop)
  45526. #pragma pack (pop)
  45527. #endif
  45528. END_JUCE_NAMESPACE
  45529. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  45530. #ifdef JUCE_NAMESPACE
  45531. // this will obviously save a lot of typing, but can be disabled by
  45532. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  45533. using namespace JUCE_NAMESPACE;
  45534. /* On the Mac, these symbols are defined in the Mac libraries, so
  45535. these macros make it easier to reference them without writing out
  45536. the namespace every time.
  45537. If you run into difficulties where these macros interfere with the contents
  45538. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  45539. the comments in that file for more information.
  45540. */
  45541. #if (JUCE_MAC || JUCE_IPHONE) && ! JUCE_DONT_DEFINE_MACROS
  45542. #define Component JUCE_NAMESPACE::Component
  45543. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  45544. #define Point JUCE_NAMESPACE::Point
  45545. #define Button JUCE_NAMESPACE::Button
  45546. #endif
  45547. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  45548. it easier to use the juce version explicitly.
  45549. If you run into difficulties where this macro interferes with other 3rd party header
  45550. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  45551. file for more information.
  45552. */
  45553. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  45554. #define Rectangle JUCE_NAMESPACE::Rectangle
  45555. #endif
  45556. #endif
  45557. #endif
  45558. /* Easy autolinking to the right JUCE libraries under win32.
  45559. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  45560. including this header file.
  45561. */
  45562. #if JUCE_MSVC
  45563. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  45564. /** If you want your application to link to Juce as a DLL instead of
  45565. a static library (on win32), just define the JUCE_DLL macro before
  45566. including juce.h
  45567. */
  45568. #ifdef JUCE_DLL
  45569. #if JUCE_DEBUG
  45570. #define AUTOLINKEDLIB "JUCE_debug.lib"
  45571. #else
  45572. #define AUTOLINKEDLIB "JUCE.lib"
  45573. #endif
  45574. #else
  45575. #if JUCE_DEBUG
  45576. #ifdef _WIN64
  45577. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  45578. #else
  45579. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  45580. #endif
  45581. #else
  45582. #ifdef _WIN64
  45583. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  45584. #else
  45585. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  45586. #endif
  45587. #endif
  45588. #endif
  45589. #pragma comment(lib, AUTOLINKEDLIB)
  45590. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  45591. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  45592. #endif
  45593. // Auto-link the other win32 libs that are needed by library calls..
  45594. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  45595. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  45596. // Auto-links to various win32 libs that are needed by library calls..
  45597. #pragma comment(lib, "kernel32.lib")
  45598. #pragma comment(lib, "user32.lib")
  45599. #pragma comment(lib, "shell32.lib")
  45600. #pragma comment(lib, "gdi32.lib")
  45601. #pragma comment(lib, "vfw32.lib")
  45602. #pragma comment(lib, "comdlg32.lib")
  45603. #pragma comment(lib, "winmm.lib")
  45604. #pragma comment(lib, "wininet.lib")
  45605. #pragma comment(lib, "ole32.lib")
  45606. #pragma comment(lib, "oleaut32.lib")
  45607. #pragma comment(lib, "advapi32.lib")
  45608. #pragma comment(lib, "ws2_32.lib")
  45609. #pragma comment(lib, "comsupp.lib")
  45610. #pragma comment(lib, "version.lib")
  45611. #if JUCE_OPENGL
  45612. #pragma comment(lib, "OpenGL32.Lib")
  45613. #pragma comment(lib, "GlU32.Lib")
  45614. #endif
  45615. #if JUCE_QUICKTIME
  45616. #pragma comment (lib, "QTMLClient.lib")
  45617. #endif
  45618. #if JUCE_USE_CAMERA
  45619. #pragma comment (lib, "Strmiids.lib")
  45620. #pragma comment (lib, "wmvcore.lib")
  45621. #endif
  45622. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  45623. #endif
  45624. #endif
  45625. #endif
  45626. /*
  45627. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  45628. AppSubClass is the name of a class derived from JUCEApplication.
  45629. See the JUCEApplication class documentation (juce_Application.h) for more details.
  45630. */
  45631. #if defined (JUCE_GCC) || defined (__MWERKS__)
  45632. #define START_JUCE_APPLICATION(AppClass) \
  45633. int main (int argc, char* argv[]) \
  45634. { \
  45635. return JUCE_NAMESPACE::JUCEApplication::main (argc, (const char**) argv, new AppClass()); \
  45636. }
  45637. #elif JUCE_WINDOWS
  45638. #ifdef _CONSOLE
  45639. #define START_JUCE_APPLICATION(AppClass) \
  45640. int main (int, char* argv[]) \
  45641. { \
  45642. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  45643. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  45644. }
  45645. #elif ! defined (_AFXDLL)
  45646. #ifdef _WINDOWS_
  45647. #define START_JUCE_APPLICATION(AppClass) \
  45648. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  45649. { \
  45650. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  45651. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  45652. }
  45653. #else
  45654. #define START_JUCE_APPLICATION(AppClass) \
  45655. int __stdcall WinMain (int, int, const char*, int) \
  45656. { \
  45657. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  45658. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  45659. }
  45660. #endif
  45661. #endif
  45662. #endif
  45663. #endif // __JUCE_JUCEHEADER__
  45664. /*** End of inlined file: juce.h ***/
  45665. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__